<?php
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Get date filters
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-t');
$currency_filter = isset($_GET['currency']) ? $_GET['currency'] : 'all';

// Fetch visa applications within date range
$sql = "SELECT 
            va.*,
            u_created.full_name as created_by_name,
            CASE 
                WHEN va.care_of IS NOT NULL THEN va.care_of 
                ELSE u_created.full_name 
            END as processed_by
        FROM visa_applications va
        LEFT JOIN users u_created ON va.created_by = u_created.user_id
        WHERE va.created_at BETWEEN ? AND ?";

if ($currency_filter !== 'all') {
    $sql .= " AND va.currency = ?";
}

$stmt = $conn->prepare($sql);

if ($currency_filter !== 'all') {
    $stmt->bind_param("sss", $start_date, $end_date, $currency_filter);
} else {
    $stmt->bind_param("ss", $start_date, $end_date);
}

$stmt->execute();
$result = $stmt->get_result();

// Calculate totals
$totals = [
    'USD' => [
        'total_amount' => 0, 
        'total_payment' => 0, 
        'total_commission' => 0, 
        'count' => 0,
        'status_counts' => [
            'Pending' => 0,
            'Processing' => 0,
            'Completed' => 0,
            'Cancelled' => 0
        ]
    ],
    'KES' => [
        'total_amount' => 0, 
        'total_payment' => 0, 
        'total_commission' => 0, 
        'count' => 0,
        'status_counts' => [
            'Pending' => 0,
            'Processing' => 0,
            'Completed' => 0,
            'Cancelled' => 0
        ]
    ]
];

$visas = [];
while ($row = $result->fetch_assoc()) {
    $visas[] = $row;
    $totals[$row['currency']]['total_amount'] += $row['amount'];
    $totals[$row['currency']]['total_payment'] += $row['payment'];
    $totals[$row['currency']]['total_commission'] += $row['commission'];
    $totals[$row['currency']]['count']++;
    $totals[$row['currency']]['status_counts'][$row['status']]++;
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Visa Applications Report')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Visa Applications Report</h4>
                                    <div>
                                        <button type="button" class="btn btn-success" onclick="exportToExcel()">
                                            <i class="ri-file-excel-line align-middle me-1"></i> Export
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <!-- Filter Form -->
                                    <form method="GET" class="row g-3 mb-4">
                                        <div class="col-sm-3">
                                            <label class="form-label">Start Date</label>
                                            <input type="date" class="form-control" name="start_date" 
                                                   value="<?php echo $start_date; ?>">
                                        </div>
                                        <div class="col-sm-3">
                                            <label class="form-label">End Date</label>
                                            <input type="date" class="form-control" name="end_date" 
                                                   value="<?php echo $end_date; ?>">
                                        </div>
                                        <div class="col-sm-3">
                                            <label class="form-label">Currency</label>
                                            <select class="form-select" name="currency">
                                                <option value="all" <?php if($currency_filter == 'all') echo 'selected'; ?>>All</option>
                                                <option value="USD" <?php if($currency_filter == 'USD') echo 'selected'; ?>>USD</option>
                                                <option value="KES" <?php if($currency_filter == 'KES') echo 'selected'; ?>>KES</option>
                                            </select>
                                        </div>
                                        <div class="col-sm-3">
                                            <label class="form-label">&nbsp;</label>
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-filter-2-line align-middle me-1"></i> Filter
                                            </button>
                                        </div>
                                    </form>

                                    <!-- Summary Cards -->
                                    <div class="row mb-4">
                                        <?php foreach ($totals as $currency => $total): ?>
                                            <div class="col-sm-6">
                                                <div class="card border">
                                                    <div class="card-body">
                                                        <h5 class="card-title mb-3"><?php echo $currency; ?> Summary</h5>
                                                        <div class="table-responsive">
                                                            <table class="table table-borderless mb-0">
                                                                <tr>
                                                                    <th>Total Applications:</th>
                                                                    <td><?php echo $total['count']; ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <th>Total Amount:</th>
                                                                    <td><?php echo $currency . ' ' . number_format($total['total_amount'], 2); ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <th>Total Payments:</th>
                                                                    <td><?php echo $currency . ' ' . number_format($total['total_payment'], 2); ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <th>Total Commission:</th>
                                                                    <td><?php echo $currency . ' ' . number_format($total['total_commission'], 2); ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <th colspan="2" class="pt-3">Status Breakdown:</th>
                                                                </tr>
                                                                <?php foreach ($total['status_counts'] as $status => $count): ?>
                                                                    <tr>
                                                                        <td><?php echo $status; ?>:</td>
                                                                        <td><?php echo $count; ?></td>
                                                                    </tr>
                                                                <?php endforeach; ?>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>

                                    <!-- Detailed Table -->
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped">
                                            <thead>
                                                <tr>
                                                    <th>Ref Number</th>
                                                    <th>Date</th>
                                                    <th>Client Name</th>
                                                    <th>Care Of</th>
                                                    <th>Amount</th>
                                                    <th>Payment</th>
                                                    <th>Commission</th>
                                                    <th>Status</th>
                                                    <th>Processed By</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($visas as $visa): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($visa['reference_number']); ?></td>
                                                        <td><?php echo date('d M Y', strtotime($visa['created_at'])); ?></td>
                                                        <td><?php echo htmlspecialchars($visa['client_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($visa['care_of'] ?? '-'); ?></td>
                                                        <td><?php echo $visa['currency'] . ' ' . 
                                                            number_format($visa['amount'], 2); ?></td>
                                                        <td><?php echo $visa['currency'] . ' ' . 
                                                            number_format($visa['payment'], 2); ?></td>
                                                        <td><?php echo $visa['currency'] . ' ' . 
                                                            number_format($visa['commission'], 2); ?></td>
                                                        <td>
                                                            <span class="badge bg-<?php
                                                                echo $visa['status'] === 'Completed' ? 'success' : 
                                                                    ($visa['status'] === 'Cancelled' ? 'danger' : 
                                                                    ($visa['status'] === 'Processing' ? 'warning' : 'info'));
                                                                ?>">
                                                                <?php echo ucfirst($visa['status']); ?>
                                                            </span>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($visa['processed_by']); ?></td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script>
    function exportToExcel() {
        const urlParams = new URLSearchParams(window.location.search);
        const startDate = urlParams.get('start_date') || '<?php echo date('Y-m-01'); ?>';
        const endDate = urlParams.get('end_date') || '<?php echo date('Y-m-t'); ?>';
        const currency = urlParams.get('currency') || 'all';

        window.location.href = `export_visa_report.php?start_date=${startDate}&end_date=${endDate}&currency=${currency}`;
    }
    </script>
</body>
</html>