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

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

$upload_dir = '../uploads/director/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle Update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $badge = trim($_POST['badge'] ?? "DIRECTOR'S DESK");
    $title = trim($_POST['title'] ?? "From Director's Desk");
    $subtitle = trim($_POST['subtitle'] ?? "");
    $director_name = trim($_POST['director_name'] ?? "Dr. Furkan Saifi");
    $designation = trim($_POST['designation'] ?? "Principle");
    $quote = trim($_POST['quote'] ?? "");

    // Check if new director photo uploaded
    $image_update_sql = "";
    $types = "sssss";
    $params = [$badge, $title, $subtitle, $director_name, $designation];

    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 = 'director_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $image_name)) {
                $image_update_sql .= ", image = ?";
                $types .= "s";
                $params[] = $image_name;
            }
        } else {
            $error = "Invalid format for Director Photo! (Only JPG, PNG, WEBP allowed)";
        }
    }

    if (empty($error)) {
        $types .= "s";
        $params[] = $quote;

        // Check if director_desk record exists
        $check = $conn->query("SELECT id FROM director_desk LIMIT 1");
        if ($check && $check->num_rows > 0) {
            $row = $check->fetch_assoc();
            $id = $row['id'];
            $sql = "UPDATE director_desk SET badge=?, title=?, subtitle=?, director_name=?, designation=? {$image_update_sql}, quote=? WHERE id=?";
            $types .= "i";
            $params[] = $id;
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
        } else {
            $stmt = $conn->prepare("INSERT INTO director_desk (badge, title, subtitle, director_name, designation, quote) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssss", $badge, $title, $subtitle, $director_name, $designation, $quote);
            $stmt->execute();
        }
        $message = "Director's Desk details updated successfully!";
    }
}

// Fetch current details
$director = [
    'badge' => "DIRECTOR'S DESK",
    'title' => "From Director's Desk",
    'subtitle' => "BSPS leadership vision and message for holistic education.",
    'director_name' => "Dr. Furkan Saifi",
    'designation' => "Principle",
    'image' => "secretary_furkan.webp",
    'quote' => "BS Public School & AH International School is committed to transforming education through modern curriculum, moral discipline, and holistic development to build real-world careers and empower students for future success.",
    'stamp_image' => "images/logo_bsps.png"
];

$res = $conn->query("SELECT * FROM director_desk LIMIT 1");
if ($res && $res->num_rows > 0) {
    $row = $res->fetch_assoc();
    $director = array_merge($director, array_filter($row));
}

$img_display = (str_starts_with($director['image'], 'http') || str_starts_with($director['image'], 'images/')) 
    ? $director['image'] 
    : (file_exists($upload_dir . $director['image']) ? $upload_dir . $director['image'] : '../images/' . $director['image']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Director's Desk | 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: 35px; }
        .card { border: none; border-radius: 12px; box-shadow: 0 4px 18px rgba(0,0,0,0.06); }
        .director-preview-box { max-width: 280px; height: 210px; border-radius: 12px; overflow: hidden; border: 3px solid #e2e8f0; margin: 0 auto; }
        .director-preview-box img { width: 100%; height: 100%; object-fit: cover; }
    </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"><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" class="active"><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="mt-5 px-3">
            <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="mb-4">
            <h2 class="fw-bold text-dark mb-1">Director's Desk Configuration</h2>
            <p class="text-muted mb-0">Control the photo, name, title, designation, and message shown in the "From Director's Desk" box.</p>
        </div>

        <?php if($message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <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" role="alert">
                <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; ?>

        <div class="row g-4">
            <div class="col-lg-8">
                <div class="card p-4">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Top Badge Text</label>
                                <input type="text" name="badge" class="form-control" value="<?php echo htmlspecialchars($director['badge']); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Box Heading</label>
                                <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($director['title']); ?>" required>
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-semibold">Subtitle Description</label>
                                <input type="text" name="subtitle" class="form-control" value="<?php echo htmlspecialchars($director['subtitle']); ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Name <span class="text-danger">*</span></label>
                                <input type="text" name="director_name" class="form-control" value="<?php echo htmlspecialchars($director['director_name']); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Designation <span class="text-danger">*</span></label>
                                <input type="text" name="designation" class="form-control" value="<?php echo htmlspecialchars($director['designation']); ?>" required>
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-semibold">Change Photo (Leave empty to keep current)</label>
                                <input type="file" name="image" class="form-control" accept="image/*" onchange="previewDirector(this)">
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-semibold">Director's Message / Quote</label>
                                <textarea name="quote" class="form-control" rows="4" required><?php echo htmlspecialchars($director['quote']); ?></textarea>
                            </div>
                            <div class="col-12 mt-4">
                                <button type="submit" class="btn btn-primary px-5 py-2 fw-semibold">
                                    <i class="fas fa-save me-2"></i> Save All Changes
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Preview Card -->
            <div class="col-lg-4">
                <div class="card p-4 text-center">
                    <h5 class="fw-bold mb-3">Live Box Preview</h5>
                    <div class="p-3 bg-light rounded-4 border">
                        <span class="badge bg-danger text-white mb-2"><?php echo htmlspecialchars($director['badge']); ?></span>
                        <h5 class="fw-bold mb-1"><?php echo htmlspecialchars($director['title']); ?></h5>
                        <p class="small text-muted mb-3"><?php echo htmlspecialchars($director['subtitle']); ?></p>

                        <div class="director-preview-box mb-2">
                            <img id="live_preview" src="<?php echo htmlspecialchars($img_display); ?>" alt="<?php echo htmlspecialchars($director['director_name']); ?>" onerror="this.src='https://ibvte.com/assets/images/secretary_furkan.webp';">
                        </div>

                        <span class="d-block text-muted small fw-semibold"><?php echo htmlspecialchars($director['designation']); ?></span>
                        <h6 class="fw-bold text-dark fs-5 mb-3"><?php echo htmlspecialchars($director['director_name']); ?></h6>

                        <div class="p-2 bg-white rounded-3 shadow-sm text-start">
                            <p class="small fst-italic mb-0 text-muted">
                                &ldquo;<?php echo htmlspecialchars($director['quote']); ?>&rdquo;
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function previewDirector(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('live_preview').src = e.target.result;
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>
