<?php
$pageName  = "Statement";

// ─── PDF GENERATION (handles form POST) ──────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Use output buffering: header.php will set up $conn, $user_id, $currency, etc.
    // but we capture and discard its HTML output
    ob_start();
    include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/header.php");
    ob_end_clean(); // Discard all HTML from header

    $from_date = $_POST['from_date'] ?? '';
    $to_date   = $_POST['to_date'] ?? '';

    // Validate
    if (empty($from_date) || empty($to_date) || !strtotime($from_date) || !strtotime($to_date)) {
        $_SESSION['error'] = 'Please select valid start and end dates.';
        header('Location: /user/statement.php');
        exit();
    }

    if ($from_date > $to_date) {
        $_SESSION['error'] = 'Start date must be before end date.';
        header('Location: /user/statement.php');
        exit();
    }

    $diff = (new DateTime($from_date))->diff(new DateTime($to_date));
    if ($diff->days > 366) {
        $_SESSION['error'] = 'Maximum statement period is 12 months.';
        header('Location: /user/statement.php');
        exit();
    }

    // ─── Query Transactions ──────────────────────────────────────
    try {
        $sql = "SELECT * FROM transactions 
                WHERE user_id = :user_id 
                AND DATE(created_at) BETWEEN :from_date AND :to_date 
                AND trans_status IN ('completed', 'Completed', 'success', 'Success', 'approved', 'Approved')
                ORDER BY created_at ASC";
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            'user_id'   => $user_id,
            'from_date' => $from_date,
            'to_date'   => $to_date,
        ]);
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $totalCredit = 0;
        $totalDebit  = 0;
        foreach ($transactions as $txn) {
            if ($txn['transaction_type'] === 'credit') {
                $totalCredit += $txn['amount'];
            } else {
                $totalDebit += $txn['amount'];
            }
        }

        // Opening balance
        $balSql = "SELECT 
                    COALESCE(SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END), 0) -
                    COALESCE(SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END), 0) as balance
                   FROM transactions 
                   WHERE user_id = :user_id 
                   AND DATE(created_at) < :from_date 
                   AND trans_status IN ('completed', 'Completed', 'success', 'Success', 'approved', 'Approved')";
        $balStmt = $conn->prepare($balSql);
        $balStmt->execute([
            'user_id'   => $user_id,
            'from_date' => $from_date,
        ]);
        $openingBalance = $balStmt->fetchColumn() ?: 0;
        $closingBalance = $openingBalance + $totalCredit - $totalDebit;

    } catch (PDOException $e) {
        error_log("Statement generation error: " . $e->getMessage());
        $_SESSION['error'] = 'An error occurred while generating your statement.';
        header('Location: /user/statement.php');
        exit();
    }

    // ─── Output Print-Ready HTML Statement ───────────────────────
