<?php
session_start();
error_reporting(0);
include("header.php");
require_once("../config/topup_helpers.php");
ensureTopupSchema($con);

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

// Get account details
$result = $con->prepare("SELECT * FROM accounts WHERE customerid = ?");
$result->bind_param("s", $_SESSION['customerid']);
$result->execute();
$rowrec = $result->get_result()->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title> Statement of Account | <?php echo $sbank ?> </title>
    <meta charset="UTF-8">
    <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="https://cdnjs.cloudflare.com/ajax/libs/datatables.net-bs5/1.13.6/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/datatables.net-responsive-bs5/2.5.0/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/datatables.net-buttons-bs5/2.4.1/buttons.bootstrap5.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">

   <style>
    :root {
        --primary-purple: #003399;
        --dark-purple: #005D9D;
        --deep-bg: #001a4d;
        --soft-purple-bg: #e6efff;
        --bg-body: #f8fafc;
        --card-surface: #ffffff;
        --text-main: #0f172a;
        --text-secondary: #64748b;
        --border-light: #e2e8f0;
        --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1);
    }

    body { background-color: var(--bg-body); font-family: 'Plus Jakarta Sans', sans-serif; color: var(--text-main); }
    .statement-card { background: white; border-radius: 24px; border: none; overflow: hidden; box-shadow: var(--shadow-lg); margin-bottom: 30px; }
    .card-header-modern { background: linear-gradient(135deg, var(--deep-bg) 0%, var(--primary-purple) 100%); padding: 40px; color: white; position: relative; }
    .account-info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 25px; }
    .acc-detail-item { background: rgba(255,255,255,0.1); backdrop-filter: blur(5px); padding: 15px 20px; border-radius: 16px; border: 1px solid rgba(255,255,255,0.15); }
    .acc-label { font-size: 0.75rem; text-transform: uppercase; opacity: 0.8; margin-bottom: 5px; font-weight: 600; }
    .acc-value { font-size: 1.1rem; font-weight: 700; color: white; }
    .table-modern thead th { background-color: var(--soft-purple-bg); color: var(--primary-purple); font-weight: 700; text-transform: uppercase; font-size: 0.8rem; padding: 15px; }
    .transaction-id { font-family: 'Courier New', monospace; background: var(--bg-body); padding: 4px 8px; border-radius: 6px; color: var(--text-secondary); font-size: 0.85rem; font-weight: 600; }
    .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">Statement of Account</h4>
                                    <p class="text-secondary mb-0">Combined history of your transactions and transfers.</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row pb-5">
                        <div class="col-12">
                            <div class="statement-card">
                                <div class="card-header-modern">
                                    <h2 class="fw-bold mb-1">Transaction History</h2>
                                    <div class="account-info-grid">
                                        <div class="acc-detail-item">
                                            <div class="acc-label">Account Holder</div>
                                            <div class="acc-value"><?php echo htmlspecialchars($_SESSION['customername']); ?></div>
                                        </div>
                                        <div class="acc-detail-item">
                                            <div class="acc-label">Account Number</div>
                                            <div class="acc-value">**** <?php echo substr($rowrec['accno'], -4); ?></div>
                                        </div>
                                        <div class="acc-detail-item">
                                            <div class="acc-label">Current Balance</div>
                                            <div class="acc-value"><?php echo $cur . number_format($rowrec['accountbalance'] ?? 0, 2); ?></div>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="transactions-table" class="table table-modern align-middle" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>ID</th>
                                                    <th>Type</th>
                                                    <th>Description</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $customid = $_SESSION['customerid'];
                                                
                                                // MERGED QUERY: Transactions + Transfers + Top ups
                                                $query = "
                                                    (SELECT paymentdate as t_date, transactionid as t_id, amount as t_amount, paymentstat as t_status, payeeid, receiveid, charged, 'GENERAL' as source, '' as extra_bank FROM transactions WHERE payeeid = ? OR receiveid = ? OR charged = ?)
                                                    UNION ALL
                                                    (SELECT date as t_date, id as t_id, amount as t_amount, status as t_status, sender as payeeid, receiver as receiveid, '' as charged, 'TRANSFER' as source, bank as extra_bank FROM transfers WHERE sender = ?)
                                                    UNION ALL
                                                    (SELECT tr.created_at as t_date, tr.id as t_id, tr.amount as t_amount, tr.status as t_status, CAST(tr.customerid AS CHAR) as payeeid, tr.reference as receiveid, '' as charged, 'TOPUP' as source, pm.method_name as extra_bank FROM topup_requests tr INNER JOIN payment_methods pm ON pm.id = tr.method_id WHERE tr.customerid = ?)
                                                    ORDER BY UNIX_TIMESTAMP(t_date) DESC";

                                                $stmt = $con->prepare($query);
                                                $cidTop = (int) $customid;
                                                $stmt->bind_param("ssssi", $customid, $customid, $customid, $customid, $cidTop);
                                                $stmt->execute();
                                                $result = $stmt->get_result();

                                                while ($row = $result->fetch_assoc()) {
                                                    $date = date("d M Y h:i A", strtotime($row['t_date']));
                                                    $amount = floatval($row['t_amount']);
                                                    $formattedAmount = number_format($amount, 2);
                                                    
                                                    // Default values
                                                    $typeLabel = 'Transaction';
                                                    $description = 'General Transaction';
                                                    $amountDisplay = $cur . $formattedAmount;
                                                    $statusRaw = strtolower($row['t_status']);

                                                    if ($row['source'] === 'TRANSFER') {
                                                        // Data from transfers table
                                                        $typeLabel = 'Transfer';
                                                        $description = "Transfer to " . htmlspecialchars($row['receiveid']) . " (" . htmlspecialchars($row['extra_bank']) . ")";
                                                        $amountDisplay = '-' . $cur . $formattedAmount;
                                                        $transactionId = "#TRANS" . $row['t_id'];
                                                        $statusHtml = ($statusRaw == '1') ? "<span class='badge badge-soft-success'>Successful</span>" : "<span class='badge bg-warning'>Pending</span>";
                                                    } elseif ($row['source'] === 'TOPUP') {
                                                        $typeLabel = 'Top Up';
                                                        $ref = htmlspecialchars((string) $row['receiveid']);
                                                        $methodName = htmlspecialchars((string) $row['extra_bank']);
                                                        $description = 'Top up request via ' . $methodName . ($ref !== '' ? ' (Ref: ' . $ref . ')' : '');
                                                        $transactionId = $ref !== '' ? '#' . $ref : '#TUP' . $row['t_id'];
                                                        if ($statusRaw === 'approved') {
                                                            $amountDisplay = '+' . $cur . $formattedAmount;
                                                            $statusHtml = "<span class='badge badge-soft-success'>Approved</span>";
                                                        } elseif ($statusRaw === 'rejected') {
                                                            $amountDisplay = $cur . $formattedAmount;
                                                            $statusHtml = "<span class='badge bg-danger'>Rejected</span>";
                                                        } else {
                                                            $amountDisplay = $cur . $formattedAmount;
                                                            $statusHtml = "<span class='badge bg-warning'>Pending</span>";
                                                        }
                                                    } else {
                                                        // Data from transactions table
                                                        $transactionId = "#TRX" . date('His', strtotime($row['t_date'])) . $row['t_id'];
                                                        
                                                        if ((string)$row['charged'] === (string)$customid) {
                                                            $typeLabel = 'Charge';
                                                            $description = 'Account Maintenance Fee';
                                                            $amountDisplay = '-' . $cur . $formattedAmount;
                                                        } elseif ((string)$row['payeeid'] === (string)$customid) {
                                                            $typeLabel = 'Withdrawal';
                                                            $description = "Outward Payment";
                                                            $amountDisplay = '-' . $cur . $formattedAmount;
                                                        } else {
                                                            $typeLabel = 'Deposit';
                                                            $description = "Deposit to Account";
                                                            $amountDisplay = '+' . $cur . $formattedAmount;
                                                        }

                                                        switch ($statusRaw) {
                                                            case 'pending': $statusHtml = "<span class='badge bg-warning'>Pending</span>"; break;
                                                            case 'failed': $statusHtml = "<span class='badge bg-danger'>Failed</span>"; break;
                                                            default: $statusHtml = "<span class='badge badge-soft-success'>Completed</span>"; break;
                                                        }
                                                    }

                                                    echo "<tr>
                                                        <td>" . htmlspecialchars($date) . "</td>
                                                        <td><span class='transaction-id'>" . htmlspecialchars($transactionId) . "</span></td>
                                                        <td>" . htmlspecialchars(strtoupper($typeLabel)) . "</td>
                                                        <td>" . $description . "</td>
                                                        <td class='fw-bold'>" . $amountDisplay . "</td>
                                                        <td>" . $statusHtml . "</td>
                                                    </tr>";
                                                }
                                                $stmt->close();
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'footer.php'; ?>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

   <script>
    $(document).ready(function() {
        $('#transactions-table').DataTable({
            responsive: true,
            pageLength: 25,
            order: [[0, 'desc']],
            dom: '<"row mb-3"<"col-md-6"l><"col-md-6"f>>rt<"row mt-3"<"col-md-6"i><"col-md-6"p>>B',
            buttons: [
                { extend: 'excel', text: 'Excel', className: 'btn btn-light btn-sm' },
                { extend: 'pdf', text: 'PDF', className: 'btn btn-light btn-sm' },
                { extend: 'print', text: 'Print', className: 'btn btn-light btn-sm' }
            ]
        });
    });
</script>
    <script src="assets/js/app.js"></script>
</body>
</html>