<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1;

// Check permissions
$permissionMiddleware = new PermissionMiddleware($integratedAuth, $adminData);
if (!$permissionMiddleware->hasPermission('manage_settings')) {
    header('Location: dashboard.php?error=' . urlencode('Access denied.'));
    exit;
}

$db = new Database();
$message = '';
$messageType = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'update_basic') {
            // Basic website settings
            $siteName = trim($_POST['site_name'] ?? '');
            $siteDescription = trim($_POST['site_description'] ?? '');
            $welcomeText = trim($_POST['welcome_text'] ?? '');
            $marqueeText = trim($_POST['marquee_text'] ?? '');
            $marqueeSpeed = trim($_POST['marquee_speed'] ?? 'slow');
            $existingLogo = trim($_POST['existing_logo'] ?? '');
            
            if (empty($siteName)) {
                throw new Exception('Site name tidak boleh kosong!');
            }
            
            $updates = [
                'site_name' => $siteName,
                'site_description' => $siteDescription,
                'welcome_text' => $welcomeText,
                'marquee_text' => $marqueeText,
                'marquee_speed' => $marqueeSpeed,
                'site_logo' => $existingLogo // Default to existing logo
            ];
            
            // Handle logo upload
            if (isset($_FILES['logo_file']) && $_FILES['logo_file']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../assets/logos/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileExtension = strtolower(pathinfo($_FILES['logo_file']['name'], PATHINFO_EXTENSION));
                $allowedExtensions = ['jpg', 'jpeg', 'png', 'svg', 'webp'];
                
                if (in_array($fileExtension, $allowedExtensions)) {
                    $fileName = 'site_logo_' . time() . '.' . $fileExtension;
                    $filePath = $uploadDir . $fileName;
                    
                    if (move_uploaded_file($_FILES['logo_file']['tmp_name'], $filePath)) {
                        // Store relative path from website root for display
                        $updates['site_logo'] = 'assets/logos/' . $fileName;
                        
                        // Delete old logo if exists
                        if (!empty($existingLogo) && file_exists('../' . $existingLogo)) {
                            unlink('../' . $existingLogo);
                        }
                    } else {
                        throw new Exception('Gagal mengupload logo!');
                    }
                } else {
                    throw new Exception('Format logo tidak didukung! Gunakan JPG, PNG, SVG, atau WebP.');
                }
            }
            
            // Use updateWebsiteSettings for bulk update
            $updateResult = $db->updateWebsiteSettings($updates);
            
            if ($updateResult) {
                $message = 'Pengaturan dasar berhasil diupdate!';
                $messageType = 'success';
                
                // Log activity
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_SETTINGS', 
                    'Updated basic settings', $adminData['type'] ?? 'master');
            } else {
                // More detailed error for debugging
                error_log("Admin settings update failed for basic settings");
                error_log("Update data: " . json_encode($updates));
                
                $connection = $db->getConnection();
                if (!$connection) {
                    throw new Exception('Gagal mengupdate pengaturan! Koneksi database bermasalah.');
                } else {
                    throw new Exception('Gagal mengupdate pengaturan! Periksa log error untuk detail.');
                }
            }
            
        } elseif ($action === 'update_social') {
            // Social media links
            $socialUpdates = [
                'facebook_link' => trim($_POST['facebook_link'] ?? ''),
                'twitter_link' => trim($_POST['twitter_link'] ?? ''),
                'instagram_link' => trim($_POST['instagram_link'] ?? ''),
                'youtube_link' => trim($_POST['youtube_link'] ?? ''),
                'whatsapp_number' => trim($_POST['whatsapp_number'] ?? ''),
                'telegram_link' => trim($_POST['telegram_link'] ?? ''),
                'register_member_link' => trim($_POST['register_link'] ?? ''),
                'login_link' => trim($_POST['login_link'] ?? ''),
                'download_app_link' => trim($_POST['download_app_link'] ?? ''),
                'livechat_link' => trim($_POST['livechat_link'] ?? ''),
                'slot_gacor_link' => trim($_POST['slot_gacor_link'] ?? '')
            ];
            
            // Use updateWebsiteSettings for bulk update
            $socialResult = $db->updateWebsiteSettings($socialUpdates);
            
            if ($socialResult) {
                $message = 'Social media links berhasil diupdate!';
                $messageType = 'success';
                
                // Log activity
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_SOCIAL', 
                    'Updated social media settings', $adminData['type'] ?? 'master');
            } else {
                error_log("Admin settings update failed for social media");
                error_log("Social update data: " . json_encode($socialUpdates));
                throw new Exception('Gagal mengupdate social media links! Periksa koneksi database.');
            }
            
        } elseif ($action === 'update_footer') {
            // Footer information settings
            $footerUpdates = [
                'footer_company_name' => trim($_POST['footer_company_name'] ?? ''),
                'footer_description' => trim($_POST['footer_description'] ?? ''),
                'footer_address' => trim($_POST['footer_address'] ?? ''),
                'footer_phone' => trim($_POST['footer_phone'] ?? ''),
                'contact_email' => trim($_POST['contact_email'] ?? ''),
                'whatsapp_display' => trim($_POST['whatsapp_display'] ?? ''),
                'footer_business_hours' => trim($_POST['footer_business_hours'] ?? ''),
                'footer_copyright_text' => trim($_POST['footer_copyright_text'] ?? ''),
                'footer_disclaimer' => trim($_POST['footer_disclaimer'] ?? '')
            ];
            
            $footerResult = $db->updateWebsiteSettings($footerUpdates);
            
            if ($footerResult) {
                $message = 'Footer information berhasil diupdate!';
                $messageType = 'success';
                
                // Log activity
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_FOOTER', 
                    'Updated footer settings', $adminData['type'] ?? 'master');
            } else {
                error_log("Admin settings update failed for footer");
                error_log("Footer update data: " . json_encode($footerUpdates));
                throw new Exception('Gagal mengupdate footer information! Periksa koneksi database.');
            }
            
        } elseif ($action === 'update_meta') {
            // SEO and meta settings - All 20 fields
            $metaUpdates = [
                // Basic SEO
                'site_title_template' => trim($_POST['site_title_template'] ?? ''),
                'home_title' => trim($_POST['home_title'] ?? ''),
                'meta_keywords' => trim($_POST['meta_keywords'] ?? ''),
                'meta_description' => trim($_POST['meta_description'] ?? ''),
                'meta_author' => trim($_POST['meta_author'] ?? ''),
                'meta_robots' => trim($_POST['meta_robots'] ?? 'index, follow'),
                'canonical_url' => trim($_POST['canonical_url'] ?? ''),
                
                // Open Graph
                'og_title' => trim($_POST['og_title'] ?? ''),
                'og_description' => trim($_POST['og_description'] ?? ''),
                'og_image' => trim($_POST['og_image'] ?? ''),
                'og_type' => trim($_POST['og_type'] ?? 'website'),
                'og_url' => trim($_POST['og_url'] ?? ''),
                
                // Twitter Cards
                'twitter_card' => trim($_POST['twitter_card'] ?? 'summary'),
                'twitter_title' => trim($_POST['twitter_title'] ?? ''),
                'twitter_description' => trim($_POST['twitter_description'] ?? ''),
                'twitter_image' => trim($_POST['twitter_image'] ?? ''),
                
                // Technical SEO
                'favicon_path' => trim($_POST['favicon_path'] ?? ''),
                'theme_color' => trim($_POST['theme_color'] ?? '#007bff'),
                'structured_data_json' => trim($_POST['structured_data_json'] ?? ''),
                'google_analytics' => trim($_POST['google_analytics'] ?? '')
            ];
            
            // Validate JSON-LD if provided
            if (!empty($metaUpdates['structured_data_json'])) {
                $jsonData = json_decode($metaUpdates['structured_data_json'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    throw new Exception('Format JSON untuk Structured Data tidak valid!');
                }
            }
            
            // Use updateWebsiteSettings for bulk update
            if ($db->updateWebsiteSettings($metaUpdates)) {
                $message = 'Semua pengaturan SEO berhasil diupdate!';
                $messageType = 'success';
                
                // Log activity
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_SEO', 
                    'Updated comprehensive SEO settings (20 fields)', $adminData['type'] ?? 'master');
            } else {
                throw new Exception('Gagal mengupdate pengaturan SEO!');
            }
            
        } elseif ($action === 'update_promo') {
            // Promo and marketing links
            $promoUpdates = [
                'promo_link' => trim($_POST['promo_link'] ?? ''),
                'promo_description' => trim($_POST['promo_description'] ?? '')
            ];
            
            $success = true;
            foreach ($promoUpdates as $key => $value) {
                if (!$db->updateWebsiteSetting($key, $value)) {
                    $success = false;
                    break;
                }
            }
            
            if ($success) {
                $message = 'Promo settings berhasil diupdate!';
                $messageType = 'success';
                
                // Log activity
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_PROMO', 
                    'Updated promo settings', $adminData['type'] ?? 'master');
            } else {
                throw new Exception('Gagal mengupdate promo settings!');
            }
        }
        
    } catch (Exception $e) {
        $message = $e->getMessage();
        $messageType = 'error';
    }
}

