<?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 = '';

// Check if 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();
}

// Handle delete action
if (isset($_GET['delete'])) {
    $delete_id = $_GET['delete'];
    try {
        // First check if any universities are using this country
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM universities WHERE country_id = ?");
        $stmt->execute([$delete_id]);
        $university_count = $stmt->fetchColumn();
        
        if ($university_count > 0) {
            $error = "Cannot delete country - it has universities associated with it.";
        } else {
            // Delete the country image if exists
            $stmt = $pdo->prepare("SELECT image_path FROM countries WHERE id = ?");
            $stmt->execute([$delete_id]);
            $image_path = $stmt->fetchColumn();
            
            if ($image_path && file_exists($image_path)) {
                unlink($image_path);
            }
            
            // Delete the country
            $stmt = $pdo->prepare("DELETE FROM countries WHERE id = ?");
            $stmt->execute([$delete_id]);
            $success = "Country deleted successfully!";
            header("Location: admin-countries.php?success=1");
            exit;
        }
    } catch (Exception $e) {
        $error = "Failed to delete country: " . $e->getMessage();
    }
}

// Handle create 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'] ?? null;
    $popularity_rank = $_POST['popularity_rank'] ?? 0;
    $current_image = $_POST['current_image'] ?? null;

    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 zero or a positive number.";
    } else {
        try {
            $pdo->beginTransaction();

            // Handle file upload
            $image_path = $current_image;
            if (isset($_FILES['country_image']) && $_FILES['country_image']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = 'uploads/countries/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                // Delete old image if exists
                if ($image_path && file_exists($image_path)) {
                    unlink($image_path);
                }
                
                // Generate unique filename
                $file_ext = pathinfo($_FILES['country_image']['name'], PATHINFO_EXTENSION);
                $filename = 'country-' . strtolower(str_replace(' ', '-', $name)) . '-' . uniqid() . '.' . $file_ext;
                $target_path = $upload_dir . $filename;
                
                // Check file type
                $allowed_types = ['jpg', 'jpeg', 'png', 'webp'];
                if (!in_array(strtolower($file_ext), $allowed_types)) {
                    throw new Exception("Only JPG, JPEG, PNG, and WEBP files are allowed.");
                }
                
                // Move uploaded file
                if (move_uploaded_file($_FILES['country_image']['tmp_name'], $target_path)) {
                    $image_path = $target_path;
                } else {
                    throw new Exception("Failed to upload image.");
                }
            }

            if ($edit_country_id && $country) {
                // Update
                $stmt = $pdo->prepare("UPDATE countries SET 
                    name = ?, code = ?, visa_requirements = ?, living_cost_estimate = ?, 
                    popularity_rank = ?, image_path = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([
                    $name, $code, $visa_requirements, $living_cost_estimate, 
                    $popularity_rank, $image_path, $edit_country_id
                ]);
                $success = "Country updated successfully!";
            } else {
                // Insert
                $stmt = $pdo->prepare("INSERT INTO countries (
                    name, code, visa_requirements, living_cost_estimate, popularity_rank, 
                    image_path, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())");
                $stmt->execute([
                    $name, $code, $visa_requirements, $living_cost_estimate, 
                    $popularity_rank, $image_path
                ]);
                $success = "Country created successfully!";
            }

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

// Get all countries with image info
$countries = $pdo->query("SELECT * FROM countries ORDER BY popularity_rank, name")->fetchAll();

// Stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM countries")->fetchColumn(),
    'with_universities' => $pdo->query("SELECT COUNT(DISTINCT country_id) FROM universities")->fetchColumn(),
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Manage Countries - JV Overseas Education</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .country-image-preview {
            max-width: 200px;
            max-height: 150px;
            margin-top: 10px;
            display: <?= isset($country['image_path']) ? 'block' : 'none' ?>;
        }
        .country-image-thumbnail {
            max-width: 80px;
            max-height: 60px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
<?php include 'admin-navbar.php'; ?>

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

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

    <!-- Country Form -->
    <div class="card p-4 mb-4">
        <h3><?= $edit_country_id ? "Edit Country" : "Add New Country" ?></h3>
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Country Name *</label>
                        <input type="text" name="name" class="form-control" required
                               value="<?= htmlspecialchars($country['name'] ?? '') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Country Code *</label>
                        <input type="text" name="code" class="form-control" required
                               value="<?= htmlspecialchars($country['code'] ?? '') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Popularity Rank</label>
                        <input type="number" name="popularity_rank" class="form-control"
                               value="<?= htmlspecialchars($country['popularity_rank'] ?? 0) ?>">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Living Cost Estimate (USD)</label>
                        <input type="number" step="0.01" name="living_cost_estimate" class="form-control"
                               value="<?= htmlspecialchars($country['living_cost_estimate'] ?? '') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Country Image</label>
                        <input type="file" name="country_image" class="form-control" accept="image/*">
                        <input type="hidden" name="current_image" value="<?= htmlspecialchars($country['image_path'] ?? '') ?>">
                        <?php if (isset($country['image_path']) && !empty($country['image_path'])): ?>
                            <img src="<?= htmlspecialchars($country['image_path']) ?>" class="country-image-preview mt-2" id="imagePreview">
                        <?php else: ?>
                            <img src="" class="country-image-preview mt-2" id="imagePreview">
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Visa Requirements</label>
                <textarea name="visa_requirements" class="form-control" rows="4"><?= htmlspecialchars($country['visa_requirements'] ?? '') ?></textarea>
            </div>
            <button type="submit" name="save_country" class="btn btn-primary">
                <?= $edit_country_id ? "Update Country" : "Create Country" ?>
            </button>
            <?php if ($edit_country_id): ?>
                <a href="admin-countries.php" class="btn btn-secondary">Cancel</a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Countries List -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Country List</h5>
            <div>
                <span class="badge bg-primary me-2">Total: <?= $stats['total'] ?></span>
                <span class="badge bg-success">With Universities: <?= $stats['with_universities'] ?></span>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>Image</th>
                            <th>Country</th>
                            <th>Code</th>
                            <th>Rank</th>
                            <th>Living Cost</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($countries as $c): ?>
                        <tr>
                            <td>
                                <?php if (!empty($c['image_path'])): ?>
                                    <img src="<?= htmlspecialchars($c['image_path']) ?>" class="country-image-thumbnail">
                                <?php else: ?>
                                    <span class="text-muted">No image</span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($c['name']) ?></td>
                            <td><?= htmlspecialchars($c['code']) ?></td>
                            <td><?= $c['popularity_rank'] ?></td>
                            <td>$<?= number_format($c['living_cost_estimate']) ?></td>
                            <td>
                                <div class="d-flex gap-2">
                                    <a href="admin-countries.php?edit=<?= $c['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                                    <a href="admin-countries.php?delete=<?= $c['id'] ?>" 
                                       class="btn btn-sm btn-danger" 
                                       onclick="return confirm('Are you sure you want to delete this country?')">Delete</a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($countries)): ?>
                        <tr><td colspan="6" class="text-center">No countries found.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>

<script>
    // Image preview functionality
    document.querySelector('input[name="country_image"]').addEventListener('change', function(e) {
        const preview = document.getElementById('imagePreview');
        if (this.files && this.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
            }
            reader.readAsDataURL(this.files[0]);
        }
    });
</script>
</body>
</html>