<?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/important_sites/';
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 important_sites 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 important_sites WHERE id = $id");
    $message = "Important site deleted successfully!";
}

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

// Handle Add / Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $title = trim($_POST['title'] ?? '');
    $url = trim($_POST['url'] ?? '#');
    $order_num = intval($_POST['order_num'] ?? 0);

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

                if ($id > 0) {
                    $old_res = $conn->query("SELECT image FROM important_sites WHERE id = $id");
                    if ($old = $old_res->fetch_assoc()) {
                        if ($old['image'] && file_exists($upload_dir . $old['image']) && !str_starts_with($old['image'], 'site_')) {
                            @unlink($upload_dir . $old['image']);
                        }
                    }
                }
            } else {
                $error = "Invalid image format! Please use JPG, PNG, WEBP, or SVG.";
            }
        }

        if (empty($error)) {
            if ($id > 0) {
                if ($image_name !== "") {
                    $stmt = $conn->prepare("UPDATE important_sites SET title=?, url=?, image=?, order_num=? WHERE id=?");
                    $stmt->bind_param("sssii", $title, $url, $image_name, $order_num, $id);
                } else {
                    $stmt = $conn->prepare("UPDATE important_sites SET title=?, url=?, order_num=? WHERE id=?");
                    $stmt->bind_param("ssii", $title, $url, $order_num, $id);
                }
                $stmt->execute();
                $message = "Important site updated successfully!";
            } else {
                if ($image_name === "") {
                    $image_name = "site_makeinindia.png";
                }
                $stmt = $conn->prepare("INSERT INTO important_sites (title, url, image, order_num, status) VALUES (?, ?, ?, ?, 1)");
                $stmt->bind_param("sssi", $title, $url, $image_name, $order_num);
                $stmt->execute();
                $message = "New important site added successfully!";
            }
        }
    }
}

