<?php
require_once __DIR__ . '/auth-check.php';
require_once __DIR__ . '/../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: settings.php');
    exit;
}

$settings = getData('settings');
$tab = $_POST['tab'] ?? 'general';

// General tab
if ($tab === 'general') {
    $fields = ['hero_headline','hero_subtext','about_text','phone','whatsapp','email','address','hours','parent_site','facebook','youtube','linkedin','twitter','instagram'];
    foreach ($fields as $f) {
        if (isset($_POST[$f])) $settings[$f] = trim($_POST[$f]);
    }
}

// Packages tab
if ($tab === 'packages') {
    if (isset($_POST['package_shell_title'])) $settings['package_shell_title'] = trim($_POST['package_shell_title']);
    if (isset($_POST['package_shell_features'])) $settings['package_shell_features'] = array_filter(array_map('trim', explode("\n", $_POST['package_shell_features'])));
    if (isset($_POST['package_space_title'])) $settings['package_space_title'] = trim($_POST['package_space_title']);
    if (isset($_POST['package_space_features'])) $settings['package_space_features'] = array_filter(array_map('trim', explode("\n", $_POST['package_space_features'])));
    if (isset($_POST['package_pavilion_title'])) $settings['package_pavilion_title'] = trim($_POST['package_pavilion_title']);
    if (isset($_POST['package_pavilion_features'])) $settings['package_pavilion_features'] = array_filter(array_map('trim', explode("\n", $_POST['package_pavilion_features'])));
    if (isset($_POST['all_packages_include'])) $settings['all_packages_include'] = array_filter(array_map('trim', explode("\n", $_POST['all_packages_include'])));
}

// SEO tab
if ($tab === 'seo') {
    $seoKeys = [
        'seo_home_title','seo_home_desc','seo_about_title','seo_about_desc',
        'seo_sectors_title','seo_sectors_desc','seo_exhibitors_title','seo_exhibitors_desc',
        'seo_register_title','seo_register_desc','seo_gallery_title','seo_gallery_desc',
        'seo_faq_title','seo_faq_desc','seo_contact_title','seo_contact_desc'
    ];
    foreach ($seoKeys as $k) {
        if (isset($_POST[$k])) $settings[$k] = trim($_POST[$k]);
    }
}

saveData('settings', $settings);
setFlash('success', 'Settings saved successfully');
header('Location: settings.php?tab=' . $tab);
exit;
