<?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.");
}

$error = '';
$success = '';

// Show success after redirect
if (isset($_GET['created'])) {
    $success = "Country created successfully!";
} elseif (isset($_GET['updated'])) {
    $success = "Country updated successfully!";
} elseif (isset($_GET['deleted'])) {
    $success = "Country deleted successfully!";
}

$upload_dir = 'uploads/countries/';

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// ==========================
// Get country ID for editing
// ==========================
$edit_country_id = $_GET['edit'] ?? null;
$country = null;

if ($edit_country_id) {
    $stmt = $pdo->prepare("SELECT * FROM countries WHERE id = ?");
    $stmt->execute([$edit_country_id]);
    $country = $stmt->fetch();
    
    if (!$country) {
        $error = "Country not found.";
        $edit_country_id = null;
    }
}

// ==========================
// Handle country creation or update
// ==========================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_country'])) {
    $name = trim($_POST['name'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $visa_requirements = $_POST['visa_requirements'] ?? '';
    $living_cost_estimate = $_POST['living_cost_estimate'] ?? '';
    $popularity_rank = $_POST['popularity_rank'] ?? 0;

    // Convert empty living cost to 0
    if ($living_cost_estimate === '' || $living_cost_estimate === null) {
        $living_cost_estimate = 0;
    }

    // Validate form data
    if (empty($name) || empty($code)) {
        $error = "Country name and code are required.";
    } elseif (!is_numeric($living_cost_estimate) || $living_cost_estimate < 0) {
        $error = "Living cost estimate must be a number (0 or positive).";
    } else {
        try {
            $pdo->beginTransaction();

            if ($edit_country_id && $country) {
                // Update existing country
                $stmt = $pdo->prepare("UPDATE countries SET 
                    name = ?, code = ?, visa_requirements = ?, living_cost_estimate = ?, 
                    popularity_rank = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([
                    $name, $code, $visa_requirements, $living_cost_estimate, 
                    $popularity_rank, $edit_country_id
                ]);

                // Log activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, created_at
                ) VALUES (?, ?, ?, NOW())")->execute([
                    $_SESSION['user_id'],
                    "country_updated",
                    "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} updated country: {$name}"
                ]);

                $pdo->commit();
                header("Location: admin-countries.php?updated=1");
                exit;
            } else {
                // Create new country
                $stmt = $pdo->prepare("INSERT INTO countries (
                    name, code, visa_requirements, living_cost_estimate, popularity_rank, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
                $stmt->execute([
                    $name, $code, $visa_requirements, $living_cost_estimate, $popularity_rank
                ]);

                // Log activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, created_at
                ) VALUES (?, ?, ?, NOW())")->execute([
                    $_SESSION['user_id'],
                    "country_created",
                    "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} created country: {$name}"
                ]);

                $pdo->commit();
                header("Location: admin-countries.php?created=1");
                exit;
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Failed to save country: " . $e->getMessage();
        }
    }
}

// ==========================
// Handle country deletion
// ==========================
if (isset($_GET['delete']) && !empty($_GET['delete'])) {
    $country_id = $_GET['delete'];
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM universities WHERE country_id = ?");
        $stmt->execute([$country_id]);
        $usage_count = $stmt->fetchColumn();

        if ($usage_count > 0) {
            $error = "Cannot delete this country as it is being used in {$usage_count} university(s).";
        } else {
            $stmt = $pdo->prepare("DELETE FROM countries WHERE id = ?");
            $stmt->execute([$country_id]);

            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "country_deleted",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} deleted country with ID: {$country_id}"
            ]);

            header("Location: admin-countries.php?deleted=1");
            exit;
        }
    } catch (Exception $e) {
        $error = "Failed to delete country: " . $e->getMessage();
    }
}

// ==========================
// Get all countries and stats
// ==========================
$countries = $pdo->query("SELECT * FROM countries ORDER BY popularity_rank DESC, name")->fetchAll();
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM countries")->fetchColumn(),
    'with_universities' => $pdo->query("SELECT COUNT(DISTINCT country_id) FROM universities")->fetchColumn(),
];

// ==========================
// Logout
// ==========================
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Manage Destinations - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
</head>
<body>

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

<div class="container py-5">
    <h1 class="mb-4">Manage Study Destinations</h1>

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

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

    <!-- Stats -->
    <div class="mb-4">
        <p>Total Destinations: <?= $stats['total'] ?></p>
        <p>With Universities: <?= $stats['with_universities'] ?></p>
    </div>

    <?php if ($edit_country_id && $country): ?>
    <!-- Edit Form -->
    <form method="POST" action="admin-countries.php?edit=<?= $edit_country_id ?>">
        <h3>Edit Destination</h3>
        <?php include 'country-form-fields.php'; ?>
        <button type="submit" name="save_country" class="btn btn-primary">Update Destination</button>
        <a href="admin-countries.php" class="btn btn-secondary">Cancel</a>
    </form>
    <?php else: ?>
    <!-- Create Form -->
    <form method="POST" action="admin-countries.php">
        <h3>Create New Destination</h3>
        <?php include 'country-form-fields.php'; ?>
        <button type="submit" name="save_country" class="btn btn-primary">Create Destination</button>
    </form>

    <!-- Countries List -->
    <h3 class="mt-5">Existing Destinations</h3>
    <?php if (empty($countries)): ?>
        <p>No destinations found.</p>
    <?php else: ?>
        <ul>
        <?php foreach ($countries as $c): ?>
            <li>
                <?= htmlspecialchars($c['name']) ?> (<?= htmlspecialchars($c['code']) ?>)
                <a href="admin-countries.php?edit=<?= $c['id'] ?>">Edit</a>
                <a href="admin-countries.php?delete=<?= $c['id'] ?>" 
                   onclick="return confirm('Delete <?= htmlspecialchars($c['name']) ?>?')">Delete</a>
            </li>
        <?php endforeach; ?>
        </ul>
    <?php endif; ?>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?>
</body>
</html>
