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

$search = isset($_GET['search']) ? $_GET['search'] : '';
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$statusFilter = isset($_GET['status']) ? $_GET['status'] : '';

$query = "SELECT v.*, 
                 u_created.full_name as created_by_name,
                 u_updated.full_name as updated_by_name
          FROM visa_applications v 
          LEFT JOIN users u_created ON v.created_by = u_created.user_id
          LEFT JOIN users u_updated ON v.updated_by = u_updated.user_id 
          WHERE 1=1";

if (!empty($search)) {
    $query .= " AND (v.client_name LIKE '%$search%' OR v.reference_number LIKE '%$search%' 
                OR v.care_of LIKE '%$search%')";
}
if (!empty($dateFrom)) {
    $query .= " AND DATE(v.created_at) >= '$dateFrom'";
}
if (!empty($dateTo)) {
    $query .= " AND DATE(v.created_at) <= '$dateTo'";
}
if (!empty($statusFilter)) {
    $query .= " AND v.status = '$statusFilter'";
}
$query .= " ORDER BY v.created_at DESC";

$result = $conn->query($query);
?>

<!doctype html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Visa Applications')); ?>
    <?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">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Visa Applications', 'title' => 'All Applications')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Visa Applications</h4>
                                    <div>
                                        <button onclick="exportToCSV()" class="btn btn-success me-2">
                                            <i class="ri-file-download-line align-middle me-1"></i> Export
                                        </button>
                                        <a href="add_visa.php" class="btn btn-primary">
                                            <i class="ri-add-line align-middle me-1"></i> New Application
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <!-- Search Form -->
                                    <form class="row g-3 mb-4" method="GET">
                                        <div class="col-md-3">
                                            <input type="text" class="form-control" name="search" 
                                                   placeholder="Search by name or reference..." 
                                                   value="<?php echo htmlspecialchars($search); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="Pending" <?php if($statusFilter == 'Pending') echo 'selected'; ?>>Pending</option>
                                                <option value="Processing" <?php if($statusFilter == 'Processing') echo 'selected'; ?>>Processing</option>
                                                <option value="Completed" <?php if($statusFilter == 'Completed') echo 'selected'; ?>>Completed</option>
                                                <option value="Cancelled" <?php if($statusFilter == 'Cancelled') echo 'selected'; ?>>Cancelled</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <input type="date" class="form-control" name="date_from" 
                                                   value="<?php echo htmlspecialchars($dateFrom); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <input type="date" class="form-control" name="date_to" 
                                                   value="<?php echo htmlspecialchars($dateTo); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <button type="submit" class="btn btn-primary w-100">Search</button>
                                        </div>
                                    </form>

                                    <!-- Table -->
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped">
                                            <thead>
                                                <tr>
                                                    <th>Ref No.</th>
                                                    <th>Client Name</th>
                                                    <th>Care Of</th>
                                                    <th>Amount</th>
                                                    <th>Payment</th>
                                                    <th>Commission</th>
                                                    <th>Status</th>
                                                    <th>Created By</th>
                                                    <th>Created At</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while ($row = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($row['reference_number']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['client_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['care_of'] ?? '-'); ?></td>
                                                            <td><?php echo $row['currency'] . ' ' . number_format($row['amount'], 2); ?></td>
                                                            <td><?php echo $row['currency'] . ' ' . number_format($row['payment'], 2); ?></td>
                                                            <td><?php echo $row['currency'] . ' ' . number_format($row['commission'], 2); ?></td>
                                                            <td>
                                                                <span class="badge bg-<?php 
                                                                    echo $row['status'] === 'Completed' ? 'success' : 
                                                                        ($row['status'] === 'Cancelled' ? 'danger' : 
                                                                        ($row['status'] === 'Processing' ? 'warning' : 'info')); 
                                                                ?>">
                                                                    <?php echo htmlspecialchars($row['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['created_by_name']); ?></td>
                                                            <td><?php echo date('d M Y H:i', strtotime($row['created_at'])); ?></td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-sm btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu">
                                                                        <li>
                                                                            <a class="dropdown-item" href="view_visa.php?id=<?php echo $row['application_id']; ?>">
                                                                                <i class="ri-eye-line align-middle me-1"></i> View
                                                                            </a>
                                                                        </li>
                                                                        <?php if ($row['status'] === 'Pending'): ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="edit_visa.php?id=<?php echo $row['application_id']; ?>">
                                                                                <i class="ri-pencil-line align-middle me-1"></i> Edit
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item text-danger" href="javascript:void(0);" 
                                                                               onclick="cancelVisa(<?php echo $row['application_id']; ?>)">
                                                                                <i class="ri-close-circle-line align-middle me-1"></i> Cancel
                                                                            </a>
                                                                        </li>
                                                                        <?php endif; ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="print_visa.php?id=<?php echo $row['application_id']; ?>">
                                                                                <i class="ri-printer-line align-middle me-1"></i> Print
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="10" class="text-center">No applications found</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </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 exportToCSV() {
        const urlParams = new URLSearchParams(window.location.search);
        const params = {
            search: urlParams.get('search') || '',
            date_from: urlParams.get('date_from') || '',
            date_to: urlParams.get('date_to') || '',
            status: urlParams.get('status') || ''
        };
        window.location.href = `export_visas.php?${new URLSearchParams(params)}`;
    }

    function cancelVisa(id) {
        if (confirm('Are you sure you want to cancel this visa application?')) {
            fetch('cancel_visa.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `id=${id}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while cancelling the visa application');
            });
        }
    }
    </script>
</body>
</html>