<?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");

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

$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; }
    .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">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</th>
                                                    <th>Bank</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $query = $con->prepare("SELECT * FROM transfers WHERE sender=?");
                                                $query->bind_param("s", $_SESSION['customerid']);
                                                $query->execute();
                                                $rectrans = $query->get_result();

                                                while ($recs = $rectrans->fetch_assoc()) {
                                                    $transid = $recs['id'];
                                                    $rawDate = $recs['date'];
                                                    $formattedDateForJS = date('d M Y h:i A', strtotime($rawDate));
                                                    $statusBadge = ($recs['status'] == '1') ? 'bg-success-subtle' : 'bg-warning-subtle';
                                                    $statusText = ($recs['status'] == '1') ? 'Successful' : 'Pending';

                                                    echo "<tr onclick=\"showReceipt('".htmlspecialchars($recs['receiver'])."', '$formattedDateForJS', '".number_format($recs['amount'], 2)."', '$statusText', '".htmlspecialchars($recs['bank'])."', '$transid', '$cur')\">
                                                        <td class='fw-bold text-primary'>#TRANS$transid</td>
                                                        <td>".date("M d, Y", strtotime($rawDate))."</td>
                                                        <td class='fw-bold'>".htmlspecialchars($recs['receiver'])."</td>
                                                        <td>".htmlspecialchars($recs['bank'])."</td>
                                                        <td class='fw-bold text-dark'>$cur".number_format($recs['amount'], 2)."</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">Bank Name</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">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(receiver, date, amount, status, bank, id, cur) {
        document.getElementById('receipt-title').innerText = 'Transfer to ' + receiver;
        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 = '#TRANS' + id;
        const badge = document.getElementById('receipt-status-badge');
        const iconBg = document.getElementById('receipt-icon-bg');
        if(status === 'Successful') {
            badge.innerText = 'Successful'; badge.className = 'badge rounded-pill bg-success-subtle'; iconBg.style.background = '#dcfce7';
        } 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>