// Fetch all sites
$sites_res = $conn->query("SELECT * FROM important_sites ORDER BY order_num ASC, id ASC");
$all_sites = [];
if ($sites_res) {
    while ($row = $sites_res->fetch_assoc()) {
        $all_sites[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Important Sites | 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: #004b91; --dark: #0b1a30; }
        body { background: #f4f7f6; font-family: 'Inter', system-ui, sans-serif; }
        .sidebar { height: 100vh; width: 260px; position: fixed; background: var(--dark); color: #fff; padding-top: 20px; z-index: 100; overflow-y: auto; }
        .sidebar a { color: rgba(255,255,255,0.7); text-decoration: none; padding: 13px 22px; display: block; font-size: 0.93rem; transition: 0.3s; }
        .sidebar a:hover, .sidebar a.active { color: #fff; background: var(--primary); }
        .main-content { margin-left: 260px; padding: 35px; }
        .card { border: none; border-radius: 12px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
        .site-circle-preview {
            width: 70px;
            height: 70px;
            background: #fff;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 8px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
            border: 2px solid #e2e8f0;
            overflow: hidden;
        }
        .site-circle-preview img {
            max-height: 52px;
            max-width: 52px;
            object-fit: contain;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="px-4 mb-4">
            <h4 class="fw-bold mb-0 text-white">BSPS ADMIN</h4>
            <small class="text-white-50">Control Panel</small>
        </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"><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" class="active"><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>
        <a href="logout.php" class="text-danger mt-4"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
    </div>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="fw-bold mb-1"><i class="fas fa-globe text-primary me-2"></i> Manage Important Sites</h3>
                <p class="text-muted mb-0">Control the national initiatives, government portals, and educational links displayed above the footer.</p>
            </div>
            <button class="btn btn-primary px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#addSiteModal">
                <i class="fas fa-plus-circle me-1"></i> Add New Site
            </button>
        </div>

        <?php if($message): ?>
            <div class="alert alert-success alert-dismissible fade show rounded-3 shadow-sm mb-4">
                <i class="fas fa-check-circle me-2"></i><?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="alert alert-danger alert-dismissible fade show rounded-3 shadow-sm mb-4">
                <i class="fas fa-exclamation-triangle me-2"></i><?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Table of Sites -->
        <div class="card p-4">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 70px;">Order</th>
                            <th style="width: 100px;">Logo</th>
                            <th>Site Title</th>
                            <th>Official URL / Link</th>
                            <th style="width: 110px;">Status</th>
                            <th style="width: 150px;" class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($all_sites)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">No important sites added yet.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach($all_sites as $s): 
                                $img_src = (str_starts_with($s['image'], 'http')) ? $s['image'] : '../uploads/important_sites/' . $s['image'];
                            ?>
                            <tr>
                                <td><span class="badge bg-secondary rounded-pill px-2"><?php echo $s['order_num']; ?></span></td>
                                <td>
                                    <div class="site-circle-preview">
                                        <img src="<?php echo htmlspecialchars($img_src); ?>" alt="<?php echo htmlspecialchars($s['title']); ?>" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($s['title']); ?>&background=004b91&color=fff';">
                                    </div>
                                </td>
                                <td>
                                    <h6 class="fw-bold mb-0"><?php echo htmlspecialchars($s['title']); ?></h6>
                                </td>
                                <td>
                                    <a href="<?php echo htmlspecialchars($s['url']); ?>" target="_blank" class="text-primary text-decoration-none small">
                                        <?php echo htmlspecialchars($s['url']); ?> <i class="fas fa-external-link-alt ms-1"></i>
                                    </a>
                                </td>
                                <td>
                                    <a href="?toggle_status=<?php echo $s['id']; ?>" class="badge rounded-pill text-decoration-none px-3 py-2 <?php echo $s['status'] ? 'bg-success' : 'bg-secondary'; ?>">
                                        <?php echo $s['status'] ? 'Active' : 'Disabled'; ?>
                                    </a>
                                </td>
                                <td class="text-end">
                                    <button class="btn btn-sm btn-outline-primary me-1" 
                                            onclick='editSite(<?php echo json_encode($s); ?>)'
                                            title="Edit Site">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a href="?delete=<?php echo $s['id']; ?>" class="btn btn-sm btn-outline-danger" 
                                       onclick="return confirm('Are you sure you want to delete this important site?');"
                                       title="Delete Site">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add / Edit Modal -->
    <div class="modal fade" id="addSiteModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded-4 border-0 shadow-lg">
                <div class="modal-header text-white" style="background: #004b91;">
                    <h5 class="modal-title fw-bold" id="modalTitle"><i class="fas fa-plus-circle me-2"></i> Add Important Site</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data" id="siteForm">
                    <input type="hidden" name="id" id="site_id" value="0">
                    <div class="modal-body p-4">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Site Title / Label <span class="text-danger">*</span></label>
                            <input type="text" name="title" id="site_title" class="form-control" placeholder="e.g. MAKE IN INDIA, FIT INDIA" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Official Link / URL <span class="text-danger">*</span></label>
                            <input type="url" name="url" id="site_url" class="form-control" placeholder="https://www.makeinindia.com/" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Display Order</label>
                            <input type="number" name="order_num" id="site_order" class="form-control" value="1">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Site Logo Image</label>
                            <input type="file" name="image" id="site_image" class="form-control" accept="image/*">
                            <div class="form-text">Recommended: Clean PNG/SVG with transparent background (120x120px).</div>
                        </div>
                    </div>
                    <div class="modal-footer bg-light">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary px-4 fw-bold">Save Site</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 editSite(site) {
        document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit me-2"></i> Edit Important Site';
        document.getElementById('site_id').value = site.id;
        document.getElementById('site_title').value = site.title;
        document.getElementById('site_url').value = site.url;
        document.getElementById('site_order').value = site.order_num;
        new bootstrap.Modal(document.getElementById('addSiteModal')).show();
    }
    document.getElementById('addSiteModal').addEventListener('hidden.bs.modal', function () {
        document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle me-2"></i> Add Important Site';
        document.getElementById('site_id').value = '0';
        document.getElementById('siteForm').reset();
    });
    </script>
</body>
</html>
