<?php 
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("header.php");
require_once("../config/topup_helpers.php");

if (!(isset($_SESSION['customerid'])))
    header('Location:login.php?error=nologin');

ensureTopupSchema($con);

$dts = date("l jS \of F Y ");

// Update last login
$stmt = $con->prepare("UPDATE customers SET lastlogin=? WHERE customerid=?");
$stmt->bind_param("ss", $dts, $_SESSION['customerid']);
$stmt->execute();
$stmt->close();

// System Settings (for currency symbol)
$cur = '$';
$sbank = 'Default Bank';
$favicon = ''; 

if (isset($con) && $con instanceof mysqli) {
   $stmt = $con->prepare("SELECT bank_name, currency, favicon FROM system_settings LIMIT 1");
   if ($stmt) {
       $stmt->execute();
       $stmt->bind_result($bankname_db, $currency_db, $favicon_db);
       if($stmt->fetch()) {
           $sbank = $bankname_db ? $bankname_db : $sbank;
           $cur = $currency_db ? $currency_db : $cur;
           $favicon = $favicon_db;
       }
       $stmt->close();
   }
}

// Check for deposit (Logic from your snippet)
if (isset($_POST['deposit'])) {
    $now = $_POST['mone'];
    $lid = $_POST['lid'];
    $amt = $_POST['amt'];
    $dt = date("Y-m-d H:i:s");

    $stmt = $con->prepare("UPDATE accounts SET accountbalance = accountbalance + ? WHERE customerid=?");
    $stmt->bind_param("ds", $now, $_SESSION['customerid']);
    $stmt->execute();
    $stmt->close();

    $sql = $con->prepare("INSERT INTO loanpayment (customerid, loanid, paidamt, date) VALUES (?,?,?,?)");
    $sql->bind_param("sids", $_SESSION['customerid'], $lid, $amt, $dt);
    $sql->execute();
    $sql->close();

    echo "<script>window.location='dashboard.php';</script>";
    exit;
}
?>
  
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Transfer History | <?php echo $sbank ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php if (!empty($favicon)): ?>
      <link rel="icon" href="../<?= htmlspecialchars($favicon); ?>" type="image/<?= pathinfo($favicon, PATHINFO_EXTENSION); ?>">
    <?php endif; ?>
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="assets/libs/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css" />

    <style>
    :root {
        --primary-purple: #003399; 
        --soft-purple-bg: #e6efff;
        --bg-body: #f8fafc;
        --text-main: #0f172a;
        --text-secondary: #64748b;
    }

    body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-body); color: var(--text-main); }
    .page-content { padding-top: 80px; }

    /* --- MOBILE TABLE FIX: STOP THE PLUS ICON LIST --- */
    .table-rep-plugin { overflow-x: auto; -webkit-overflow-scrolling: touch; }
    .table-responsive { border-radius: 16px; border: 1px solid #f1f5f9; }
    
    table.dataTable { border: none !important; margin: 0 !important; }
    table.dataTable thead th { 
        background-color: #f1f5f9 !important; 
        color: #475569 !important; 
        font-size: 11px;
        text-transform: uppercase;
        padding: 12px 20px !important;
        white-space: nowrap;
    }
    table.dataTable tbody td { 
        padding: 15px 20px !important; 
        font-size: 13px; 
        border-bottom: 1px solid #f1f5f9;
        white-space: nowrap; /* Forces table to stay as a table, not a list */
        color: var(--text-main);
    }
    table.dataTable tbody tr:hover { background-color: #f0f7ff !important; cursor: pointer; }

    /* --- RECEIPT MODAL COLOR FIX --- */
    #receiptModal .modal-content { background-color: #ffffff !important; border-radius: 24px !important; border: none !important; }
    #receiptModal .modal-body { background-color: #ffffff !important; color: #0f172a !important; border-radius: 24px !important; }
    #receiptModal h2, #receiptModal h5, #receiptModal span, #receiptModal b { color: #0f172a !important; }
    #receiptModal .text-muted { color: #64748b !important; }
    #receiptModal .bg-light { background-color: #f8f9fa !important; border: 1px solid #e2e8f0 !important; }

    .card { border: none; border-radius: 24px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05); background: #fff; }
    .badge { padding: 6px 12px; border-radius: 50px; font-weight: 700; font-size: 0.7rem; }
    .bg-success-subtle { background-color: #dcfce7 !important; color: #166534 !important; }
    .bg-warning-subtle { background-color: #fef9c3 !important; color: #854d0e !important; }
    .bg-danger-subtle { background-color: #fee2e2 !important; color: #991b1b !important; }
    .text-purple { color: var(--primary-purple) !important; }
</style>
</head>

<body data-sidebar="colored">
    <div id="layout-wrapper">
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="d-flex align-items-center justify-content-between">
                                <div>
                                    <h4 class="mb-1 fw-bold text-dark">Transfer History</h4>
                                    <p class="text-secondary mb-0">Transfers and top ups are listed here. Swipe left/right to view full table on mobile.</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="datatable" class="table align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Transaction ID</th>
                                                    <th>Date</th>
                                                    <th>Beneficiary / Source</th>
                                                    <th>Channel</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $customerId = $_SESSION['customerid'];
                                                $customerIdInt = (int) $_SESSION['customerid'];
                                                $query = $con->prepare("
                                                    (SELECT id AS item_id, date AS item_date, receiver AS beneficiary, bank AS channel_name, amount, status, 'transfer' AS item_type, '' AS topup_reference
                                                     FROM transfers
                                                     WHERE sender = ?)
                                                    UNION ALL
                                                    (SELECT tr.id AS item_id, tr.created_at AS item_date, 'Top Up' AS beneficiary, pm.method_name AS channel_name, tr.amount, tr.status, 'topup' AS item_type, tr.reference AS topup_reference
                                                     FROM topup_requests tr
                                                     INNER JOIN payment_methods pm ON pm.id = tr.method_id
                                                     WHERE tr.customerid = ?)
                                                    ORDER BY item_date DESC
                                                ");
                                                $query->bind_param("si", $customerId, $customerIdInt);
                                                $query->execute();
                                                $rectrans = $query->get_result();

                                                while ($recs = $rectrans->fetch_assoc()) {
                                                    $isTopup = ($recs['item_type'] === 'topup');
                                                    $rawDate = $recs['item_date'];
                                                    $formattedDateForJS = date('d M Y h:i A', strtotime($rawDate));
                                                    if ($isTopup) {
                                                        $statusRaw = strtolower((string) $recs['status']);
                                                        if ($statusRaw === 'approved') {
                                                            $statusBadge = 'bg-success-subtle';
                                                            $statusText = 'Approved';
                                                        } elseif ($statusRaw === 'rejected') {
                                                            $statusBadge = 'bg-danger-subtle text-danger';
                                                            $statusText = 'Rejected';
                                                        } else {
                                                            $statusBadge = 'bg-warning-subtle';
                                                            $statusText = 'Pending';
                                                        }
                                                        $transLabel = '#' . ($recs['topup_reference'] !== '' ? $recs['topup_reference'] : ('TOPUP' . $recs['item_id']));
                                                        $amountDisplay = $statusRaw === 'approved'
                                                            ? '+' . $cur . number_format((float) $recs['amount'], 2)
                                                            : $cur . number_format((float) $recs['amount'], 2);
                                                        $receiptTitle = 'Top Up via ' . ($recs['channel_name'] ?: 'Payment Method');
                                                        $receiptType = 'Account Top Up';
                                                    } else {
                                                        $statusBadge = ($recs['status'] == '1') ? 'bg-success-subtle' : 'bg-warning-subtle';
                                                        $statusText = ($recs['status'] == '1') ? 'Successful' : 'Pending';
                                                        $transLabel = '#TRANS' . $recs['item_id'];
                                                        $amountDisplay = $cur . number_format((float) $recs['amount'], 2);
                                                        $receiptTitle = 'Transfer to ' . $recs['beneficiary'];
                                                        $receiptType = 'Online Transfer';
                                                    }

                                                    $onClick = "showReceipt("
                                                        . json_encode($receiptTitle) . ","
                                                        . json_encode($formattedDateForJS) . ","
                                                        . json_encode(number_format((float) $recs['amount'], 2)) . ","
                                                        . json_encode($statusText) . ","
                                                        . json_encode((string) $recs['channel_name']) . ","
                                                        . json_encode($transLabel) . ","
                                                        . json_encode($cur) . ","
                                                        . json_encode($receiptType)
                                                        . ")";

                                                    echo "<tr onclick='" . htmlspecialchars($onClick, ENT_QUOTES, 'UTF-8') . "'>
                                                        <td class='fw-bold text-primary'>" . htmlspecialchars($transLabel) . "</td>
                                                        <td>".date("M d, Y", strtotime($rawDate))."</td>
                                                        <td class='fw-bold'>".htmlspecialchars($recs['beneficiary'])."</td>
                                                        <td>".htmlspecialchars($recs['channel_name'])."</td>
                                                        <td class='fw-bold text-dark'>" . htmlspecialchars($amountDisplay) . "</td>
                                                        <td><span class='badge $statusBadge'>$statusText</span></td>
                                                    </tr>";
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'footer.php'; ?>
        </div>
    </div>

    <div class="modal fade" id="receiptModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body p-4 text-center">
                    <div id="receipt-icon-bg" style="width: 70px; height: 70px; background: #dcfce7; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px auto;">
                        <i class='bx bx-check text-success fs-1' id="receipt-icon"></i>
                    </div>
                    <h5 class="fw-bold mb-1" id="receipt-title">Transfer</h5>
                    <p class="text-muted small mb-4" id="receipt-date"></p>
                    <h2 class="fw-bold mb-2"><span id="receipt-currency"></span><span id="receipt-amount"></span></h2>
                    <div class="mb-4"><span class="badge rounded-pill" id="receipt-status-badge"></span></div>
                    <div class="bg-light p-3 rounded-4 text-start">
                        <div class="d-flex justify-content-between mb-2"><span class="text-muted small">Channel</span><span class="fw-bold small" id="receipt-bank"></span></div>
                        <div class="d-flex justify-content-between mb-2"><span class="text-muted small">Transaction ID</span><span class="fw-bold small" id="receipt-id"></span></div>
                        <div class="d-flex justify-content-between"><span class="text-muted small">Type</span><span class="fw-bold small" id="receipt-type">Online Transfer</span></div>
                    </div>
                    <button class="btn btn-dark rounded-pill w-100 mt-4 py-2 fw-bold" onclick="window.print()"><i class='bx bx-download me-2'></i> Download Receipt</button>
                    <button class="btn btn-link text-muted w-100 mt-1" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>

    <script>
    $(document).ready(function () {
        $('#datatable').DataTable({
            responsive: false, // Disables the "list mode" on mobile
            language: { search: "", searchPlaceholder: "Search history..." },
            dom: '<"row align-items-center mb-4"<"col-6"l><"col-6"f>>rtp',
            order: [[ 1, "desc" ]] 
        });
    });

    function showReceipt(title, date, amount, status, bank, id, cur, typeText) {
        document.getElementById('receipt-title').innerText = title;
        document.getElementById('receipt-date').innerText = date;
        document.getElementById('receipt-amount').innerText = amount;
        document.getElementById('receipt-currency').innerText = cur;
        document.getElementById('receipt-bank').innerText = bank;
        document.getElementById('receipt-id').innerText = id;
        document.getElementById('receipt-type').innerText = typeText || 'Online Transfer';
        const badge = document.getElementById('receipt-status-badge');
        const iconBg = document.getElementById('receipt-icon-bg');
        if(status === 'Successful' || status === 'Approved') {
            badge.innerText = status; badge.className = 'badge rounded-pill bg-success-subtle'; iconBg.style.background = '#dcfce7';
        } else if (status === 'Rejected') {
            badge.innerText = 'Rejected'; badge.className = 'badge rounded-pill bg-danger-subtle text-danger'; iconBg.style.background = '#fee2e2';
        } else {
            badge.innerText = 'Pending'; badge.className = 'badge rounded-pill bg-warning-subtle'; iconBg.style.background = '#fef9c3';
        }
        new bootstrap.Modal(document.getElementById('receiptModal')).show();
    }
    </script>
</body>
</html>