// Get current settings
$settings = $db->getWebsiteSettings();

// Set page variables for template
$pageTitle = 'Pengaturan Website';
$pageDescription = 'Konfigurasi umum website dan SEO';

// Set flash messages
if ($messageType === 'success') {
    $_SESSION['success_message'] = $message;
} elseif ($messageType === 'error') {
    $_SESSION['error_message'] = $message;
}

// Include sidebar template
include 'admin-sidebar-template.php';
?>

<!-- Settings Content -->
<div class="row">
    <!-- Basic Settings -->
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-gear me-2"></i>
                    Pengaturan Dasar
                </h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update_basic">
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-image me-1"></i>
                            Logo Website
                        </label>
                        <input type="file" class="form-control" name="logo_file" accept=".jpg,.jpeg,.png,.svg,.webp">
                        <div class="form-text">Upload logo baru atau biarkan kosong untuk menggunakan logo saat ini</div>
                        
                        <?php if (!empty($settings['site_logo'])): ?>
                            <div class="mt-2">
                                <?php 
                                // Check logo file path
                                $logoPath = '../' . $settings['site_logo'];
                                $logoExists = file_exists($logoPath);
                                $logoUrl = '../' . $settings['site_logo'];
                                ?>
                                
                                <div class="current-logo-preview">
                                    <?php if ($logoExists): ?>
                                <img src="<?php echo htmlspecialchars($logoUrl); ?>?v=<?php echo pm_asset_version($settings['site_logo']); ?>" 
                                    alt="Current Logo" 
                                    class="img-thumbnail" 
                                    style="max-height: 100px; max-width: 200px;"
                                    loading="lazy" decoding="async"
                                    onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                                        <div class="text-success small">
                                            <i class="bi bi-check-circle me-1"></i>
                                            Logo saat ini: <?php echo htmlspecialchars(basename($settings['site_logo'])); ?>
                                        </div>
                                        <div class="text-danger small" style="display:none;">
                                            <i class="bi bi-x-circle me-1"></i>
                                            Logo gagal dimuat
                                        </div>
                                    <?php else: ?>
                                        <div class="text-warning small">
                                            <i class="bi bi-exclamation-triangle me-1"></i>
                                            Logo tidak ditemukan: <?php echo htmlspecialchars($settings['site_logo']); ?>
                                        </div>
                                        <div class="text-muted small">Path: <?php echo htmlspecialchars($logoPath); ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="mt-2">
                                <div class="text-muted small">
                                    <i class="bi bi-info-circle me-1"></i>
                                    Belum ada logo diupload
                                </div>
                            </div>
                        <?php endif; ?>
                        <input type="hidden" name="existing_logo" value="<?php echo htmlspecialchars($settings['site_logo'] ?? ''); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Nama Website *</label>
                        <input type="text" class="form-control" name="site_name" 
                               value="<?php echo htmlspecialchars($settings['site_name'] ?? ''); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Deskripsi Website</label>
                        <textarea class="form-control" name="site_description" rows="3"><?php echo htmlspecialchars($settings['site_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Welcome Text</label>
                        <textarea class="form-control" name="welcome_text" rows="3"><?php echo htmlspecialchars($settings['welcome_text'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-megaphone me-1"></i>
                            Marquee Text (Running Text)
                        </label>
                        <textarea class="form-control" name="marquee_text" rows="2" 
                                  placeholder="Contoh: DAFTAR SEKARANG | DOWNLOAD APLIKASI | TELEGRAM | WHATSAPP"><?php echo htmlspecialchars($settings['marquee_text'] ?? ''); ?></textarea>
                        <div class="form-text">Teks ini akan ditampilkan sebagai teks berjalan di bagian atas website</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-speedometer me-1"></i>
                            Kecepatan Marquee
                        </label>
                        <select class="form-select" name="marquee_speed">
                            <option value="slow" <?php echo ($settings['marquee_speed'] ?? 'slow') === 'slow' ? 'selected' : ''; ?>>Lambat (30s)</option>
                            <option value="normal" <?php echo ($settings['marquee_speed'] ?? 'slow') === 'normal' ? 'selected' : ''; ?>>Normal (20s)</option>
                            <option value="fast" <?php echo ($settings['marquee_speed'] ?? 'slow') === 'fast' ? 'selected' : ''; ?>>Cepat (10s)</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check-lg me-1"></i>
                        Update Basic Settings
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Social Media Settings -->
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-share me-2"></i>
                    Social Media Links
                </h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="update_social">
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-facebook text-primary me-1"></i>
                            Facebook
                        </label>
                        <input type="url" class="form-control" name="facebook_link" 
                               value="<?php echo htmlspecialchars($settings['facebook_link'] ?? ''); ?>" 
                               placeholder="https://facebook.com/yourpage">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-twitter text-info me-1"></i>
                            Twitter
                        </label>
                        <input type="url" class="form-control" name="twitter_link" 
                               value="<?php echo htmlspecialchars($settings['twitter_link'] ?? ''); ?>" 
                               placeholder="https://twitter.com/youraccount">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-instagram text-danger me-1"></i>
                            Instagram
                        </label>
                        <input type="url" class="form-control" name="instagram_link" 
                               value="<?php echo htmlspecialchars($settings['instagram_link'] ?? ''); ?>" 
                               placeholder="https://instagram.com/youraccount">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-youtube text-danger me-1"></i>
                            YouTube
                        </label>
                        <input type="url" class="form-control" name="youtube_link" 
                               value="<?php echo htmlspecialchars($settings['youtube_link'] ?? ''); ?>" 
                               placeholder="https://youtube.com/yourchannel">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-whatsapp text-success me-1"></i>
                            WhatsApp Number
                        </label>
                        <input type="text" class="form-control" name="whatsapp_number" 
                               value="<?php echo htmlspecialchars($settings['whatsapp_number'] ?? ''); ?>" 
                               placeholder="6281234567890">
                        <div class="form-text">Format: 62 + nomor tanpa 0 di depan</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-telegram text-primary me-1"></i>
                            Telegram Link
                        </label>
                        <input type="url" class="form-control" name="telegram_link" 
                               value="<?php echo htmlspecialchars($settings['telegram_link'] ?? ''); ?>" 
                               placeholder="https://t.me/yourgroup">
                        <div class="form-text">Link ke channel atau grup Telegram</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-person-plus text-info me-1"></i>
                            Link Daftar Member
                        </label>
                        <input type="url" class="form-control" name="register_link" 
                               value="<?php echo htmlspecialchars($settings['register_member_link'] ?? ''); ?>" 
                               placeholder="https://daftar.example.com">
                        <div class="form-text">Link ke halaman pendaftaran member</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-box-arrow-in-right text-success me-1"></i>
                            Link Login Member
                        </label>
                        <input type="url" class="form-control" name="login_link" 
                               value="<?php echo htmlspecialchars($settings['login_link'] ?? ''); ?>" 
                               placeholder="https://login.example.com">
                        <div class="form-text">Link ke halaman login member</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-phone text-dark me-1"></i>
                            Link Download Aplikasi
                        </label>
                        <input type="url" class="form-control" name="download_app_link" 
                               value="<?php echo htmlspecialchars($settings['download_app_link'] ?? ''); ?>" 
                               placeholder="https://download.example.com">
                        <div class="form-text">Link untuk download aplikasi mobile</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-chat-dots text-warning me-1"></i>
                            Link LiveChat
                        </label>
                        <input type="url" class="form-control" name="livechat_link" 
                               value="<?php echo htmlspecialchars($settings['livechat_link'] ?? ''); ?>" 
                               placeholder="https://livechat.example.com">
                        <div class="form-text">Link ke sistem live chat customer service</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-star-fill text-warning me-1"></i>
                            Slot Gacor Link
                        </label>
                        <input type="url" class="form-control" name="slot_gacor_link" 
                               value="<?php echo htmlspecialchars($settings['slot_gacor_link'] ?? ''); ?>" 
                               placeholder="https://slotgacor.example.com">
                        <div class="form-text">Link untuk promosi slot gacor</div>
                    </div>
                    
                    <button type="submit" class="btn btn-success">
                        <i class="bi bi-check-lg me-1"></i>
                        Update Social Links
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Footer Settings Row -->
<div class="row">
    <!-- Footer Information -->
    <div class="col-lg-12 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-layout-text-window-reverse me-2"></i>
                    Footer Information
                </h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="update_footer">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-building me-1"></i>
                                Nama Perusahaan
                            </label>
                            <input type="text" class="form-control" name="footer_company_name" 
                                   value="<?php echo htmlspecialchars($settings['footer_company_name'] ?? ''); ?>" 
                                   placeholder="Inatogel">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-envelope me-1"></i>
                                Email Kontak
                            </label>
                            <input type="email" class="form-control" name="contact_email" 
                                   value="<?php echo htmlspecialchars($settings['contact_email'] ?? ''); ?>" 
                                   placeholder="support@inatogel.com">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-card-text me-1"></i>
                            Deskripsi Footer
                        </label>
                        <textarea class="form-control" name="footer_description" rows="3" 
                                  placeholder="Situs Togel Live Draw Terpercaya dengan prediksi angka jitu..."><?php echo htmlspecialchars($settings['footer_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-geo-alt me-1"></i>
                                Alamat
                            </label>
                            <textarea class="form-control" name="footer_address" rows="2" 
                                      placeholder="Jakarta, Indonesia"><?php echo htmlspecialchars($settings['footer_address'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-telephone me-1"></i>
                                Telepon / Customer Service
                            </label>
                            <input type="text" class="form-control" name="footer_phone" 
                                   value="<?php echo htmlspecialchars($settings['footer_phone'] ?? ''); ?>" 
                                   placeholder="Customer Service 24/7">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-whatsapp text-success me-1"></i>
                                WhatsApp Display
                            </label>
                            <input type="text" class="form-control" name="whatsapp_display" 
                                   value="<?php echo htmlspecialchars($settings['whatsapp_display'] ?? ''); ?>" 
                                   placeholder="+62 813-8911-4046">
                            <div class="form-text">Format tampilan nomor WA di footer</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-clock me-1"></i>
                                Jam Operasional
                            </label>
                            <input type="text" class="form-control" name="footer_business_hours" 
                                   value="<?php echo htmlspecialchars($settings['footer_business_hours'] ?? ''); ?>" 
                                   placeholder="Online 24/7">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-c-circle me-1"></i>
                            Copyright Text
                        </label>
                        <textarea class="form-control" name="footer_copyright_text" rows="2" 
                                  placeholder="All rights reserved. | Situs Togel Terpercaya Indonesia"><?php echo htmlspecialchars($settings['footer_copyright_text'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="bi bi-exclamation-triangle me-1"></i>
                            Disclaimer
                        </label>
                        <textarea class="form-control" name="footer_disclaimer" rows="3" 
                                  placeholder="Disclaimer: Kami tidak bertanggung jawab atas kerugian..."><?php echo htmlspecialchars($settings['footer_disclaimer'] ?? ''); ?></textarea>
                    </div>
                    
                    <button type="submit" class="btn btn-info">
                        <i class="bi bi-check-lg me-1"></i>
                        Update Footer Information
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- SEO Settings -->
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-search me-2"></i>
                    SEO & Analytics
                </h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="update_meta">
                    
                    <!-- Basic SEO Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <h6 class="text-primary border-bottom pb-2 mb-3">
                                <i class="bi bi-tag me-1"></i>Basic SEO Settings
                            </h6>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Site Title Template</label>
                            <input type="text" class="form-control" name="site_title_template" 
                                   placeholder="%s - Nama Situs" 
                                   value="<?php echo htmlspecialchars($settings['site_title_template'] ?? ''); ?>">
                            <div class="form-text">%s akan diganti dengan judul halaman</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Home Page Title</label>
                            <input type="text" class="form-control" name="home_title" 
                                   placeholder="Prediksi Togel Terpercaya" 
                                   value="<?php echo htmlspecialchars($settings['home_title'] ?? ''); ?>">
                            <div class="form-text">Judul khusus untuk halaman home</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Meta Keywords</label>
                            <textarea class="form-control" name="meta_keywords" rows="3" 
                                      placeholder="togel, prediksi, hongkong, singapore"><?php echo htmlspecialchars($settings['meta_keywords'] ?? ''); ?></textarea>
                            <div class="form-text">Pisahkan dengan koma</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Meta Description</label>
                            <textarea class="form-control" name="meta_description" rows="3" 
                                      placeholder="Website prediksi togel terpercaya"><?php echo htmlspecialchars($settings['meta_description'] ?? ''); ?></textarea>
                            <div class="form-text">Max 160 karakter</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Meta Author</label>
                            <input type="text" class="form-control" name="meta_author" 
                                   placeholder="Tim Prediksi" 
                                   value="<?php echo htmlspecialchars($settings['meta_author'] ?? ''); ?>">
                            <div class="form-text">Nama penulis atau organisasi</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Meta Robots</label>
                            <select class="form-control" name="meta_robots">
                                <option value="index, follow" <?php echo ($settings['meta_robots'] ?? '') === 'index, follow' ? 'selected' : ''; ?>>Index, Follow</option>
                                <option value="noindex, nofollow" <?php echo ($settings['meta_robots'] ?? '') === 'noindex, nofollow' ? 'selected' : ''; ?>>No Index, No Follow</option>
                                <option value="index, nofollow" <?php echo ($settings['meta_robots'] ?? '') === 'index, nofollow' ? 'selected' : ''; ?>>Index, No Follow</option>
                                <option value="noindex, follow" <?php echo ($settings['meta_robots'] ?? '') === 'noindex, follow' ? 'selected' : ''; ?>>No Index, Follow</option>
                            </select>
                            <div class="form-text">Instruksi untuk search engine robots</div>
                        </div>
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Canonical URL</label>
                            <input type="url" class="form-control" name="canonical_url" 
                                   placeholder="https://domain.com/halaman-utama" 
                                   value="<?php echo htmlspecialchars($settings['canonical_url'] ?? ''); ?>">
                            <div class="form-text">URL canonical untuk menghindari duplicate content</div>
                        </div>
                    </div>

                    <!-- Open Graph Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <h6 class="text-success border-bottom pb-2 mb-3">
                                <i class="bi bi-share me-1"></i>Open Graph (Facebook/Social Media)
                            </h6>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">OG Title</label>
                            <input type="text" class="form-control" name="og_title" 
                                   placeholder="Prediksi Togel Akurat" 
                                   value="<?php echo htmlspecialchars($settings['og_title'] ?? ''); ?>">
                            <div class="form-text">Judul saat dibagikan di media sosial</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">OG Type</label>
                            <select class="form-control" name="og_type">
                                <option value="website" <?php echo ($settings['og_type'] ?? '') === 'website' ? 'selected' : ''; ?>>Website</option>
                                <option value="article" <?php echo ($settings['og_type'] ?? '') === 'article' ? 'selected' : ''; ?>>Article</option>
                                <option value="blog" <?php echo ($settings['og_type'] ?? '') === 'blog' ? 'selected' : ''; ?>>Blog</option>
                            </select>
                            <div class="form-text">Tipe konten untuk Open Graph</div>
                        </div>
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label">OG Description</label>
                            <textarea class="form-control" name="og_description" rows="3" 
                                      placeholder="Deskripsi menarik untuk media sosial"><?php echo htmlspecialchars($settings['og_description'] ?? ''); ?></textarea>
                            <div class="form-text">Deskripsi saat dibagikan (berbeda dari meta description)</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">OG Image URL</label>
                            <input type="url" class="form-control" name="og_image" 
                                   placeholder="https://domain.com/assets/og-image.jpg" 
                                   value="<?php echo htmlspecialchars($settings['og_image'] ?? ''); ?>">
                            <div class="form-text">Gambar untuk preview media sosial (min 1200x630px)</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">OG URL</label>
                            <input type="url" class="form-control" name="og_url" 
                                   placeholder="https://domain.com" 
                                   value="<?php echo htmlspecialchars($settings['og_url'] ?? ''); ?>">
                            <div class="form-text">URL utama website untuk Open Graph</div>
                        </div>
                    </div>

                    <!-- Twitter Cards Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <h6 class="text-info border-bottom pb-2 mb-3">
                                <i class="bi bi-twitter me-1"></i>Twitter Cards
                            </h6>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Twitter Card Type</label>
                            <select class="form-control" name="twitter_card">
                                <option value="summary" <?php echo ($settings['twitter_card'] ?? '') === 'summary' ? 'selected' : ''; ?>>Summary</option>
                                <option value="summary_large_image" <?php echo ($settings['twitter_card'] ?? '') === 'summary_large_image' ? 'selected' : ''; ?>>Summary Large Image</option>
                            </select>
                            <div class="form-text">Tipe Twitter Card untuk preview</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Twitter Title</label>
                            <input type="text" class="form-control" name="twitter_title" 
                                   placeholder="Prediksi Togel | Twitter" 
                                   value="<?php echo htmlspecialchars($settings['twitter_title'] ?? ''); ?>">
                            <div class="form-text">Judul khusus untuk Twitter</div>
                        </div>
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Twitter Description</label>
                            <textarea class="form-control" name="twitter_description" rows="2" 
                                      placeholder="Deskripsi singkat untuk Twitter"><?php echo htmlspecialchars($settings['twitter_description'] ?? ''); ?></textarea>
                            <div class="form-text">Deskripsi untuk Twitter Card</div>
                        </div>
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Twitter Image URL</label>
                            <input type="url" class="form-control" name="twitter_image" 
                                   placeholder="https://domain.com/assets/twitter-image.jpg" 
                                   value="<?php echo htmlspecialchars($settings['twitter_image'] ?? ''); ?>">
                            <div class="form-text">Gambar untuk Twitter Card (min 800x418px)</div>
                        </div>
                    </div>

                    <!-- Technical SEO Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <h6 class="text-warning border-bottom pb-2 mb-3">
                                <i class="bi bi-gear me-1"></i>Technical SEO
                            </h6>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Favicon Path</label>
                            <input type="text" class="form-control" name="favicon_path" 
                                   placeholder="/assets/favicon.ico" 
                                   value="<?php echo htmlspecialchars($settings['favicon_path'] ?? ''); ?>">
                            <div class="form-text">Path ke file favicon</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Theme Color</label>
                            <input type="color" class="form-control form-control-color" name="theme_color" 
                                   value="<?php echo htmlspecialchars($settings['theme_color'] ?? '#007bff'); ?>">
                            <div class="form-text">Warna tema untuk mobile browser</div>
                        </div>
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Structured Data JSON-LD</label>
                            <textarea class="form-control" name="structured_data_json" rows="6" 
                                      placeholder='{"@context": "https://schema.org", "@type": "Organization", "name": "Nama Situs"}'><?php echo htmlspecialchars($settings['structured_data_json'] ?? ''); ?></textarea>
                            <div class="form-text">JSON-LD structured data untuk rich snippets (format JSON valid)</div>
                        </div>
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Google Analytics Code</label>
                            <textarea class="form-control" name="google_analytics" rows="4" 
                                      placeholder="<!-- Google tag (gtag.js) -->"><?php echo htmlspecialchars($settings['google_analytics'] ?? ''); ?></textarea>
                            <div class="form-text">Paste complete Google Analytics tracking code</div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-success btn-lg">
                        <i class="bi bi-check-lg me-1"></i>
                        Update All SEO Settings
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Promo Settings -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-gift me-2"></i>
                    Promo & Marketing Links
                </h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="update_promo">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-link-45deg me-1"></i>
                                Promo Link
                            </label>
                            <input type="url" class="form-control" name="promo_link" 
                                   value="<?php echo htmlspecialchars($settings['promo_link'] ?? ''); ?>" 
                                   placeholder="https://promo.example.com">
                            <div class="form-text">Link yang akan dibuka ketika user klik menu promosi</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-chat-text me-1"></i>
                                Promo Description
                            </label>
                            <input type="text" class="form-control" name="promo_description" 
                                   value="<?php echo htmlspecialchars($settings['promo_description'] ?? ''); ?>" 
                                   placeholder="Deskripsi singkat promosi">
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-warning">
                        <i class="bi bi-check-lg me-1"></i>
                        Update Promo Settings
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Current Settings Overview -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-info-circle me-2"></i>
                    Current Settings Overview
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <h6 class="text-muted">Website Info</h6>
                        <p><strong>Name:</strong> <?php echo htmlspecialchars($settings['site_name'] ?? 'Not set'); ?></p>
                        <p><strong>Description:</strong> <?php echo htmlspecialchars(substr($settings['site_description'] ?? 'Not set', 0, 50)) . (strlen($settings['site_description'] ?? '') > 50 ? '...' : ''); ?></p>
                    </div>
                    
                    <div class="col-md-3">
                        <h6 class="text-muted">Social Media</h6>
                        <p>
                            <?php if (!empty($settings['facebook_link'])): ?>
                                <i class="bi bi-facebook text-primary me-1"></i>
                            <?php endif; ?>
                            <?php if (!empty($settings['twitter_link'])): ?>
                                <i class="bi bi-twitter text-info me-1"></i>
                            <?php endif; ?>
                            <?php if (!empty($settings['instagram_link'])): ?>
                                <i class="bi bi-instagram text-danger me-1"></i>
                            <?php endif; ?>
                            <?php if (!empty($settings['youtube_link'])): ?>
                                <i class="bi bi-youtube text-danger me-1"></i>
                            <?php endif; ?>
                            <?php if (!empty($settings['whatsapp_link'])): ?>
                                <i class="bi bi-whatsapp text-success me-1"></i>
                            <?php endif; ?>
                            <?php if (!empty($settings['slot_gacor_link'])): ?>
                                <i class="bi bi-star-fill text-warning me-1"></i>
                            <?php endif; ?>
                            <?php if (empty($settings['facebook_link']) && empty($settings['twitter_link']) && empty($settings['instagram_link']) && empty($settings['youtube_link']) && empty($settings['whatsapp_link']) && empty($settings['slot_gacor_link'])): ?>
                                <span class="text-muted">No social links configured</span>
                            <?php endif; ?>
                        </p>
                        <p>
                            <span class="badge bg-<?php echo !empty($settings['slot_gacor_link']) ? 'success' : 'secondary'; ?>">
                                Slot Gacor: <?php echo !empty($settings['slot_gacor_link']) ? 'Set' : 'Not set'; ?>
                            </span>
                        </p>
                    </div>
                    
                    <div class="col-md-3">
                        <h6 class="text-muted">Promo Status</h6>
                        <p>
                            <span class="badge bg-<?php echo !empty($settings['promo_link']) ? 'success' : 'warning'; ?>">
                                Promo Link: <?php echo !empty($settings['promo_link']) ? 'Set' : 'Not set'; ?>
                            </span>
                        </p>
                        <?php if (!empty($settings['promo_description'])): ?>
                        <p><small class="text-muted"><?php echo htmlspecialchars(substr($settings['promo_description'], 0, 30)) . (strlen($settings['promo_description']) > 30 ? '...' : ''); ?></small></p>
                        <?php endif; ?>
                    </div>
                    
                    <div class="col-md-3">
                        <h6 class="text-muted">SEO Status</h6>
                        <p>
                            <span class="badge bg-<?php echo !empty($settings['meta_keywords']) ? 'success' : 'warning'; ?>">
                                Keywords: <?php echo !empty($settings['meta_keywords']) ? 'Set' : 'Not set'; ?>
                            </span>
                        </p>
                        <p>
                            <span class="badge bg-<?php echo !empty($settings['google_analytics']) ? 'success' : 'warning'; ?>">
                                Analytics: <?php echo !empty($settings['google_analytics']) ? 'Configured' : 'Not configured'; ?>
                            </span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Additional JavaScript for settings
$additionalJS = '
<script>
// Character counter for meta description
document.addEventListener("DOMContentLoaded", function() {
    const metaDesc = document.querySelector("textarea[name=meta_description]");
    if (metaDesc) {
        const counter = document.createElement("small");
        counter.className = "text-muted";
        metaDesc.parentNode.appendChild(counter);
        
        function updateCounter() {
            const length = metaDesc.value.length;
            counter.textContent = `${length}/160 characters`;
            counter.className = length > 160 ? "text-danger" : "text-muted";
        }
        
        metaDesc.addEventListener("input", updateCounter);
        updateCounter();
    }
    
    // URL validation feedback
    const urlInputs = document.querySelectorAll("input[type=url]");
    urlInputs.forEach(input => {
        input.addEventListener("blur", function() {
            if (this.value && !this.checkValidity()) {
                this.classList.add("is-invalid");
            } else {
                this.classList.remove("is-invalid");
            }
        });
    });
});
</script>';

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