$bankName    = $web_title ?? 'Bank';
$logoUrl     = ($web_url ?? '') . '/admin/assets/images/logo/' . htmlspecialchars($page['image']);
$acctNo      = $row['acct_no'] ?? '';
$acctType    = $row['acct_type'] ?? '';
$cur         = $currency ?? '$';
$fromDisplay = date('M d, Y', strtotime($from_date));
$toDisplay   = date('M d, Y', strtotime($to_date));
$generatedAt = date('M d, Y \a\t g:i A');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Account Statement - <?= htmlspecialchars($bankName) ?></title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            background: #f3f4f6;
            color: #0D1B23;
            font-size: 13px;
            line-height: 1.5;
        }

        .page-wrapper {
            max-width: 850px;
            margin: 0 auto;
            background: #fff;
        }

        /* ── Header ── */
        .stmt-header {
            background: linear-gradient(135deg, #0f3c32 0%, #1a5c4a 100%);
            color: #fff;
            padding: 28px 36px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .stmt-header .brand { display: flex; align-items: center; gap: 14px; }
        .stmt-header .brand img { height: 40px; width: auto; }
        .stmt-header .brand-text h1 { font-size: 20px; font-weight: 700; letter-spacing: -0.3px; }
        .stmt-header .brand-text p { font-size: 12px; opacity: 0.7; margin-top: 2px; }
        .stmt-header .period { text-align: right; font-size: 12px; opacity: 0.8; }
        .stmt-header .period strong { display: block; font-size: 13px; opacity: 1; margin-top: 4px; }

        /* ── Account Info ── */
        .acct-info {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
            padding: 24px 36px;
            background: #f8fafa;
            border-bottom: 1px solid #e0e5e5;
        }
        .acct-info .info-item label { font-size: 10px; color: #7a7a7a; text-transform: uppercase; letter-spacing: 0.5px; display: block; margin-bottom: 3px; }
        .acct-info .info-item span { font-size: 13px; font-weight: 600; color: #0D1B23; }

        /* ── Summary Cards ── */
        .summary-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
            padding: 24px 36px;
            border-bottom: 1px solid #e0e5e5;
        }
        .summary-card {
            background: #f8fafa;
            border: 1px solid #e0e5e5;
            border-radius: 8px;
            padding: 14px 16px;
        }
        .summary-card label { font-size: 10px; color: #7a7a7a; text-transform: uppercase; letter-spacing: 0.5px; display: block; margin-bottom: 6px; }
        .summary-card .value { font-size: 16px; font-weight: 700; }
        .summary-card .value.credit { color: #22c55e; }
        .summary-card .value.debit { color: #D55672; }

        /* ── Table ── */
        .stmt-table-wrap { padding: 0 36px 24px; }
        .stmt-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .stmt-table thead th {
            background: #0f3c32;
            color: #fff;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.4px;
            padding: 10px 12px;
            text-align: left;
        }
        .stmt-table thead th:nth-child(n+4) { text-align: right; }
        .stmt-table thead th:first-child { border-radius: 6px 0 0 0; }
        .stmt-table thead th:last-child { border-radius: 0 6px 0 0; }
        .stmt-table tbody tr { border-bottom: 1px solid #f0f2f2; }
        .stmt-table tbody tr:nth-child(even) { background: #fafbfb; }
        .stmt-table tbody td { padding: 9px 12px; font-size: 12px; }
        .stmt-table tbody td:nth-child(n+4) { text-align: right; }
        .stmt-table .credit-text { color: #22c55e; font-weight: 600; }
        .stmt-table .debit-text { color: #D55672; font-weight: 600; }
        .stmt-table .balance-text { font-weight: 700; color: #0D1B23; }
        .stmt-table .type-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 10px;
            font-weight: 600;
        }
        .stmt-table .type-badge.credit { background: #dcfce7; color: #16a34a; }
        .stmt-table .type-badge.debit { background: #fde8ec; color: #D55672; }

        /* ── Closing Bar ── */
        .closing-bar {
            background: #0f3c32;
            color: #fff;
            padding: 12px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 0 0 6px 6px;
            font-size: 13px;
            font-weight: 700;
            margin: 0 36px;
        }

        /* ── Footer ── */
        .stmt-footer {
            text-align: center;
            padding: 28px 36px;
            border-top: 1px solid #e0e5e5;
            margin-top: 24px;
        }
        .stmt-footer p { font-size: 11px; color: #7a7a7a; margin-bottom: 3px; }
        .stmt-footer .copy { font-size: 10px; color: #c8d1d1; margin-top: 8px; }

        /* ── Empty State ── */
        .empty-state { text-align: center; padding: 48px 36px; color: #7a7a7a; }
        .empty-state p { font-size: 14px; }

        /* ── Action Bar (no print) ── */
        .action-bar {
            max-width: 850px;
            margin: 20px auto;
            display: flex;
            justify-content: center;
            gap: 12px;
            padding: 0 36px;
        }
        .action-bar button, .action-bar a {
            padding: 10px 24px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            border: none;
            transition: background 0.2s;
        }
        .btn-print { background: #0f3c32; color: #fff; }
        .btn-print:hover { background: #1a5c4a; }
        .btn-back { background: #fff; color: #4a4a4a; border: 1px solid #e0e5e5 !important; }
        .btn-back:hover { background: #f3f4f6; }

        /* ── Print Styles ── */
        @media print {
            body { background: #fff; }
            .action-bar { display: none !important; }
            .page-wrapper { box-shadow: none; max-width: 100%; }
            .stmt-header { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .stmt-table thead th { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .closing-bar { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .summary-card { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .stmt-table tbody tr:nth-child(even) { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            @page { margin: 10mm 8mm; size: A4; }
        }
    </style>
</head>
<body>

    <!-- Action Buttons -->
    <div class="action-bar">
        <button class="btn-print" onclick="window.print()">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
            Print / Save as PDF
        </button>
        <a href="/user/statement.php" class="btn-back">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
            Back
        </a>
    </div>

    <div class="page-wrapper">

        <!-- Header -->
        <div class="stmt-header">
            <div class="brand">
                <img src="<?= htmlspecialchars($logoUrl) ?>" alt="<?= htmlspecialchars($bankName) ?>" onerror="this.style.display='none'">
                <div class="brand-text">
                    <h1><?= htmlspecialchars($bankName) ?></h1>
                    <p>Account Statement</p>
                </div>
            </div>
            <div class="period">
                Statement Period
                <strong><?= $fromDisplay ?> &mdash; <?= $toDisplay ?></strong>
            </div>
        </div>

        <!-- Account Info -->
        <div class="acct-info">
            <div class="info-item">
                <label>Account Holder</label>
                <span><?= htmlspecialchars($fullName ?? '') ?></span>
            </div>
            <div class="info-item">
                <label>Account Number</label>
                <span><?= htmlspecialchars($acctNo) ?></span>
            </div>
            <div class="info-item">
                <label>Account Type</label>
                <span><?= htmlspecialchars($acctType) ?></span>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="summary-row">
            <div class="summary-card">
                <label>Opening Balance</label>
                <div class="value"><?= $cur ?><?= number_format($openingBalance, 2, '.', ',') ?></div>
            </div>
            <div class="summary-card">
                <label>Total Credits</label>
                <div class="value credit">+<?= $cur ?><?= number_format($totalCredit, 2, '.', ',') ?></div>
            </div>
            <div class="summary-card">
                <label>Total Debits</label>
                <div class="value debit">-<?= $cur ?><?= number_format($totalDebit, 2, '.', ',') ?></div>
            </div>
            <div class="summary-card">
                <label>Closing Balance</label>
                <div class="value"><?= $cur ?><?= number_format($closingBalance, 2, '.', ',') ?></div>
            </div>
        </div>

        <!-- Transactions Table -->
        <div class="stmt-table-wrap">
            <?php if (count($transactions) === 0) { ?>
                <div class="empty-state">
                    <p>No transactions found for the selected period.</p>
                </div>
            <?php } else { ?>
                <table class="stmt-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Description</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $runningBalance = $openingBalance;
                        foreach ($transactions as $txn) {
                            $isCredit = $txn['transaction_type'] === 'credit';
                            $runningBalance += $isCredit ? $txn['amount'] : -$txn['amount'];

                            $desc = htmlspecialchars($txn['trans_type'] ?? '');
                            if (!empty($txn['description'])) {
                                $desc .= ' &mdash; ' . htmlspecialchars($txn['description']);
                            }
                        ?>
                        <tr>
                            <td><?= date('M d, Y', strtotime($txn['created_at'])) ?></td>
                            <td><?= $desc ?></td>
                            <td><span class="type-badge <?= $isCredit ? 'credit' : 'debit' ?>"><?= $isCredit ? 'Credit' : 'Debit' ?></span></td>
                            <td class="<?= $isCredit ? 'credit-text' : 'debit-text' ?>">
                                <?= $isCredit ? '+' : '-' ?><?= $cur ?><?= number_format($txn['amount'], 2, '.', ',') ?>
                            </td>
                            <td class="balance-text"><?= $cur ?><?= number_format($runningBalance, 2, '.', ',') ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>

                <!-- Closing Balance Bar -->
                <div class="closing-bar">
                    <span>Closing Balance</span>
                    <span><?= $cur ?><?= number_format($closingBalance, 2, '.', ',') ?></span>
                </div>
            <?php } ?>
        </div>

        <!-- Footer -->
        <div class="stmt-footer">
            <p>This is a computer-generated statement and does not require a signature.</p>
            <p>For any issues or inquiries, please contact support.</p>
            <p style="font-size:10px; color:#aaa; margin-top:6px;">
                Total transactions: <?= count($transactions) ?> &nbsp;|&nbsp; 
                Generated on <?= $generatedAt ?>
            </p>
            <p class="copy">&copy; <?= date('Y') ?> <?= htmlspecialchars($bankName) ?>. All rights reserved.</p>
        </div>

    </div>

    <script>
        // Auto-trigger print dialog on load
        window.onload = function() {
            // Small delay to ensure everything renders
            setTimeout(function() {
                window.print();
            }, 500);
        };
    </script>
</body>
</html>
<?php
    exit(); // Stop here — don't render the form below
}

// ─── FORM DISPLAY (GET request) ──────────────────────────────────
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/header.php");

$today     = date('Y-m-d');
$last30    = date('Y-m-d', strtotime('-30 days'));
$last7     = date('Y-m-d', strtotime('-7 days'));
$last3m    = date('Y-m-d', strtotime('-3 months'));
$last6m    = date('Y-m-d', strtotime('-6 months'));
$last12m   = date('Y-m-d', strtotime('-12 months'));
$yearStart = date('Y') . '-01-01';

$error = $_SESSION['error'] ?? '';
unset($_SESSION['error']);
?>
    <!-- Main Content Area -->
    <main class="pt-10 md:pt-14 pb-24 md:pb-8 min-h-screen lg:ml-80">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            
<div class="space-y-6">

    <!-- Page Header -->
    <div>
        <h1 class="text-2xl font-semibold text-[#0D1B23] mb-1">Account Statement</h1>
        <p class="text-sm text-[#7A7A7A]">Generate and download an official statement of your account transactions</p>
    </div>

    <!-- Error Message -->
    <?php if (!empty($error)) { ?>
    <div class="bg-red-50 border border-red-200 rounded-xl p-4 flex items-center gap-3">
        <i data-lucide="alert-circle" class="w-5 h-5 text-red-500 flex-shrink-0"></i>
        <p class="text-sm text-red-600"><?= htmlspecialchars($error) ?></p>
    </div>
    <?php } ?>

    <!-- Statement Form Card -->
    <div class="bg-white border border-[#E0E5E5] rounded-2xl overflow-hidden shadow-sm">
        
        <!-- Card Header -->
        <div class="px-6 py-5 border-b border-[#E0E5E5]">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-lg bg-primary-500/10 flex items-center justify-center">
                    <i data-lucide="file-text" class="w-5 h-5 text-primary-500"></i>
                </div>
                <div>
                    <h2 class="text-lg font-semibold text-[#0D1B23]">Generate Statement</h2>
                    <p class="text-xs text-[#7A7A7A]">Select a date range to generate your account statement</p>
                </div>
            </div>
        </div>

        <!-- Form posts to itself -->
        <form action="" method="POST" class="p-6">
            <input type="hidden" name="_token" value="<?= $_SESSION['_token'] ?? '' ?>">
            
            <!-- Account Info Preview -->
            <div class="bg-[#F9F9F9] rounded-xl p-5 mb-6 border border-[#E0E5E5]">
                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div>
                        <p class="text-xs text-[#7A7A7A] mb-1">Account Holder</p>
                        <p class="text-sm font-medium text-[#0D1B23]"><?= htmlspecialchars($fullName) ?></p>
                    </div>
                    <div>
                        <p class="text-xs text-[#7A7A7A] mb-1">Account Number</p>
                        <p class="text-sm font-medium text-[#0D1B23]"><?= htmlspecialchars($row['acct_no'] ?? '') ?></p>
                    </div>
                    <div>
                        <p class="text-xs text-[#7A7A7A] mb-1">Account Type</p>
                        <p class="text-sm font-medium text-[#0D1B23]"><?= htmlspecialchars($row['acct_type'] ?? '') ?></p>
                    </div>
                </div>
            </div>

            <!-- Date Range -->
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-5 mb-6">
                <div>
                    <label for="from_date" class="block text-sm font-medium text-[#4A4A4A] mb-2">From Date</label>
                    <input 
                        type="date" 
                        id="from_date" 
                        name="from_date" 
                        value="<?= $last30 ?>"
                        max="<?= $today ?>"
                        required
                        class="w-full px-4 py-3 bg-white border border-[#E0E5E5] rounded-xl text-sm text-[#0D1B23] focus:border-primary-500 focus:ring-1 focus:ring-primary-500/20 transition-colors"
                    >
                </div>
                <div>
                    <label for="to_date" class="block text-sm font-medium text-[#4A4A4A] mb-2">To Date</label>
                    <input 
                        type="date" 
                        id="to_date" 
                        name="to_date" 
                        value="<?= $today ?>"
                        max="<?= $today ?>"
                        required
                        class="w-full px-4 py-3 bg-white border border-[#E0E5E5] rounded-xl text-sm text-[#0D1B23] focus:border-primary-500 focus:ring-1 focus:ring-primary-500/20 transition-colors"
                    >
                </div>
            </div>

            <!-- Quick Select Buttons -->
            <div class="mb-6">
                <p class="text-xs text-[#7A7A7A] mb-3">Quick select</p>
                <div class="flex flex-wrap gap-2">
                    <button type="button" onclick="document.getElementById('from_date').value='<?= $last7 ?>'; document.getElementById('to_date').value='<?= $today ?>';"
                        class="px-3 py-1.5 text-xs font-medium rounded-lg border border-[#E0E5E5] bg-white text-[#4A4A4A] hover:bg-[#DFE5E5] hover:text-[#0D1B23] transition-colors">
                        Last 7 Days
                    </button>
                    <button type="button" onclick="document.getElementById('from_date').value='<?= $last30 ?>'; document.getElementById('to_date').value='<?= $today ?>';"
                        class="px-3 py-1.5 text-xs font-medium rounded-lg border border-[#E0E5E5] bg-white text-[#4A4A4A] hover:bg-[#DFE5E5] hover:text-[#0D1B23] transition-colors">
                        Last 30 Days
                    </button>
                    <button type="button" onclick="document.getElementById('from_date').value='<?= $last3m ?>'; document.getElementById('to_date').value='<?= $today ?>';"
                        class="px-3 py-1.5 text-xs font-medium rounded-lg border border-[#E0E5E5] bg-white text-[#4A4A4A] hover:bg-[#DFE5E5] hover:text-[#0D1B23] transition-colors">
                        Last 3 Months
                    </button>
                    <button type="button" onclick="document.getElementById('from_date').value='<?= $last6m ?>'; document.getElementById('to_date').value='<?= $today ?>';"
                        class="px-3 py-1.5 text-xs font-medium rounded-lg border border-[#E0E5E5] bg-white text-[#4A4A4A] hover:bg-[#DFE5E5] hover:text-[#0D1B23] transition-colors">
                        Last 6 Months
                    </button>
                    <button type="button" onclick="document.getElementById('from_date').value='<?= $yearStart ?>'; document.getElementById('to_date').value='<?= $today ?>';"
                        class="px-3 py-1.5 text-xs font-medium rounded-lg border border-[#E0E5E5] bg-white text-[#4A4A4A] hover:bg-[#DFE5E5] hover:text-[#0D1B23] transition-colors">
                        Year to Date
                    </button>
                    <button type="button" onclick="document.getElementById('from_date').value='<?= $last12m ?>'; document.getElementById('to_date').value='<?= $today ?>';"
                        class="px-3 py-1.5 text-xs font-medium rounded-lg border border-[#E0E5E5] bg-white text-[#4A4A4A] hover:bg-[#DFE5E5] hover:text-[#0D1B23] transition-colors">
                        Last 12 Months
                    </button>
                </div>
            </div>

            <!-- Submit Button -->
            <button type="submit" class="w-full sm:w-auto px-8 py-3 bg-primary-500 hover:bg-primary-600 text-white font-semibold rounded-xl transition-colors flex items-center justify-center gap-2">
                <i data-lucide="download" class="w-4 h-4"></i>
                Download Statement (PDF)
            </button>
        </form>
    </div>

    <!-- Info Card -->
    <div class="bg-white border border-[#E0E5E5] rounded-xl p-5">
        <div class="flex items-start gap-3">
            <i data-lucide="info" class="w-5 h-5 text-[#7A7A7A] flex-shrink-0 mt-0.5"></i>
            <div class="text-sm text-[#7A7A7A] space-y-1">
                <p>Your statement includes all <strong class="text-[#4A4A4A]">processed</strong> credits, debits, and deposits within the selected dates.</p>
                <p>Pending or rejected transactions are not included. Maximum period is 12 months per statement.</p>
            </div>
        </div>
    </div>

</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(() => lucide.createIcons(), 100);
    });
</script>

        </div>
    </main>

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/footer.php");
?>