<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $setting_key = $_POST['setting_key'] ?? '';
    $setting_value = $_POST['setting_value'] ?? '';
    
    if ($setting_key && $setting_value) {
        try {
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, setting_group, is_public, updated_at) 
                                  VALUES (?, ?, 'website', 1, NOW()) 
                                  ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()");
            $stmt->execute([$setting_key, $setting_value]);
            
            $success = "Website content updated successfully!";
            
        } catch (Exception $e) {
            $error = "Failed to update website content. Please try again.";
        }
    } else {
        $error = "Please fill in all required fields.";
    }
}

// Get website content
$website_content = [
    'home_hero_title' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'home_hero_title'")->fetchColumn() ?: 'Helping Students Achieve Their International Education Dreams',
    'home_hero_subtitle' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'home_hero_subtitle'")->fetchColumn() ?: 'Expert guidance for studying abroad in the UK, USA, Canada, Australia, and more',
    'about_title' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'about_title'")->fetchColumn() ?: 'About JV Overseas Education',
    'about_content' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'about_content'")->fetchColumn() ?: 'JV Overseas Education has been helping Ugandan students achieve their international education dreams since 2010. Our expert counselors provide comprehensive support throughout the entire study abroad journey.',
    'services_title' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'services_title'")->fetchColumn() ?: 'Our Services',
    'services_content' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'services_content'")->fetchColumn() ?: 'We offer a comprehensive range of services to support students throughout their study abroad journey.',
    'contact_email' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'contact_email'")->fetchColumn() ?: 'info@jveducation.com',
    'contact_phone' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'contact_phone'")->fetchColumn() ?: '+256 788 289 235',
    'contact_address' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'contact_address'")->fetchColumn() ?: 'Kampala, Uganda',
];

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Website Content - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .content-section {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }
        .section-title {
            border-bottom: 2px solid #3fb7fe;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Content Management</h6>
        <h1 class="display-5">Manage Website Content</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="POST">
        <!-- Home Page Content -->
        <div class="content-section">
            <h5 class="section-title">Home Page</h5>
            
            <div class="form-group">
                <label>Hero Title</label>
                <input type="text" name="setting_value" value="<?= htmlspecialchars($website_content['home_hero_title']) ?>" 
                       class="form-control" data-key="home_hero_title">
                <small class="form-text text-muted">Main title on the home page hero section</small>
            </div>
            
            <div class="form-group">
                <label>Hero Subtitle</label>
                <input type="text" name="setting_value" value="<?= htmlspecialchars($website_content['home_hero_subtitle']) ?>" 
                       class="form-control" data-key="home_hero_subtitle">
                <small class="form-text text-muted">Subtitle on the home page hero section</small>
            </div>
        </div>

        <!-- About Page Content -->
        <div class="content-section">
            <h5 class="section-title">About Page</h5>
            
            <div class="form-group">
                <label>Title</label>
                <input type="text" name="setting_value" value="<?= htmlspecialchars($website_content['about_title']) ?>" 
                       class="form-control" data-key="about_title">
            </div>
            
            <div class="form-group">
                <label>Content</label>
                <textarea name="setting_value" class="form-control" rows="5" 
                          data-key="about_content"><?= htmlspecialchars($website_content['about_content']) ?></textarea>
            </div>
        </div>

        <!-- Services Page Content -->
        <div class="content-section">
            <h5 class="section-title">Services Page</h5>
            
            <div class="form-group">
                <label>Title</label>
                <input type="text" name="setting_value" value="<?= htmlspecialchars($website_content['services_title']) ?>" 
                       class="form-control" data-key="services_title">
            </div>
            
            <div class="form-group">
                <label>Content</label>
                <textarea name="setting_value" class="form-control" rows="5" 
                          data-key="services_content"><?= htmlspecialchars($website_content['services_content']) ?></textarea>
            </div>
        </div>

        <!-- Contact Information -->
        <div class="content-section">
            <h5 class="section-title">Contact Information</h5>
            
            <div class="form-group">
                <label>Email</label>
                <input type="email" name="setting_value" value="<?= htmlspecialchars($website_content['contact_email']) ?>" 
                       class="form-control" data-key="contact_email">
            </div>
            
            <div class="form-group">
                <label>Phone</label>
                <input type="text" name="setting_value" value="<?= htmlspecialchars($website_content['contact_phone']) ?>" 
                       class="form-control" data-key="contact_phone">
            </div>
            
            <div class="form-group">
                <label>Address</label>
                <input type="text" name="setting_value" value="<?= htmlspecialchars($website_content['contact_address']) ?>" 
                       class="form-control" data-key="contact_address">
            </div>
        </div>

        <button type="submit" class="btn btn-primary">Save All Changes</button>
    </form>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    // Update hidden input with the correct setting_key when form is submitted
    $('form').on('submit', function(e) {
        // Prevent default form submission
        e.preventDefault();
        
        // Get all inputs with data-key attribute
        $('input[name="setting_value"], textarea[name="setting_value"]').each(function() {
            const settingKey = $(this).data('key');
            const settingValue = $(this).val();
            
            // Create hidden input with correct name
            const hiddenInput = $('<input>')
                .attr('type', 'hidden')
                .attr('name', 'setting_key')
                .val(settingKey);
                
            const hiddenValue = $('<input>')
                .attr('type', 'hidden')
                .attr('name', 'setting_value')
                .val(settingValue);
                
            // Add to form
            $(this).after(hiddenInput).after(hiddenValue);
        });
        
        // Submit form
        e.target.submit();
    });
</script>
</body>
</html>