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

require_once __DIR__ . '/../../config/config.php';

// Auth Check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../login.php");
    exit();
}

$success_msg = '';
$error_msg = '';
$upload_directory = __DIR__ . '/../../../uploads/system';

// Handle Transparent Logo Upload Safely
function uploadLogoSafely($fileArray, $uploadDir) {
    if (!isset($fileArray['error']) || $fileArray['error'] !== UPLOAD_ERR_OK) return false;
    
    $tmpName = $fileArray['tmp_name'];
    $fileType = mime_content_type($tmpName);
    
    // Only allow PNG or WEBP for logos to preserve transparency
    if (!in_array($fileType, ['image/png', 'image/webp', 'image/jpeg'])) return false;

    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
    
    $ext = ($fileType === 'image/png') ? '.png' : (($fileType === 'image/webp') ? '.webp' : '.jpg');
    $fileName = 'footer_logo_' . time() . $ext;
    $destination = $uploadDir . '/' . $fileName;

    if(move_uploaded_file($tmpName, $destination)) {
        return 'uploads/system/' . $fileName;
    }
    return false;
}

// =========================================================
// MASS UPDATE HANDLER
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_footer'])) {
    
    // 1. Handle Text Content
    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 = 'global'");
            
            foreach ($_POST['content'] as $key => $value) {
                $clean_value = trim($value);
                $update_stmt->execute([$clean_value, $key]);
            }
            $pdo->commit();
            $success_msg = "Global footer matrix synchronized successfully.";
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_msg = "Matrix sync failed: " . $e->getMessage();
        }
    }

    // 2. Handle Logo Upload (if provided)
    if (isset($_FILES['footer_logo']) && $_FILES['footer_logo']['error'] === UPLOAD_ERR_OK) {
        $logo_path = uploadLogoSafely($_FILES['footer_logo'], $upload_directory);
        if ($logo_path) {
            $logo_stmt = $pdo->prepare("UPDATE page_content SET content_value = ? WHERE content_key = 'footer_logo_image'");
            $logo_stmt->execute([$logo_path]);
            $success_msg = "Logo uploaded and footer synchronized successfully.";
        } else {
            $error_msg = "Logo upload failed. Please ensure it is a valid PNG or JPG.";
        }
    }
}

// =========================================================
// FETCH GLOBAL CONTENT
// =========================================================
$global_sections = [];
try {
    $stmt = $pdo->query("SELECT * FROM page_content WHERE page_slug = 'global' ORDER BY section_name ASC");
    $content_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($content_rows as $row) {
        $section = $row['section_name'];
        if (!isset($global_sections[$section])) $global_sections[$section] = [];
        $global_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 - Global Footer 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 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-blue-500/10 border border-blue-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-blue-500 mb-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-blue-400 animate-pulse"></span>
                    <span>Global Elements</span>
                </div>
                <h2 class="text-3xl font-bold text-slate-900 dark:text-white tracking-wide">Footer & Global Matrix</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-1">Manage platform-wide persistent elements like the footer, logo, and copyright data.</p>
            </div>
        </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">
                ✅ <?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">
                ❌ <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <form action="footer-management.php" method="POST" enctype="multipart/form-data" class="w-full max-w-4xl space-y-8 pb-10">
            
            <?php foreach ($global_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-blue-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): 
                            if ($field['content_key'] === 'footer_logo_image') {
                                // Special handling for Logo Upload
                                ?>
                                <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">Custom Footer Logo (PNG Recommended)</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: footer_logo_image</span>
                                    </div>
                                    <div class="flex items-center space-x-4">
                                        <?php if (!empty($field['content_value'])): ?>
                                            <div class="w-16 h-16 bg-slate-950 border border-slate-800 rounded flex items-center justify-center p-2 shrink-0">
                                                <img src="<?php echo SITE_URL . '/' . htmlspecialchars($field['content_value']); ?>" class="max-w-full max-h-full">
                                            </div>
                                        <?php endif; ?>
                                        <input type="file" name="footer_logo" accept="image/png, image/jpeg, image/webp" class="w-full text-slate-500 cursor-pointer file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 dark:file:bg-blue-500/10 dark:file:text-blue-400 hover:file:bg-blue-100 transition">
                                    </div>
                                </div>
                                <?php
                                continue;
                            }

                            // Standard Text Fields
                            $label = ucwords(str_replace('_', ' ', str_replace('footer_', '', $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-blue-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-blue-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_footer" class="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-black font-black py-4 px-8 rounded-xl transition-all shadow-xl shadow-blue-900/30 text-xs tracking-widest uppercase flex items-center space-x-2 border border-blue-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 Global Elements</span>
                </button>
            </div>
            
        </form>

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