<?php
require_once 'admin-header.php'; 
$page_title = 'Site Settings & Customizer';

// --- File Upload Logic for Logos ---
if (!function_exists('handle_logo_upload')) {
    function handle_logo_upload($file_input_name, $setting_name, $max_width = 200) {
        global $conn;
        if (isset($_FILES[$file_input_name]) && $_FILES[$file_input_name]['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES[$file_input_name];
            $upload_dir = '../uploads/logos/';
            if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
            $filename = uniqid(str_replace('site_logo_', '', $setting_name) . '-', true) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $target_path = $upload_dir . $filename;
            $image_type = exif_imagetype($file['tmp_name']);
            if (in_array($image_type, [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP])) {
                if (move_uploaded_file($file['tmp_name'], $target_path)) {
                    $db_path = 'uploads/logos/' . $filename;
                    $stmt = $conn->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_name = ?");
                    $stmt->bind_param("ss", $db_path, $setting_name);
                    $stmt->execute();
                    $stmt->close();
                    return true;
                }
            }
        }
        return false;
    }
}

// --- Hero Background Upload Logic ---
if (!function_exists('handle_hero_upload')) {
    function handle_hero_upload($file_input_name) {
        global $conn;
        if (isset($_FILES[$file_input_name]) && $_FILES[$file_input_name]['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES[$file_input_name];
            $upload_dir = '../uploads/site/';
            if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
            $filename = 'hero-background-' . uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $target_path = $upload_dir . $filename;
            if (move_uploaded_file($file['tmp_name'], $target_path)) {
                $db_path = 'uploads/site/' . $filename;
                $setting_key = 'banner_image_url';
                $stmt = $conn->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_name = ?");
                $stmt->bind_param("ss", $db_path, $setting_key);
                $stmt->execute();
                $stmt->close();
                return true;
            }
        }
        return false;
    }
}

// --- Handle Form Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $settings_keys_result = $conn->query("SELECT setting_name FROM site_settings");
    $valid_keys = [];
    while($row = $settings_keys_result->fetch_assoc()) {
        $valid_keys[] = $row['setting_name'];
    }
    foreach ($_POST as $key => $value) {
        if (in_array($key, $valid_keys)) {
            $stmt = $conn->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_name = ?");
            $stmt->bind_param("ss", $value, $key);
            $stmt->execute();
            $stmt->close();
        }
    }
    handle_logo_upload('new_logo_light', 'site_logo_url');
    handle_logo_upload('new_logo_dark', 'site_logo_dark_url');
    handle_hero_upload('new_banner_image');
    $_SESSION['success_message'] = "Settings updated successfully.";
    header("Location: site-settings.php");
    exit();
}
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="bi bi-sliders me-2"></i><?php echo $page_title; ?></h1>
</div>

<form method="POST" enctype="multipart/form-data">
    <div class="card shadow-sm">
        <div class="card-header"><ul class="nav nav-tabs card-header-tabs" id="settingsTabs" role="tablist"><li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#header-footer" type="button">📄 Header & Footer</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#branding" type="button">🎨 Branding</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#banners" type="button">🖼️ Banners</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#apis" type="button">🔑 APIs</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#payments" type="button">💳 Payments</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#mailer" type="button">📧 Mailer</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#seo" type="button">📈 SEO</button></li></ul></div>
        <div class="card-body">
            <div class="tab-content p-2" id="settingsTabsContent">
                <div class="tab-pane fade show active" id="header-footer" role="tabpanel">
                    <h5>Header Content</h5><div class="row"><div class="col-md-6 mb-3"><label class="form-label">Header Contact Phone</label><input type="text" class="form-control" name="header_contact_phone" value="<?php echo htmlspecialchars($settings['header_contact_phone'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Header Contact Email</label><input type="email" class="form-control" name="header_contact_email" value="<?php echo htmlspecialchars($settings['header_contact_email'] ?? ''); ?>"></div></div><hr>
                    <h5>Footer Content</h5><div class="mb-3"><label class="form-label">Footer "About" Text</label><textarea class="form-control" name="footer_about_text" rows="3"><?php echo htmlspecialchars($settings['footer_about_text'] ?? ''); ?></textarea></div><div class="mb-3"><label class="form-label">Footer Copyright Text</label><input type="text" class="form-control" name="footer_copyright_text" value="<?php echo htmlspecialchars($settings['footer_copyright_text'] ?? ''); ?>"></div><h6>Social Media Links</h6><div class="row"><div class="col-md-4 mb-3"><label class="form-label">Facebook URL</label><input type="text" class="form-control" name="footer_social_facebook_url" value="<?php echo htmlspecialchars($settings['footer_social_facebook_url'] ?? ''); ?>"></div><div class="col-md-4 mb-3"><label class="form-label">Instagram URL</label><input type="text" class="form-control" name="footer_social_instagram_url" value="<?php echo htmlspecialchars($settings['footer_social_instagram_url'] ?? ''); ?>"></div><div class="col-md-4 mb-3"><label class="form-label">Twitter URL</label><input type="text" class="form-control" name="footer_social_twitter_url" value="<?php echo htmlspecialchars($settings['footer_social_twitter_url'] ?? ''); ?>"></div></div>
                </div>
                <div class="tab-pane fade" id="branding" role="tabpanel"><h5>Logos & Colors</h5><div class="row"><div class="col-md-6 mb-3"><label class="form-label">Logo (Light Backgrounds)</label><br><img src="../<?php echo htmlspecialchars($settings['site_logo_url'] ?? ''); ?>" style="max-height: 40px; background: #f8f9fa; padding: 5px; border-radius: 5px;"><label for="new_logo_light" class="form-label mt-2">Upload New</label><input type="file" class="form-control" id="new_logo_light" name="new_logo_light"></div><div class="col-md-6 mb-3"><label class="form-label">Logo (Dark Backgrounds)</label><br><img src="../<?php echo htmlspecialchars($settings['site_logo_dark_url'] ?? ''); ?>" style="max-height: 40px; background: #212529; padding: 5px; border-radius: 5px;"><label for="new_logo_dark" class="form-label mt-2">Upload New</label><input type="file" class="form-control" id="new_logo_dark" name="new_logo_dark"></div><div class="col-md-6 mb-3"><label for="color_primary" class="form-label">Primary Color</label><input type="color" class="form-control form-control-color" id="color_primary" name="color_primary" value="<?php echo htmlspecialchars($settings['color_primary'] ?? '#0d6efd'); ?>"></div><div class="col-md-6 mb-3"><label for="color_secondary" class="form-label">Secondary Color</label><input type="color" class="form-control form-control-color" id="color_secondary" name="color_secondary" value="<?php echo htmlspecialchars($settings['color_secondary'] ?? '#6c757d'); ?>"></div></div></div>
                <div class="tab-pane fade" id="banners" role="tabpanel"><h5 class="card-title">Homepage Main Banner</h5><div class="row"><div class="col-md-6 mb-3"><label class="form-label">Heading</label><input type="text" class="form-control" name="banner_heading" value="<?php echo htmlspecialchars($settings['banner_heading'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Subheading</label><input type="text" class="form-control" name="banner_subheading" value="<?php echo htmlspecialchars($settings['banner_subheading'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Button Text</label><input type="text" class="form-control" name="banner_btn_text" value="<?php echo htmlspecialchars($settings['banner_btn_text'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Button Link</label><input type="text" class="form-control" name="banner_btn_link" value="<?php echo htmlspecialchars($settings['banner_btn_link'] ?? ''); ?>"></div><div class="col-12 mb-3"><label for="new_banner_image" class="form-label">Upload Background Image</label><input type="file" class="form-control" id="new_banner_image" name="new_banner_image" accept="image/*"><?php if (!empty($settings['banner_image_url'])): ?><div class="mt-2"><img src="../<?php echo htmlspecialchars($settings['banner_image_url']); ?>" style="max-height: 100px; border-radius: 5px;" class="mt-1"></div><?php endif; ?></div></div><hr><h5 class="card-title">Top Notification Banner</h5><div class="row"><div class="col-md-8 mb-3"><label class="form-label">Banner Text</label><input type="text" class="form-control" name="notification_banner_text" value="<?php echo htmlspecialchars($settings['notification_banner_text'] ?? ''); ?>"></div><div class="col-md-4 mb-3"><label class="form-label">Status</label><select class="form-select" name="notification_banner_status"><option value="active" <?php echo ($settings['notification_banner_status'] ?? '') === 'active' ? 'selected' : ''; ?>>Active</option><option value="inactive" <?php echo ($settings['notification_banner_status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option></select></div></div></div>
                <div class="tab-pane fade" id="apis" role="tabpanel"><h5>API Keys & Integrations</h5><div class="row"><div class="col-md-6 mb-3"><label class="form-label">TinyMCE API Key</label><input type="text" class="form-control" name="tinymce_api_key" value="<?php echo htmlspecialchars($settings['tinymce_api_key'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Google Analytics ID</label><input type="text" class="form-control" name="google_analytics_id" value="<?php echo htmlspecialchars($settings['google_analytics_id'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Google Maps API Key</label><input type="password" class="form-control" name="google_maps_key" value="<?php echo htmlspecialchars($settings['google_maps_key'] ?? ''); ?>"></div></div></div>
                <div class="tab-pane fade" id="payments" role="tabpanel"><h5>Payment Gateways</h5><h6>PayPal</h6><div class="row"><div class="col-md-6 mb-3"><label class="form-label">Client ID</label><input type="text" class="form-control" name="paypal_client_id" value="<?php echo htmlspecialchars($settings['paypal_client_id'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Mode</label><select class="form-select" name="paypal_mode"><option value="sandbox" <?php echo ($settings['paypal_mode'] ?? '') === 'sandbox' ? 'selected' : ''; ?>>Sandbox</option><option value="live" <?php echo ($settings['paypal_mode'] ?? '') === 'live' ? 'selected' : ''; ?>>Live</option></select></div></div></div>
                <div class="tab-pane fade" id="mailer" role="tabpanel"><h5>SMTP Mailer</h5><div class="row"><div class="col-md-6 mb-3"><label class="form-label">SMTP Host</label><input type="text" class="form-control" name="smtp_host" value="<?php echo htmlspecialchars($settings['smtp_host'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">SMTP Port</label><input type="text" class="form-control" name="smtp_port" value="<?php echo htmlspecialchars($settings['smtp_port'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">SMTP Username</label><input type="password" class="form-control" name="smtp_username" value="<?php echo htmlspecialchars($settings['smtp_username'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">SMTP Password</label><input type="password" class="form-control" name="smtp_password" value="<?php echo htmlspecialchars($settings['smtp_password'] ?? ''); ?>"></div></div></div>
                <div class="tab-pane fade" id="seo" role="tabpanel"><h5>SEO Settings</h5><div class="mb-3"><label class="form-label">Meta Title</label><input type="text" class="form-control" name="seo_meta_title" value="<?php echo htmlspecialchars($settings['seo_meta_title'] ?? ''); ?>"></div><div class="mb-3"><label class="form-label">Meta Description</label><textarea class="form-control" name="seo_meta_description" rows="3"><?php echo htmlspecialchars($settings['seo_meta_description'] ?? ''); ?></textarea></div><div class="mb-3"><label class="form-label">Meta Keywords</label><input type="text" class="form-control" name="seo_meta_keywords" value="<?php echo htmlspecialchars($settings['seo_meta_keywords'] ?? ''); ?>"></div></div>
            </div>
        </div>
        <div class="card-footer text-end"><button type="submit" class="btn btn-primary btn-lg">Save All Settings</button></div>
    </div>
</form>

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