<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: index.php');
    exit();
}
require_once('../db.php');

$message = "";
$error = "";

// Ensure uploads folder exists
$upload_dir = '../uploads/campuses/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $res = $conn->query("SELECT image FROM our_schools WHERE id = $id");
    if ($row = $res->fetch_assoc()) {
        $img_file = $row['image'];
        if ($img_file && file_exists($upload_dir . $img_file) && !str_starts_with($img_file, 'http')) {
            @unlink($upload_dir . $img_file);
        }
    }
    $conn->query("DELETE FROM our_schools WHERE id = $id");
    $message = "School campus deleted successfully!";
}

// Handle Status Toggle
if (isset($_GET['toggle_status'])) {
    $id = intval($_GET['toggle_status']);
    $conn->query("UPDATE our_schools SET status = IF(status=1, 0, 1) WHERE id = $id");
    header("Location: manage_schools.php");
    exit();
}

// Handle Add / Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $name = trim($_POST['name'] ?? '');
    $tagline = trim($_POST['tagline'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $badge = trim($_POST['badge'] ?? '');
    $explore_link = trim($_POST['explore_link'] ?? 'the-school.php');
    $admission_link = trim($_POST['admission_link'] ?? 'admission-enquiry.php');
    $order_num = intval($_POST['order_num'] ?? 0);

    if (empty($name)) {
        $error = "School name is required!";
    } else {
        $image_name = "";
        if (!empty($_FILES['image']['name'])) {
            $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
            if (in_array($ext, $allowed)) {
                $image_name = 'campus_' . time() . '_' . rand(100, 999) . '.' . $ext;
                move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $image_name);

                // If editing, remove old custom image if uploaded
                if ($id > 0) {
                    $old_res = $conn->query("SELECT image FROM our_schools WHERE id = $id");
                    if ($old = $old_res->fetch_assoc()) {
                        if ($old['image'] && file_exists($upload_dir . $old['image']) && !in_array($old['image'], ['bs_public_school.webp', 'ah_international_school.webp'])) {
                            @unlink($upload_dir . $old['image']);
                        }
                    }
                }
            } else {
                $error = "Invalid image file format! Use JPG, PNG, WEBP, or GIF.";
            }
        }

        if (empty($error)) {
            if ($id > 0) {
                if ($image_name !== "") {
                    $stmt = $conn->prepare("UPDATE our_schools SET name=?, tagline=?, description=?, badge=?, image=?, explore_link=?, admission_link=?, order_num=? WHERE id=?");
                    $stmt->bind_param("sssssssii", $name, $tagline, $description, $badge, $image_name, $explore_link, $admission_link, $order_num, $id);
                } else {
                    $stmt = $conn->prepare("UPDATE our_schools SET name=?, tagline=?, description=?, badge=?, explore_link=?, admission_link=?, order_num=? WHERE id=?");
                    $stmt->bind_param("ssssssii", $name, $tagline, $description, $badge, $explore_link, $admission_link, $order_num, $id);
                }
                $stmt->execute();
                $message = "School details updated successfully!";
            } else {
                if ($image_name === "") {
                    $image_name = "bs_public_school.webp";
                }
                $stmt = $conn->prepare("INSERT INTO our_schools (name, tagline, description, badge, image, explore_link, admission_link, order_num, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)");
                $stmt->bind_param("sssssssi", $name, $tagline, $description, $badge, $image_name, $explore_link, $admission_link, $order_num);
                $stmt->execute();
                $message = "New school campus added successfully!";
            }
        }
    }
}

