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

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

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

// Default values
$defaults = [
    'contact_title' => 'Contact Us',
    'contact_description' => 'Have questions? Reach out to IT Galaxy Academy for support or inquiries about our courses.',
    'address' => '123 Galaxy Avenue, Tech City, TC 12345',
    'phone' => '+1 (555) 123-4567',
    'email' => 'contact@itgalaxyacademy.com',
    'hours' => 'Mon-Fri: 9 AM - 5 PM',
    'map_url' => 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3022.1422937950147!2d-73.98731968459392!3d40.74844797932881!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x89c259a9b311f5c5%3A0x7d8b8e2f9c7d8e2f!2sEmpire%20State%20Building!5e0!3m2!1sen!2sus!4v1700000000000!5m2!1sen!2sus'
];

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

    $contact_title = trim($_POST['contact_title'] ?? '');
    $contact_description = trim($_POST['contact_description'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $hours = trim($_POST['hours'] ?? '');
    $map_url = trim($_POST['map_url'] ?? '');

    // Validation
    if (empty($contact_title)) $errors[] = "Page title is required.";
    if (empty($contact_description)) $errors[] = "Page description is required.";
    if (empty($address)) $errors[] = "Address is required.";
    if (empty($phone)) $errors[] = "Phone number is required.";
    if (empty($email)) $errors[] = "Email is required.";
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format.";
    if (empty($hours)) $errors[] = "Office hours are required.";
    if (empty($map_url)) $errors[] = "Google Maps URL is required.";
    elseif (!filter_var($map_url, FILTER_VALIDATE_URL)) $errors[] = "Invalid Google Maps URL.";

    // Save to DB
    if (empty($errors)) {
        if (!empty($contact['id'])) {
            // UPDATE
            $stmt = $conn->prepare("
                UPDATE manage_contact SET 
                contact_title=?, contact_description=?,
                address=?, phone=?, email=?, hours=?, map_url=?
                WHERE id=?
            ");
            $stmt->bind_param("sssssssi", 
                $contact_title, $contact_description,
                $address, $phone, $email, $hours, $map_url, $contact['id']
            );
        } else {
            // INSERT
            $stmt = $conn->prepare("
                INSERT INTO manage_contact (
                contact_title, contact_description,
                address, phone, email, hours, map_url
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param("sssssss", 
                $contact_title, $contact_description,
                $address, $phone, $email, $hours, $map_url
            );
        }

        if ($stmt->execute()) {
            $success = "Contact page updated successfully!";
            $contact = $conn->query("SELECT * FROM manage_contact 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 Contact 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; }
        .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; }
        .preview-map { width: 100%; height: 300px; border: 0; border-radius: 0.75rem; margin-top: 1rem; }
        .section-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem; color: #1F2937; }
        @media (max-width: 768px) { .content { margin-left: 0 !important; } }
        @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-4xl mx-auto my-8">
        <h2 class="text-3xl font-bold text-gray-800 mb-6 text-center">Manage Contact 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" class="space-y-6">
            <input type="hidden" name="update_contact" value="1">

            <!-- Page Title & Description -->
            <div class="form-card">
                <h3 class="section-title">Page Header</h3>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Page Title</label>
                    <input type="text" name="contact_title" value="<?php echo htmlspecialchars($contact['contact_title'] ?? $defaults['contact_title']); ?>" class="w-full p-3 border rounded-lg" required>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Page Description</label>
                    <textarea name="contact_description" rows="3" class="w-full p-3 border rounded-lg" required><?php echo htmlspecialchars($contact['contact_description'] ?? $defaults['contact_description']); ?></textarea>
                </div>
            </div>

            <!-- Contact Details -->
            <div class="form-card">
                <h3 class="section-title">Contact Details</h3>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Address</label>
                    <textarea name="address" rows="2" class="w-full p-3 border rounded-lg" required><?php echo htmlspecialchars($contact['address'] ?? $defaults['address']); ?></textarea>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Phone</label>
                    <input type="text" name="phone" value="<?php echo htmlspecialchars($contact['phone'] ?? $defaults['phone']); ?>" class="w-full p-3 border rounded-lg" required>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Email</label>
                    <input type="email" name="email" value="<?php echo htmlspecialchars($contact['email'] ?? $defaults['email']); ?>" class="w-full p-3 border rounded-lg" required>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Office Hours</label>
                    <input type="text" name="hours" value="<?php echo htmlspecialchars($contact['hours'] ?? $defaults['hours']); ?>" class="w-full p-3 border rounded-lg" required>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Google Maps Embed URL</label>
                    <input type="url" name="map_url" value="<?php echo htmlspecialchars($contact['map_url'] ?? $defaults['map_url']); ?>" class="w-full p-3 border rounded-lg" placeholder="https://www.google.com/maps/embed?..." required>
                    <p class="text-xs text-gray-500 mt-1">Get embed URL from <a href="https://www.google.com/maps" target="_blank" class="text-blue-600">Google Maps → Share → Embed</a></p>
                </div>

                <!-- Live Map Preview -->
                <?php if (!empty($contact['map_url'])): ?>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Map Preview</label>
                    <iframe src="<?php echo htmlspecialchars($contact['map_url']); ?>" class="preview-map" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
                </div>
                <?php endif; ?>
            </div>

            <!-- Submit Buttons -->
            <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 Contact 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>