<?php
include "include/db.php";
include "include/header.php";

$errors = [];
$success = '';

// ---------- FETCH CURRENT DATA ----------
$about_result = $conn->query("SELECT * FROM manage_about LIMIT 1");
$about = $about_result->num_rows > 0 ? $about_result->fetch_assoc() : [];

// Default values for section titles
$defaults = [
    'mission_title' => 'Our Mission',
    'team_section_title' => 'Meet Our Team',
    'values_section_title' => 'Our Core Values'
];

// ---------- IMAGE UPLOAD SETTINGS ----------
$upload_dir = "uploads/about/"; // create this folder
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$max_size = 2 * 1024 * 1024; // 2 MB

if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

// ---------- HANDLE FORM ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_about'])) {

    // ----- TEXT FIELDS -----
    $about_title = trim($_POST['about_title'] ?? '');
    $about_description = trim($_POST['about_description'] ?? '');
    $mission_title = trim($_POST['mission_title'] ?? '');
    $mission_text = trim($_POST['mission_text'] ?? '');
    $team_section_title = trim($_POST['team_section_title'] ?? '');
    $values_section_title = trim($_POST['values_section_title'] ?? '');

    // Team Members
    $team = [];
    for ($i = 1; $i <= 3; $i++) {
        $team[$i]['name'] = trim($_POST["team_name_$i"] ?? '');
        $team[$i]['role'] = trim($_POST["team_role_$i"] ?? '');
        $team[$i]['image'] = $about["team_image_$i"] ?? ''; // keep old
    }

    // Core Values
    $values = [];
    for ($i = 1; $i <= 3; $i++) {
        $values[$i]['title'] = trim($_POST["value_title_$i"] ?? '');
        $values[$i]['desc'] = trim($_POST["value_desc_$i"] ?? '');
    }

    // ----- VALIDATION -----
    if (empty($about_title)) $errors[] = "About title is required.";
    if (empty($about_description)) $errors[] = "About description is required.";
    if (empty($mission_text)) $errors[] = "Mission text is required.";

    foreach ($team as $i => $member) {
        if (empty($member['name'])) $errors[] = "Team member $i name is required.";
        if (empty($member['role'])) $errors[] = "Team member $i role is required.";
    }

    foreach ($values as $i => $value) {
        if (empty($value['title'])) $errors[] = "Core value $i title is required.";
        if (empty($value['desc'])) $errors[] = "Core value $i description is required.";
    }

    // Use defaults if titles are empty
    $mission_title = !empty($mission_title) ? $mission_title : $defaults['mission_title'];
    $team_section_title = !empty($team_section_title) ? $team_section_title : $defaults['team_section_title'];
    $values_section_title = !empty($values_section_title) ? $values_section_title : $defaults['values_section_title'];

    // ----- IMAGE HANDLING (Team Photos) -----
    for ($i = 1; $i <= 3; $i++) {
        if (isset($_FILES["team_image_$i"]) && $_FILES["team_image_$i"]['error'] === UPLOAD_ERR_OK) {
            $file_tmp = $_FILES["team_image_$i"]['tmp_name'];
            $file_name = basename($_FILES["team_image_$i"]['name']);
            $file_size = $_FILES["team_image_$i"]['size'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            if (!in_array($file_ext, $allowed)) {
                $errors[] = "Team member $i image: only JPG, JPEG, PNG & GIF allowed.";
            } elseif ($file_size > $max_size) {
                $errors[] = "Team member $i image must be ≤ 2 MB.";
            } else {
                $new_name = uniqid("team_{$i}_") . '.' . $file_ext;
                $dest = $upload_dir . $new_name;
                if (move_uploaded_file($file_tmp, $dest)) {
                    // Delete old image
                    $old_img = $about["team_image_$i"] ?? '';
                    if (!empty($old_img) && file_exists($upload_dir . $old_img)) {
                        @unlink($upload_dir . $old_img);
                    }
                    $team[$i]['image'] = $new_name;
                } else {
                    $errors[] = "Failed to upload team member $i image.";
                }
            }
        }
    }

    // ----- SAVE TO DB -----
    if (empty($errors)) {
        if (!empty($about['id'])) {
            // UPDATE
            $stmt = $conn->prepare("
                UPDATE manage_about SET
                    about_title=?, about_description=?, 
                    mission_title=?, mission_text=?,
                    team_section_title=?,
                    team_name_1=?, team_role_1=?, team_image_1=?,
                    team_name_2=?, team_role_2=?, team_image_2=?,
                    team_name_3=?, team_role_3=?, team_image_3=?,
                    values_section_title=?,
                    value_title_1=?, value_desc_1=?,
                    value_title_2=?, value_desc_2=?,
                    value_title_3=?, value_desc_3=?
                WHERE id=?
            ");
            $stmt->bind_param(
                "sssssssssssssssssssssi",
                $about_title, $about_description, 
                $mission_title, $mission_text,
                $team_section_title,
                $team[1]['name'], $team[1]['role'], $team[1]['image'],
                $team[2]['name'], $team[2]['role'], $team[2]['image'],
                $team[3]['name'], $team[3]['role'], $team[3]['image'],
                $values_section_title,
                $values[1]['title'], $values[1]['desc'],
                $values[2]['title'], $values[2]['desc'],
                $values[3]['title'], $values[3]['desc'],
                $about['id']
            );
        } else {
            // INSERT
            $stmt = $conn->prepare("
                INSERT INTO manage_about (
                    about_title, about_description, 
                    mission_title, mission_text,
                    team_section_title,
                    team_name_1, team_role_1, team_image_1,
                    team_name_2, team_role_2, team_image_2,
                    team_name_3, team_role_3, team_image_3,
                    values_section_title,
                    value_title_1, value_desc_1,
                    value_title_2, value_desc_2,
                    value_title_3, value_desc_3
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ");
            $stmt->bind_param(
                "ssssssssssssssssssssss",
                $about_title, $about_description, 
                $mission_title, $mission_text,
                $team_section_title,
                $team[1]['name'], $team[1]['role'], $team[1]['image'],
                $team[2]['name'], $team[2]['role'], $team[2]['image'],
                $team[3]['name'], $team[3]['role'], $team[3]['image'],
                $values_section_title,
                $values[1]['title'], $values[1]['desc'],
                $values[2]['title'], $values[2]['desc'],
                $values[3]['title'], $values[3]['desc']
            );
        }

        if ($stmt->execute()) {
            $success = "About page updated successfully!";
            $about = $conn->query("SELECT * FROM manage_about LIMIT 1")->fetch_assoc();
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage About Page - IT Galaxy Academy</title>
    <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
    <style>
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; background: #f9fafb; }
        .content { transition: margin-left 0.3s ease; }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        .form-card { background: white; padding: 2rem; border-radius: 1rem; box-shadow: 0 10px 25px rgba(0,0,0,0.1); margin-bottom: 2rem; }
        .error { color: #DC2626; background: #FEE2E2; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem; }
        .success { color: #10B981; background: #ECFDF5; padding: 1rem; border-radius: 0.5rem; text-align: center; font-weight: bold; margin-bottom: 1rem; }
        .input-group { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .section-divider { border-top: 2px solid #E5E7EB; padding-top: 1.5rem; margin-top: 1.5rem; }
        .preview-img { max-width: 100%; height: auto; margin-top: .5rem; border-radius: .5rem; max-height: 200px; object-fit: cover; }
        .team-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1.5rem; }
        .value-card { background: #f8f9fa; padding: 1rem; border-radius: 0.75rem; }
        @media (max-width: 768px) {
            .content { margin-left: 0 !important; }
            .input-group { display: block; }
        }
        @media (min-width: 769px) { .content { margin-left: 250px; } }
    </style>
</head>
<body>
<div id="content" class="content p-6 min-h-screen">
    <?php include "include/topnav.php"; ?>
    <div class="max-w-5xl mx-auto my-8">
        <h2 class="text-3xl font-bold text-gray-800 mb-6 text-center">Manage About Page</h2>

        <?php if ($success): ?>
            <div class="success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <div class="error">
                <?php foreach ($errors as $e): ?>
                    <p><?php echo htmlspecialchars($e); ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data" class="space-y-6">
            <input type="hidden" name="update_about" value="1">

            <!-- ==================== ABOUT SECTION ==================== -->
            <div class="form-card">
                <h3 class="text-xl font-semibold mb-4">About IT Galaxy Academy</h3>
                <input type="text" name="about_title" value="<?php echo htmlspecialchars($about['about_title'] ?? 'About IT Galaxy Academy'); ?>"
                       placeholder="About Title" class="w-full p-3 border rounded-lg" required>
                <textarea name="about_description" rows="3" placeholder="Empowering the next generation..."
                          class="w-full p-3 border rounded-lg mt-3" required><?php echo htmlspecialchars($about['about_description'] ?? 'Empowering the next generation of robotics innovators through world-class education, hands-on training, and cutting-edge technology.'); ?></textarea>
            </div>

            <!-- ==================== MISSION ==================== -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Our Mission Section</h3>
                
                <input type="text" name="mission_title" 
                       value="<?php echo htmlspecialchars($about['mission_title'] ?? 'Our Mission'); ?>"
                       placeholder="Section Title (e.g. Our Mission)" 
                       class="w-full p-3 border rounded-lg mb-3">

                <textarea name="mission_text" rows="5" placeholder="Founded in 2023..."
                          class="w-full p-3 border rounded-lg" required><?php echo htmlspecialchars($about['mission_text'] ?? 'Founded in 2023, IT Galaxy Academy is committed to revolutionizing robotics education. We provide immersive, practical training that transforms students into industry-ready professionals, fostering innovation and building a global community of tech leaders.'); ?></textarea>
            </div>

            <!-- ==================== TEAM MEMBERS ==================== -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Team Section</h3>
                
                <input type="text" name="team_section_title" 
                       value="<?php echo htmlspecialchars($about['team_section_title'] ?? 'Meet Our Team'); ?>"
                       placeholder="Section Title (e.g. Meet Our Team)" 
                       class="w-full p-3 border rounded-lg mb-4">

                <div class="team-grid">
                    <?php for ($i = 1; $i <= 3; $i++): ?>
                        <div class="border rounded-lg p-4">
                            <input type="text" name="team_name_<?php echo $i; ?>"
                                   value="<?php echo htmlspecialchars($about["team_name_$i"] ?? ($i == 1 ? 'Dr. Aisha Khan' : ($i == 2 ? 'Raj Patel' : 'Lina Chen'))); ?>"
                                   placeholder="Name" class="w-full p-2 border rounded mb-2" required>
                            <input type="text" name="team_role_<?php echo $i; ?>"
                                   value="<?php echo htmlspecialchars($about["team_role_$i"] ?? ($i == 1 ? 'Founder & Robotics Expert' : ($i == 2 ? 'AI & Machine Learning Specialist' : 'Education & Curriculum Lead'))); ?>"
                                   placeholder="Role" class="w-full p-2 border rounded mb-2" required>
                            <label class="block text-sm font-medium mb-1">Photo (≤ 2 MB)</label>
                            <input type="file" name="team_image_<?php echo $i; ?>" accept="image/*" class="w-full text-sm">
                            <?php if (!empty($about["team_image_$i"])): ?>
                                <img src="<?php echo htmlspecialchars($upload_dir . $about["team_image_$i"]); ?>"
                                     alt="Team <?php echo $i; ?>" class="preview-img mt-2">
                            <?php endif; ?>
                        </div>
                    <?php endfor; ?>
                </div>
            </div>

            <!-- ==================== CORE VALUES ==================== -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Core Values Section</h3>
                
                <input type="text" name="values_section_title" 
                       value="<?php echo htmlspecialchars($about['values_section_title'] ?? 'Our Core Values'); ?>"
                       placeholder="Section Title (e.g. Our Core Values)" 
                       class="w-full p-3 border rounded-lg mb-4">

                <div class="space-y-4">
                    <?php for ($i = 1; $i <= 3; $i++): ?>
                        <div class="value-card">
                            <input type="text" name="value_title_<?php echo $i; ?>"
                                   value="<?php echo htmlspecialchars($about["value_title_$i"] ?? ($i == 1 ? 'Innovation' : ($i == 2 ? 'Community' : 'Excellence'))); ?>"
                                   placeholder="Value Title" class="w-full p-2 border rounded mb-2" required>
                            <textarea name="value_desc_<?php echo $i; ?>" rows="2" placeholder="Description..."
                                      class="w-full p-2 border rounded" required><?php echo htmlspecialchars($about["value_desc_$i"] ?? ($i == 1 ? 'Pushing boundaries with creative robotics solutions.' : ($i == 2 ? 'Building a collaborative global network of learners.' : 'Delivering unmatched quality in education and results.'))); ?></textarea>
                        </div>
                    <?php endfor; ?>
                </div>
            </div>

            <!-- ==================== SUBMIT ==================== -->
            <div class="flex gap-4">
                <button type="submit"
                        class="flex-1 bg-yellow-500 text-white p-4 rounded-lg hover:bg-yellow-600 font-bold text-lg">
                    Update About Page
                </button>
                <a href="dashboard.php"
                   class="flex-1 bg-gray-600 text-white p-4 rounded-lg text-center font-bold text-lg">
                    Back to Dashboard
                </a>
            </div>
        </form>
    </div>
</div>

<?php include "include/footer.php"; $conn->close(); ?>
</body>
</html>