// Fetch all schools
$schools = $conn->query("SELECT * FROM our_schools ORDER BY order_num ASC, id ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Our Schools & Campuses | BSPS Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root { --primary: #0b3b60; --accent: #f5a623; --dark: #1e293b; }
        body { background: #f8fafc; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .sidebar { height: 100vh; width: 260px; position: fixed; background: var(--dark); color: #fff; padding-top: 20px; overflow-y: auto; }
        .sidebar a { color: rgba(255,255,255,0.7); text-decoration: none; padding: 13px 25px; display: block; transition: 0.3s; font-size: 14.5px; }
        .sidebar a:hover, .sidebar a.active { color: #fff; background: #0b3b60; border-left: 4px solid var(--accent); }
        .main-content { margin-left: 260px; padding: 40px; }
        .card { border-radius: 12px; border: none; box-shadow: 0 4px 18px rgba(0,0,0,0.06); }
        .school-img-preview { width: 140px; height: 90px; object-fit: cover; border-radius: 8px; border: 2px solid #e2e8f0; }
        .logout-btn { position: relative; margin-top: 40px; padding: 0 15px; }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="px-4 mb-4">
            <h4 class="fw-bold text-white mb-0">BSPS ADMIN</h4>
            <span class="small text-secondary">Control Panel</span>
        </div>
        <a href="dashboard.php"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="manage_applications.php"><i class="fas fa-envelope-open-text me-2"></i> Applications Box</a>
        <a href="manage_schools.php" class="active"><i class="fas fa-school me-2"></i> Our Schools (Campuses)</a>
        <a href="manage_leadership.php"><i class="fas fa-users-cog me-2"></i> Board Leadership</a>
        <a href="manage_director.php"><i class="fas fa-user-tie me-2"></i> Director's Desk</a>
        <a href="manage_events.php"><i class="fas fa-calendar-alt me-2"></i> Events Gallery</a>
        <a href="manage_important_sites.php"><i class="fas fa-globe me-2"></i> Important Sites</a>
        <a href="manage_slider.php"><i class="fas fa-images me-2"></i> Manage Slider</a>
        <a href="manage_gallery.php"><i class="fas fa-photo-video me-2"></i> Manage Gallery</a>
        <a href="../index.php" target="_blank"><i class="fas fa-external-link-alt me-2"></i> Visit Website</a>
        <div class="logout-btn">
            <a href="logout.php" class="btn btn-outline-danger w-100 text-start py-2"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
        </div>
    </div>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="fw-bold text-dark mb-1">Our Schools &amp; Campuses Showcase</h2>
                <div class="text-muted">Manage the two institution names, photos, descriptions, and interactive hover showcase.</div>
            </div>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addSchoolModal" onclick="resetForm()">
                <i class="fas fa-plus me-2"></i> Add New School
            </button>
        </div>

        <?php if (!empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show"><?php echo $message; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show"><?php echo $error; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <div class="card p-4">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 50px;">Order</th>
                            <th style="width: 160px;">Campus Photo</th>
                            <th>School Name &amp; Tagline</th>
                            <th>Badge</th>
                            <th style="width: 120px;">Status</th>
                            <th style="width: 140px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($schools && $schools->num_rows > 0): ?>
                            <?php while ($row = $schools->fetch_assoc()): ?>
                                <tr>
                                    <td class="fw-bold text-muted"><?php echo $row['order_num']; ?></td>
                                    <td>
                                        <?php 
                                        $img_src = (str_starts_with($row['image'], 'http') || str_starts_with($row['image'], 'images/')) 
                                            ? $row['image'] 
                                            : '../uploads/campuses/' . $row['image'];
                                        ?>
                                        <img src="<?php echo htmlspecialchars($img_src); ?>" class="school-img-preview shadow-sm" alt="Campus">
                                    </td>
                                    <td>
                                        <h6 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars($row['name']); ?></h6>
                                        <span class="text-muted small d-block"><?php echo htmlspecialchars($row['tagline']); ?></span>
                                        <span class="text-secondary small fst-italic text-truncate d-inline-block" style="max-width: 400px;"><?php echo htmlspecialchars($row['description']); ?></span>
                                    </td>
                                    <td>
                                        <span class="badge bg-warning text-dark px-3 py-2"><?php echo htmlspecialchars($row['badge']); ?></span>
                                    </td>
                                    <td>
                                        <?php if ($row['status'] == 1): ?>
                                            <a href="manage_schools.php?toggle_status=<?php echo $row['id']; ?>" class="badge bg-success text-decoration-none px-3 py-2">Active</a>
                                        <?php else: ?>
                                            <a href="manage_schools.php?toggle_status=<?php echo $row['id']; ?>" class="badge bg-secondary text-decoration-none px-3 py-2">Inactive</a>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" onclick='editSchool(<?php echo json_encode($row); ?>)'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <a href="manage_schools.php?delete=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this school?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">No schools added yet. Click "Add New School" to start.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add / Edit Modal -->
    <div class="modal fade" id="addSchoolModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form action="manage_schools.php" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="id" id="school_id" value="0">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold" id="modalTitle">Add School Campus</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-8">
                                <label class="form-label fw-bold">School Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" id="school_name" class="form-control" placeholder="e.g. B.S. Public School" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Order Number</label>
                                <input type="number" name="order_num" id="school_order" class="form-control" value="1">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Subtitle / Tagline</label>
                                <input type="text" name="tagline" id="school_tagline" class="form-control" placeholder="e.g. CBSE Pattern • Classes Nursery to 10th">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Badge Text</label>
                                <input type="text" name="badge" id="school_badge" class="form-control" placeholder="e.g. Main Campus • Estd. 2005">
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-bold">Description / Overview</label>
                                <textarea name="description" id="school_desc" class="form-control" rows="3" placeholder="Brief introduction about this institution, facilities, and academic highlights..."></textarea>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Explore Campus Link</label>
                                <input type="text" name="explore_link" id="school_explore_link" class="form-control" value="the-school.php">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Admission Link</label>
                                <input type="text" name="admission_link" id="school_admission_link" class="form-control" value="admission-enquiry.php">
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-bold">Campus Photo (Landscape View)</label>
                                <input type="file" name="image" class="form-control" accept="image/*">
                                <small class="text-muted">Recommended resolution: 1280x720 or 16:9 aspect ratio. Allowed formats: JPG, PNG, WEBP.</small>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary px-4">Save School</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function resetForm() {
            document.getElementById('modalTitle').innerText = 'Add School Campus';
            document.getElementById('school_id').value = '0';
            document.getElementById('school_name').value = '';
            document.getElementById('school_tagline').value = '';
            document.getElementById('school_badge').value = '';
            document.getElementById('school_desc').value = '';
            document.getElementById('school_explore_link').value = 'the-school.php';
            document.getElementById('school_admission_link').value = 'admission-enquiry.php';
            document.getElementById('school_order').value = '1';
        }

        function editSchool(data) {
            document.getElementById('modalTitle').innerText = 'Edit School Details';
            document.getElementById('school_id').value = data.id;
            document.getElementById('school_name').value = data.name;
            document.getElementById('school_tagline').value = data.tagline || '';
            document.getElementById('school_badge').value = data.badge || '';
            document.getElementById('school_desc').value = data.description || '';
            document.getElementById('school_explore_link').value = data.explore_link || 'the-school.php';
            document.getElementById('school_admission_link').value = data.admission_link || 'admission-enquiry.php';
            document.getElementById('school_order').value = data.order_num;
            var modal = new bootstrap.Modal(document.getElementById('addSchoolModal'));
            modal.show();
        }
    </script>
</body>
</html>
