<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// PATH ADJUSTMENT: Added an extra '../' because we are now inside the 'cont' folder
require_once __DIR__ . '/../../config/config.php';

// Auth Check (Redirect adjusted to look one folder up for login.php)
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../login.php");
    exit();
}

$success_msg = '';
$error_msg = '';

// =========================================================
// MASS UPDATE HANDLER (Only processes fields sent from this page)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_home'])) {
    if (isset($_POST['content']) && is_array($_POST['content'])) {
        try {
            $pdo->beginTransaction();
            $update_stmt = $pdo->prepare("UPDATE page_content SET content_value = ? WHERE content_key = ? AND page_slug = 'home'");
            
            foreach ($_POST['content'] as $key => $value) {
                $clean_value = trim($value);
                $update_stmt->execute([$clean_value, $key]);
            }
            
            $pdo->commit();
            $success_msg = "Home page content synchronized successfully.";
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_msg = "Matrix sync failed: " . $e->getMessage();
        }
    }
}

// =========================================================
// FETCH CONTENT STRICTLY FOR THE HOME PAGE
// =========================================================
$home_sections = [];
try {
    $stmt = $pdo->query("SELECT * FROM page_content WHERE page_slug = 'home' ORDER BY section_name ASC");
    $content_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Group by section (e.g., "Hero Section", "Call to Action")
    foreach ($content_rows as $row) {
        $section = $row['section_name'];
        if (!isset($home_sections[$section])) {
            $home_sections[$section] = [];
        }
        $home_sections[$section][] = $row;
    }
} catch (PDOException $e) {
    $error_msg = "Database Error: Ensure the page_content table exists.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Home Page Management</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php 
    // PATH ADJUSTMENT: Look one folder up, then into includes
    include __DIR__ . '/../includes/admin-sidebar.php'; 
    ?>

    <main class="flex-1 p-6 md:p-10 overflow-x-hidden flex flex-col gap-6">
        
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
                <div class="inline-flex items-center space-x-2 bg-cyan-500/10 border border-cyan-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-cyan-500 mb-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-cyan-400 animate-pulse"></span>
                    <span>Dynamic Headless CMS</span>
                </div>
                <h2 class="text-3xl font-bold text-slate-900 dark:text-white tracking-wide">Home Page Management</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-1">Control the text matrices specifically rendered on the platform's landing page.</p>
            </div>
            <a href="<?php echo SITE_URL; ?>" target="_blank" class="bg-slate-200 text-slate-600 dark:bg-slate-800 dark:text-gray-300 hover:text-white dark:hover:bg-slate-700 px-4 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider transition border border-slate-300 dark:border-slate-700 flex items-center shadow-sm">
                <span>View Live Site</span>
                <svg class="w-3 h-3 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg>
            </a>
        </div>

        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border border-emerald-200 text-emerald-600 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-500 p-4 rounded-xl text-xs font-bold tracking-wide flex items-center shadow-sm">
                <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border border-rose-200 text-rose-600 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-500 p-4 rounded-xl text-xs font-bold tracking-wide flex items-center shadow-sm">
                <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <form action="home-management.php" method="POST" class="w-full max-w-4xl space-y-8 pb-10">
            
            <?php if(empty($home_sections)): ?>
                <div class="bg-slate-900 border border-slate-800 rounded-2xl p-10 text-center">
                    <span class="text-slate-500 text-xs font-bold uppercase tracking-widest block mb-2">No Content Configured</span>
                    <p class="text-slate-400 text-sm">You need to insert starter rows into the `page_content` table where `page_slug = 'home'`.</p>
                </div>
            <?php else: ?>
                <?php foreach ($home_sections as $section_name => $fields): ?>
                    <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-6 shadow-sm transition-colors duration-300">
                        
                        <div class="flex items-center space-x-3 mb-6 border-b border-slate-200 dark:border-slate-800 pb-3">
                            <div class="w-1 h-5 bg-cyan-500 rounded-sm"></div>
                            <h3 class="font-bold text-lg text-slate-900 dark:text-white">
                                <?php echo htmlspecialchars($section_name); ?>
                            </h3>
                        </div>
                        
                        <div class="space-y-6">
                            <?php foreach ($fields as $field): 
                                $label = ucwords(str_replace('_', ' ', str_replace('home_', '', $field['content_key'])));
                            ?>
                                <div>
                                    <div class="flex justify-between items-center mb-2">
                                        <label class="text-xs text-slate-500 dark:text-gray-400 tracking-wider uppercase font-semibold"><?php echo $label; ?></label>
                                        <span class="text-[9px] font-mono text-cyan-600 dark:text-cyan-500/50 bg-cyan-50 dark:bg-cyan-500/5 border border-cyan-100 dark:border-transparent px-2 py-0.5 rounded">DB Key: <?php echo $field['content_key']; ?></span>
                                    </div>
                                    
                                    <?php if ($field['field_type'] === 'textarea'): ?>
                                        <textarea name="content[<?php echo $field['content_key']; ?>]" rows="3" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-cyan-500 text-sm transition-all resize-y shadow-inner"><?php echo htmlspecialchars($field['content_value'] ?? ''); ?></textarea>
                                    <?php else: ?>
                                        <input type="text" name="content[<?php echo $field['content_key']; ?>]" value="<?php echo htmlspecialchars($field['content_value'] ?? ''); ?>" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-cyan-500 text-sm transition-all shadow-inner">
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
                
                <div class="sticky bottom-6 mt-8 flex justify-end z-40">
                    <button type="submit" name="update_home" class="bg-gradient-to-r from-cyan-600 to-blue-600 hover:from-cyan-500 hover:to-blue-500 text-black font-black py-4 px-8 rounded-xl transition-all shadow-xl shadow-cyan-900/30 text-xs tracking-widest uppercase flex items-center space-x-2 border border-cyan-400/20">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
                        <span>Save Home Contents</span>
                    </button>
                </div>
            <?php endif; ?>
            
        </form>

    </main>
</body>
</html>