<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Get country ID
$country_id = $_GET['country_id'] ?? null;

if ($country_id) {
    // Get specific country's checklist
    $stmt = $pdo->prepare("SELECT vc.*, c.name as country_name, c.code as country_code 
                          FROM visa_checklist vc
                          JOIN countries c ON vc.country_id = c.id
                          WHERE vc.country_id = ?
                          ORDER BY vc.document_name");
    $stmt->execute([$country_id]);
    $checklist = $stmt->fetchAll();
    
    $stmt = $pdo->prepare("SELECT name, code FROM countries WHERE id = ?");
    $stmt->execute([$country_id]);
    $country = $stmt->fetch();
} else {
    // Get all checklists
    $stmt = $pdo->query("SELECT vc.*, c.name as country_name, c.code as country_code 
                        FROM visa_checklist vc
                        JOIN countries c ON vc.country_id = c.id
                        ORDER BY c.name, vc.document_name");
    $checklist = $stmt->fetchAll();
}

// Get countries for filter
$countries = $pdo->query("SELECT id, name, code FROM countries ORDER BY name")->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM visa_checklist")->fetchColumn(),
    'by_country' => $pdo->query("SELECT c.name, c.code, COUNT(*) as count FROM visa_checklist vc JOIN countries c ON vc.country_id = c.id GROUP BY c.id, c.name, c.code ORDER BY count DESC")->fetchAll(),
];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_document'])) {
    $country_id = $_POST['country_id'] ?? '';
    $document_name = $_POST['document_name'] ?? '';
    $description = $_POST['description'] ?? '';
    $is_required = isset($_POST['is_required']) ? 1 : 0;
    
    if ($country_id && $document_name) {
        try {
            $stmt = $pdo->prepare("INSERT INTO visa_checklist (
                country_id, document_name, description, is_required, created_at, updated_at
            ) VALUES (?, ?, ?, ?, NOW(), NOW())");
            
            $stmt->execute([$country_id, $document_name, $description, $is_required]);
            
            $success = "Document added to visa checklist successfully!";
            
            // Refresh data
            if (isset($_GET['country_id'])) {
                $stmt = $pdo->prepare("SELECT vc.*, c.name as country_name, c.code as country_code 
                                      FROM visa_checklist vc
                                      JOIN countries c ON vc.country_id = c.id
                                      WHERE vc.country_id = ?
                                      ORDER BY vc.document_name");
                $stmt->execute([$_GET['country_id']]);
                $checklist = $stmt->fetchAll();
            }
            
        } catch (Exception $e) {
            $error = "Failed to add document. Please try again.";
        }
    } else {
        $error = "Please fill in all required fields.";
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Visa Checklist - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .flag {
            width: 30px;
            height: 20px;
            object-fit: cover;
            border-radius: 5px;
            margin-right: 10px;
        }
        .required-badge {
            font-size: 0.8em;
            padding: 3px 8px;
            border-radius: 15px;
        }
        .required-yes {
            background: #d4edda;
            color: #155724;
        }
        .required-no {
            background: #f8f9fa;
            color: #6c757d;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Academic Management</h6>
        <h1 class="display-5">Visa Document Checklist</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Documents</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="bg-light p-4 rounded">
                <h6><i class="fas fa-globe"></i> Documents by Country</h6>
                <div class="row mt-3">
                    <?php foreach ($stats['by_country'] as $country): ?>
                    <div class="col-md-3 mb-2">
                        <div class="d-flex align-items-center">
                            <img src="img/flags/<?= strtolower($country['code']) ?>.png" 
                                 alt="<?= htmlspecialchars($country['name']) ?>" class="flag mr-2">
                            <div>
                                <strong><?= htmlspecialchars($country['name']) ?></strong>
                                <div><?= $country['count'] ?> documents</div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Country Filter -->
    <?php if (!$country_id): ?>
    <div class="row mb-4">
        <div class="col-lg-6">
            <select name="country" class="form-control" onchange="window.location='admin-visa-checklist.php?country_id='+this.value">
                <option value="">All Countries</option>
                <?php foreach ($countries as $c): ?>
                <option value="<?= $c['id'] ?>" <?= $country_id == $c['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($c['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <?php endif; ?>

    <!-- Add New Document Form -->
    <div class="bg-white p-4 rounded mb-4">
        <h5 class="mb-3">Add New Document to Checklist</h5>
        <form method="POST">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label>Country *</label>
                    <select name="country_id" class="form-control" required>
                        <option value="">Select Country</option>
                        <?php foreach ($countries as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= ($country_id ?? '') == $c['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label>Document Name *</label>
                    <input type="text" name="document_name" class="form-control" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label>Description</label>
                    <input type="text" name="description" class="form-control">
                </div>
            </div>
            <div class="form-group">
                <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="is_required" name="is_required" checked>
                    <label class="custom-control-label" for="is_required">Required Document</label>
                </div>
            </div>
            <button type="submit" name="add_document" class="btn btn-primary">Add Document</button>
        </form>
    </div>

    <!-- Checklist Table -->
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Country</th>
                    <th>Document</th>
                    <th>Description</th>
                    <th>Required</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($checklist as $item): ?>
                <tr>
                    <td>
                        <div class="d-flex align-items-center">
                            <img src="img/flags/<?= strtolower($item['country_code']) ?>.png" 
                                 alt="<?= htmlspecialchars($item['country_name']) ?>" class="flag mr-2">
                            <?= htmlspecialchars($item['country_name']) ?>
                        </div>
                    </td>
                    <td><?= htmlspecialchars($item['document_name']) ?></td>
                    <td><?= htmlspecialchars($item['description'] ?? 'No description') ?></td>
                    <td>
                        <span class="required-badge required-<?= $item['is_required'] ? 'yes' : 'no' ?>">
                            <?= $item['is_required'] ? 'Yes' : 'No' ?>
                        </span>
                    </td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-danger delete-document" data-id="<?= $item['id'] ?>">Delete</button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    $('.delete-document').on('click', function() {
        const documentId = $(this).data('id');
        if (confirm('Are you sure you want to delete this document from the visa checklist? This action cannot be undone.')) {
            alert('In a real application, this would delete the document from the database.');
        }
    });
</script>
</body>
</html>