<?php
    session_start();
require_once '../config/database.php';
    
    // Check if admin is logged in
    if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
        exit;
    }
    
$pdo = getDBConnection();
$success_message = '';
$error_message = '';

// Fetch quotes settings
$quotes_enabled = 'on';
$quotes_rotation_interval = '30';
$quotes_show_author = 'on';

$stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
$stmt->execute(['quotes_enabled']);
$quotes_enabled = $stmt->fetchColumn() ?: 'on';

$stmt->execute(['quotes_rotation_interval']);
$quotes_rotation_interval = $stmt->fetchColumn() ?: '30';

$stmt->execute(['quotes_show_author']);
$quotes_show_author = $stmt->fetchColumn() ?: 'on';

// Fetch existing quotes
$quotes = [];
try {
    $stmt = $pdo->query("SELECT * FROM quotes ORDER BY display_order, created_at");
    $quotes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Quotes table might not exist yet
    $quotes = [];
}

// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_settings'])) {
    try {
        // Debug: Log what's being submitted
        error_log("Settings form submitted. POST data: " . print_r($_POST, true));

        
        // Update help mobile number
        $help_mobile = $_POST['help_mobile_number'];
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute(['help_mobile_number', $help_mobile, $help_mobile]);
        
        // Update WhatsApp message template
        $whatsapp_message = $_POST['help_whatsapp_message'];
        $stmt->execute(['help_whatsapp_message', $whatsapp_message, $whatsapp_message]);
        
        // Update support hours
        $support_hours = $_POST['support_hours'];
        $stmt->execute(['support_hours', $support_hours, $support_hours]);
        
        // Update support email
        $support_email = $_POST['support_email'];
        $stmt->execute(['support_email', $support_email, $support_email]);
        
        // Update language support
        $language_support = $_POST['language_support'];
        $stmt->execute(['language_support', $language_support, $language_support]);
        
        // Update slot duration
        if (isset($_POST['slot_duration'])) {
            $slot_duration_value = (int)$_POST['slot_duration'];
            $stmt->execute(['slot_duration', $slot_duration_value, $slot_duration_value]);
        }
        
        // Update slots per hour
        if (isset($_POST['slots_per_hour'])) {
            $stmt->execute(['slots_per_hour', $_POST['slots_per_hour'], $_POST['slots_per_hour']]);
        }
        
        // Update start time
        if (isset($_POST['start_time'])) {
            $stmt->execute(['start_time', $_POST['start_time'], $_POST['start_time']]);
        }
        
        // Update end time
        if (isset($_POST['end_time'])) {
            $stmt->execute(['end_time', $_POST['end_time'], $_POST['end_time']]);
        }
        
        // Update lunch start time
        if (isset($_POST['lunch_start'])) {
            $stmt->execute(['lunch_start', $_POST['lunch_start'], $_POST['lunch_start']]);
        }
        
        // Update lunch end time
        if (isset($_POST['lunch_end'])) {
            $stmt->execute(['lunch_end', $_POST['lunch_end'], $_POST['lunch_end']]);
        }
        
        // Update pricing settings
        if (isset($_POST['tuesday_price'])) {
            $stmt->execute(['tuesday_price', $_POST['tuesday_price'], $_POST['tuesday_price']]);
        }
        
        if (isset($_POST['saturday_price'])) {
            $stmt->execute(['saturday_price', $_POST['saturday_price'], $_POST['saturday_price']]);
        }
        
        if (isset($_POST['sunday_price'])) {
            $stmt->execute(['sunday_price', $_POST['sunday_price'], $_POST['sunday_price']]);
        }
        
        if (isset($_POST['other_days_price'])) {
            $stmt->execute(['other_days_price', $_POST['other_days_price'], $_POST['other_days_price']]);
        }
        
        // Update system settings
        if (isset($_POST['system_enabled'])) {
            $stmt->execute(['system_enabled', $_POST['system_enabled'], $_POST['system_enabled']]);
        }
        
        if (isset($_POST['maintenance_mode'])) {
            $stmt->execute(['maintenance_mode', $_POST['maintenance_mode'], $_POST['maintenance_mode']]);
        }
        
        if (isset($_POST['maintenance_message'])) {
            $stmt->execute(['maintenance_message', $_POST['maintenance_message'], $_POST['maintenance_message']]);
        }
        
        // Update app settings
        if (isset($_POST['app_version'])) {
            $stmt->execute(['app_version', $_POST['app_version'], $_POST['app_version']]);
        }
        
        if (isset($_POST['force_update'])) {
            $stmt->execute(['force_update', $_POST['force_update'], $_POST['force_update']]);
        }
        
        if (isset($_POST['update_message'])) {
            $stmt->execute(['update_message', $_POST['update_message'], $_POST['update_message']]);
        }
        
        // Update days booking settings
        $days_settings = [
            'monday_booking', 'tuesday_booking', 'wednesday_booking', 
            'thursday_booking', 'friday_booking', 'saturday_booking', 'sunday_booking'
        ];
        
        foreach ($days_settings as $day) {
            if (isset($_POST[$day])) {
                $stmt->execute([$day, $_POST[$day], $_POST[$day]]);
            }
        }
        
        // Update consultation type settings
        $consultation_types = [
            'audio_call_enabled', 'video_call_enabled', 'office_meeting_enabled'
        ];
        
        foreach ($consultation_types as $type) {
            if (isset($_POST[$type])) {
                $stmt->execute([$type, $_POST[$type], $_POST[$type]]);
            }
        }
        
        // Update advance booking days
        if (isset($_POST['advance_booking_days'])) {
            $stmt->execute(['advance_booking_days', $_POST['advance_booking_days'], $_POST['advance_booking_days']]);
        }
        
        // Update general booking settings
        if (isset($_POST['general_booking_enabled'])) {
            $stmt->execute(['general_booking_enabled', $_POST['general_booking_enabled'], $_POST['general_booking_enabled']]);
        }
        
        if (isset($_POST['general_booking_message'])) {
            $stmt->execute(['general_booking_message', $_POST['general_booking_message'], $_POST['general_booking_message']]);
        }
        
        // Handle quotes management
        if (isset($_POST['quotes_enabled'])) {
            $stmt->execute(['quotes_enabled', $_POST['quotes_enabled'], $_POST['quotes_enabled']]);
        }
        
        if (isset($_POST['quotes_rotation_interval'])) {
            $stmt->execute(['quotes_rotation_interval', $_POST['quotes_rotation_interval'], $_POST['quotes_rotation_interval']]);
        }
        
        if (isset($_POST['quotes_show_author'])) {
            $stmt->execute(['quotes_show_author', $_POST['quotes_show_author'], $_POST['quotes_show_author']]);
        }
        
        $success_message = "Settings updated successfully!";
        
    } catch (Exception $e) {
        $error_message = "Error updating settings: " . $e->getMessage();
    }
}

// Handle quotes CRUD operations
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quote_action'])) {
    try {
        switch ($_POST['quote_action']) {
            case 'add':
                $quote_text = trim($_POST['quote_text']);
                $author = trim($_POST['quote_author']);
                $category = trim($_POST['quote_category']);
                $display_order = (int)$_POST['quote_display_order'];
                
                if (empty($quote_text)) {
                    throw new Exception('Quote text is required');
                }
                
                $stmt = $pdo->prepare("INSERT INTO quotes (quote_text, author, category, display_order) VALUES (?, ?, ?, ?)");
                $stmt->execute([$quote_text, $author, $category, $display_order]);
                $success_message = "Quote added successfully!";
                break;
                
            case 'update':
                $quote_id = (int)$_POST['quote_id'];
                $quote_text = trim($_POST['quote_text']);
                $author = trim($_POST['quote_author']);
                $category = trim($_POST['quote_category']);
                $display_order = (int)$_POST['quote_display_order'];
                $is_active = isset($_POST['quote_is_active']) ? 1 : 0;
                
                if (empty($quote_text)) {
                    throw new Exception('Quote text is required');
                }
                
                $stmt = $pdo->prepare("UPDATE quotes SET quote_text = ?, author = ?, category = ?, display_order = ?, is_active = ? WHERE id = ?");
                $stmt->execute([$quote_text, $author, $category, $display_order, $is_active, $quote_id]);
                $success_message = "Quote updated successfully!";
                break;
                
            case 'delete':
                $quote_id = (int)$_POST['quote_id'];
                $stmt = $pdo->prepare("DELETE FROM quotes WHERE id = ?");
                $stmt->execute([$quote_id]);
                $success_message = "Quote deleted successfully!";
                break;
        }
    } catch (Exception $e) {
        $error_message = "Error managing quotes: " . $e->getMessage();
    }
}

// Handle specific date blocking (only when explicitly requested, not from main form)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['block_date']) && !isset($_POST['update_settings'])) {
    try {
        $block_date = trim($_POST['block_date']);
        $block_reason = trim($_POST['block_reason'] ?? 'Admin blocked');
        
        // Validate date
        if (empty($block_date)) {
            throw new Exception('Date is required for blocking');
        }
        
        // Validate date format
        $date_obj = DateTime::createFromFormat('Y-m-d', $block_date);
        if (!$date_obj || $date_obj->format('Y-m-d') !== $block_date) {
            throw new Exception('Invalid date format. Please use YYYY-MM-DD format');
        }
        
        // Check if date is in the past
        $today = new DateTime();
        $today->setTime(0, 0, 0);
        if ($date_obj < $today) {
            throw new Exception('Cannot block past dates. Please select a future date.');
        }
        
        // Check if date already exists
        $stmt = $pdo->prepare("SELECT id FROM blocked_dates WHERE block_date = ?");
        $stmt->execute([$block_date]);
        
        if ($stmt->fetch()) {
            $error_message = "Date $block_date is already blocked!";
        } else {
            // Insert new blocked date
            $stmt = $pdo->prepare("INSERT INTO blocked_dates (block_date, reason, created_by) VALUES (?, ?, ?)");
            $stmt->execute([$block_date, $block_reason, $_SESSION['admin_username'] ?? 'admin']);
            $success_message = "Date $block_date blocked successfully!";
        }
    } catch (Exception $e) {
        $error_message = "Error blocking date: " . $e->getMessage();
    }
}

// Handle unblock date
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['unblock_date'])) {
    try {
        $date_id = $_POST['date_id'];
        
        $stmt = $pdo->prepare("DELETE FROM blocked_dates WHERE id = ?");
        $stmt->execute([$date_id]);
        $success_message = "Date unblocked successfully!";
    } catch (Exception $e) {
        $error_message = "Error unblocking date: " . $e->getMessage();
    }
}

// Get current settings
$settings = [];
$stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('help_mobile_number', 'help_whatsapp_message', 'support_hours', 'support_email', 'language_support', 'slot_duration', 'slots_per_hour', 'start_time', 'end_time', 'lunch_start', 'lunch_end', 'tuesday_price', 'saturday_price', 'sunday_price', 'other_days_price', 'system_enabled', 'maintenance_mode', 'maintenance_message', 'app_version', 'force_update', 'update_message', 'monday_booking', 'tuesday_booking', 'wednesday_booking', 'thursday_booking', 'friday_booking', 'saturday_booking', 'sunday_booking', 'advance_booking_days', 'general_booking_enabled', 'general_booking_message', 'audio_call_enabled', 'video_call_enabled', 'office_meeting_enabled')");
while ($row = $stmt->fetch()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Get blocked dates
$blocked_dates = [];
try {
    $stmt = $pdo->query("SELECT * FROM blocked_dates ORDER BY block_date DESC");
    $blocked_dates = $stmt->fetchAll();
} catch (Exception $e) {
    // Table might not exist yet
}

// Set default values if settings don't exist
$help_mobile = $settings['help_mobile_number'] ?? '+91 77373 57224';
$whatsapp_message = $settings['help_whatsapp_message'] ?? 'Hi, I need help with the Astro Admin Panel. Can you please assist me?';
$support_hours = $settings['support_hours'] ?? '24/7 Available';
$support_email = $settings['support_email'] ?? 'support@astro.com';
$language_support = $settings['language_support'] ?? 'English, Hindi';
$slot_duration = (int)($settings['slot_duration'] ?? 60);
$slots_per_hour = (int)($settings['slots_per_hour'] ?? 1);
$start_time = $settings['start_time'] ?? '09:00';
$end_time = $settings['end_time'] ?? '18:00';
$lunch_start = $settings['lunch_start'] ?? '13:00';
$lunch_end = $settings['lunch_end'] ?? '14:00';
$tuesday_price = (int)($settings['tuesday_price'] ?? 300);
$saturday_price = (int)($settings['saturday_price'] ?? 300);
$sunday_price = (int)($settings['sunday_price'] ?? 300);
$other_days_price = (int)($settings['other_days_price'] ?? 500);
$system_enabled = $settings['system_enabled'] ?? '1';
$maintenance_mode = $settings['maintenance_mode'] ?? '0';
$maintenance_message = $settings['maintenance_message'] ?? 'The app is currently under maintenance. Please try again later.';
$app_version = $settings['app_version'] ?? '1.0.0';
$force_update = $settings['force_update'] ?? '0';
$update_message = $settings['update_message'] ?? 'A new version of the app is available. Please update to continue using all features.';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Settings - Astro Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            color: white;
            min-height: 100vh;
        }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        }
        .sidebar .nav-link {
            color: #fff;
            padding: 12px 20px;
            margin: 5px 0;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 193, 7, 0.2);
            color: #ffc107;
        }
        .main-content {
            background: #f8f9fa;
            color: #333;
        }
        .settings-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            transition: all 0.3s;
        }
        .form-control:focus, .form-select:focus {
            border-color: #ffc107;
            box-shadow: 0 0 0 0.2rem rgba(255, 193, 7, 0.25);
        }
        .btn-save {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border: none;
            border-radius: 25px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s;
        }
        .btn-save:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.3);
        }
        .setting-item {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid #ffc107;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar p-3">
                    <div class="text-center mb-4">
                        <h4 class="text-warning">
                            <i class="fas fa-star"></i> ASTRO ADMIN
                        </h4>
                    </div>
                    
                    <nav class="nav flex-column">
                        <a class="nav-link" href="index.php">
                            <i class="fas fa-tachometer-alt me-2"></i> Dashboard
                        </a>
                        <a class="nav-link" href="users.php">
                            <i class="fas fa-users me-2"></i> Users
                        </a>
                        <a class="nav-link" href="appointments.php">
                            <i class="fas fa-calendar-check me-2"></i> Appointments
                        </a>
                        <a class="nav-link" href="tatkal_management_panel.php">
                            <i class="fas fa-bolt me-2"></i> Tatkal Management
                        </a>
                        <a class="nav-link" href="notifications.php">
                            <i class="fas fa-bell me-2"></i> Push Notifications
                        </a>
                        <a class="nav-link active" href="settings.php">
                            <i class="fas fa-cog me-2"></i> Settings
                        </a>
                        <a class="nav-link" href="logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> Logout
                        </a>
                        <hr class="text-light">
                        <a class="nav-link text-warning" href="#" onclick="openHelp()">
                            <i class="fab fa-whatsapp me-2"></i> Help & Support
                        </a>
                        <a class="nav-link text-info" href="HELP_GUIDE.md" target="_blank">
                            <i class="fas fa-book me-2"></i> Help Guide
                        </a>
                        <a class="nav-link text-success" href="help_utility.php">
                            <i class="fas fa-tools me-2"></i> Admin Tools
                        </a>
                        <a class="nav-link" href="quotes.php">
                            <i class="fas fa-quote-left me-2"></i> Quotes Management
                        </a>
                        <a class="nav-link text-warning" href="../optimize_database.php" target="_blank">
                            <i class="fas fa-rocket me-2"></i> Speed Up Database
                        </a>
                    </nav>
                </div>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 main-content">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-cog me-2"></i>System Settings</h2>
                        <a href="appointments.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-2"></i>Back to Appointments
                        </a>
                    </div>
                    

                    
                    <?php if ($success_message) { ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    
                    <?php if ($error_message) { ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="settings-card">
                                <div class="card-body">
                                    <h5 class="card-title mb-4">
                                        <i class="fas fa-headset me-2 text-warning"></i>Help & Support Settings
                                    </h5>
                                    
                                    <form method="POST" action="" id="mainSettingsForm">
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-mobile-alt me-2"></i>Help Mobile Number
                                            </label>
                                            <input type="text" name="help_mobile_number" class="form-control" 
                                                   value="<?php echo htmlspecialchars($help_mobile); ?>" 
                                                   placeholder="Enter help mobile number" required>
                                            <small class="text-muted">This number will be used for WhatsApp support across the system</small>
                                        </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fab fa-whatsapp me-2"></i>WhatsApp Message Template
                                            </label>
                                            <textarea name="help_whatsapp_message" class="form-control" rows="3" 
                                                      placeholder="Enter default WhatsApp message"><?php echo htmlspecialchars($whatsapp_message); ?></textarea>
                                            <small class="text-muted">Default message when users click WhatsApp support</small>
                                        </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-clock me-2"></i>Support Hours
                                            </label>
                                            <input type="text" name="support_hours" class="form-control" 
                                                   value="<?php echo htmlspecialchars($support_hours); ?>" 
                                                   placeholder="e.g., 24/7 Available, 9 AM - 6 PM">
                                            <small class="text-muted">Display support availability to users</small>
                        </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-envelope me-2"></i>Support Email
                                </label>
                                            <input type="email" name="support_email" class="form-control" 
                                                   value="<?php echo htmlspecialchars($support_email); ?>" 
                                                   placeholder="Enter support email address">
                                            <small class="text-muted">Email address for support inquiries</small>
                            </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-language me-2"></i>Language Support
                                            </label>
                                            <input type="text" name="language_support" class="form-control" 
                                                   value="<?php echo htmlspecialchars($language_support); ?>" 
                                                   placeholder="e.g., English, Hindi">
                                            <small class="text-muted">Languages supported by your support team</small>
                        </div>
                        
                                        <hr class="my-4">
                                        
                            <h5 class="mb-3">
                                            <i class="fas fa-calendar-alt me-2 text-primary"></i>Days Booking Settings
                            </h5>
                                        
                            <div class="row">
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Monday
                                                    </label>
                                                    <select name="monday_booking" class="form-select">
                                                        <option value="on" <?php echo ($settings['monday_booking'] ?? 'off') === 'on' ? 'selected' : ''; ?>>Booking ON</option>
                                                        <option value="off" <?php echo ($settings['monday_booking'] ?? 'off') === 'off' ? 'selected' : ''; ?>>Booking OFF</option>
                                                    </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Tuesday
                                                    </label>
                                                    <select name="tuesday_booking" class="form-select">
                                                        <option value="on" <?php echo ($settings['tuesday_booking'] ?? 'on') === 'on' ? 'selected' : ''; ?>>Booking ON</option>
                                                        <option value="off" <?php echo ($settings['tuesday_booking'] ?? 'on') === 'off' ? 'selected' : ''; ?>>Booking OFF</option>
                                                    </select>
                                    </div>
                                </div>
                            </div>
                                        
                            <div class="row">
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Wednesday
                                                    </label>
                                                    <select name="wednesday_booking" class="form-select">
                                                        <option value="on" <?php echo ($settings['wednesday_booking'] ?? 'off') === 'on' ? 'selected' : ''; ?>>Booking ON</option>
                                                        <option value="off" <?php echo ($settings['wednesday_booking'] ?? 'off') === 'off' ? 'selected' : ''; ?>>Booking OFF</option>
                                                    </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Thursday
                                                    </label>
                                                    <select name="thursday_booking" class="form-select">
                                                        <option value="on" <?php echo ($settings['thursday_booking'] ?? 'off') === 'on' ? 'selected' : ''; ?>>Booking ON</option>
                                                        <option value="off" <?php echo ($settings['thursday_booking'] ?? 'off') === 'off' ? 'selected' : ''; ?>>Booking OFF</option>
                                                    </select>
                                    </div>
                                </div>
                            </div>
                                        
                            <div class="row">
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Friday
                                                    </label>
                                                    <select name="friday_booking" class="form-select">
                                                        <option value="on" <?php echo ($settings['friday_booking'] ?? 'off') === 'on' ? 'selected' : ''; ?>>Booking ON</option>
                                                        <option value="off" <?php echo ($settings['friday_booking'] ?? 'off') === 'off' ? 'selected' : ''; ?>>Booking OFF</option>
                                                    </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Saturday
                                                    </label>
                                                    <select name="saturday_booking" class="form-select">
                                                        <option value="on" <?php echo ($settings['saturday_booking'] ?? 'on') === 'on' ? 'selected' : ''; ?>>Booking ON</option>
                                                        <option value="off" <?php echo ($settings['saturday_booking'] ?? 'on') === 'off' ? 'selected' : ''; ?>>Booking OFF</option>
                                                    </select>
                                </div>
                            </div>
                        </div>
                        
                            <div class="row">
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Sunday
                                                    </label>
                                                    <select name="sunday_booking" class="form-select">
                                                        <option value="on" <?php echo ($settings['sunday_booking'] ?? 'on') === 'on' ? 'selected' : ''; ?>>Booking ON</option>
                                                        <option value="off" <?php echo ($settings['sunday_booking'] ?? 'on') === 'off' ? 'selected' : ''; ?>>Booking OFF</option>
                                                    </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-plus me-2"></i>Advance Booking Days
                                                    </label>
                                                    <input type="number" name="advance_booking_days" class="form-control" 
                                                           value="<?php echo htmlspecialchars($settings['advance_booking_days'] ?? '7'); ?>" 
                                                           min="1" max="30" required>
                                                    <small class="text-muted">How many days in advance users can book</small>
                                    </div>
                                </div>
                            </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-toggle-on me-2"></i>General Booking
                                            </label>
                                            <select name="general_booking_enabled" class="form-select">
                                                <option value="on" <?php echo ($settings['general_booking_enabled'] ?? 'on') === 'on' ? 'selected' : ''; ?>>Enabled</option>
                                                <option value="off" <?php echo ($settings['general_booking_enabled'] ?? 'on') === 'off' ? 'selected' : ''; ?>>Disabled</option>
                                            </select>
                                            <small class="text-muted">Allow general booking when all slots are full</small>
                                    </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-comment me-2"></i>General Booking Message
                                            </label>
                                            <textarea name="general_booking_message" class="form-control" rows="2" 
                                                      placeholder="Message shown when slots are full"><?php echo htmlspecialchars($settings['general_booking_message'] ?? 'All slots are full. General booking available for consultation.'); ?></textarea>
                                            <small class="text-muted">Message displayed when no slots are available</small>
                                </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">
                                            <i class="fas fa-clock me-2 text-info"></i>Time & Slot Settings
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-hourglass-half me-2"></i>Slot Duration (minutes)
                                                    </label>
                                                    <select name="slot_duration" class="form-select" required>
                                                        <option value="15" <?php echo $slot_duration == 15 ? 'selected' : ''; ?>>15 minutes</option>
                                                        <option value="20" <?php echo $slot_duration == 20 ? 'selected' : ''; ?>>20 minutes</option>
                                                        <option value="30" <?php echo $slot_duration == 30 ? 'selected' : ''; ?>>30 minutes</option>
                                                        <option value="45" <?php echo $slot_duration == 45 ? 'selected' : ''; ?>>45 minutes</option>
                                                        <option value="60" <?php echo $slot_duration == 60 ? 'selected' : ''; ?>>60 minutes (1 hour)</option>
                                                        <option value="90" <?php echo $slot_duration == 90 ? 'selected' : ''; ?>>90 minutes (1.5 hours)</option>
                                                        <option value="120" <?php echo $slot_duration == 120 ? 'selected' : ''; ?>>120 minutes (2 hours)</option>
                                                    </select>
                                                    <small class="text-muted">Duration of each appointment slot (current: <?php echo $slot_duration; ?> minutes)</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-layer-group me-2"></i>Slots Per Hour
                                                    </label>
                                                    <select name="slots_per_hour" class="form-select" required>
                                                        <option value="1" <?php echo $slots_per_hour == 1 ? 'selected' : ''; ?>>1 slot per hour</option>
                                                        <option value="2" <?php echo $slots_per_hour == 2 ? 'selected' : ''; ?>>2 slots per hour</option>
                                                        <option value="3" <?php echo $slots_per_hour == 3 ? 'selected' : ''; ?>>3 slots per hour</option>
                                                        <option value="4" <?php echo $slots_per_hour == 4 ? 'selected' : ''; ?>>4 slots per hour</option>
                                                    </select>
                                                    <small class="text-muted">How many slots to create per hour (current: <?php echo $slots_per_hour; ?> per hour)</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-sun me-2"></i>Start Time
                                                    </label>
                                                    <input type="time" name="start_time" class="form-control" 
                                                           value="<?php echo htmlspecialchars($start_time); ?>" required>
                                                    <small class="text-muted">When appointments start each day</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-moon me-2"></i>End Time
                                                    </label>
                                                    <input type="time" name="end_time" class="form-control" 
                                                           value="<?php echo htmlspecialchars($end_time); ?>" required>
                                                    <small class="text-muted">When appointments end each day</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-utensils me-2"></i>Lunch Start Time
                                                    </label>
                                                    <input type="time" name="lunch_start" class="form-control" 
                                                           value="<?php echo htmlspecialchars($lunch_start); ?>" required>
                                                    <small class="text-muted">When lunch break starts</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-utensils me-2"></i>Lunch End Time
                                                    </label>
                                                    <input type="time" name="lunch_end" class="form-control" 
                                                           value="<?php echo htmlspecialchars($lunch_end); ?>" required>
                                                    <small class="text-muted">When lunch break ends</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">
                                            <i class="fas fa-rupee-sign me-2 text-success"></i>Pricing Settings
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Tuesday Price (₹)
                                                    </label>
                                                    <input type="number" name="tuesday_price" class="form-control" 
                                                           value="<?php echo htmlspecialchars($tuesday_price); ?>" 
                                                           min="100" max="5000" required>
                                                    <small class="text-muted">Appointment price for Tuesday</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Saturday Price (₹)
                                                    </label>
                                                    <input type="number" name="saturday_price" class="form-control" 
                                                           value="<?php echo htmlspecialchars($saturday_price); ?>" 
                                                           min="100" max="5000" required>
                                                    <small class="text-muted">Appointment price for Saturday</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Sunday Price (₹)
                                                    </label>
                                                    <input type="number" name="sunday_price" class="form-control" 
                                                           value="<?php echo htmlspecialchars($sunday_price); ?>" 
                                                           min="100" max="5000" required>
                                                    <small class="text-muted">Appointment price for Sunday</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-day me-2"></i>Other Days Price (₹)
                                                    </label>
                                                    <input type="number" name="other_days_price" class="form-control" 
                                                           value="<?php echo htmlspecialchars($other_days_price); ?>" 
                                                           min="100" max="5000" required>
                                                    <small class="text-muted">Appointment price for other days</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">
                                            <i class="fas fa-cog me-2 text-warning"></i>System Settings
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-toggle-on me-2"></i>System Status
                                                    </label>
                                                    <select name="system_enabled" class="form-select">
                                                        <option value="1" <?php echo $system_enabled === '1' ? 'selected' : ''; ?>>Enabled</option>
                                                        <option value="0" <?php echo $system_enabled === '0' ? 'selected' : ''; ?>>Disabled</option>
                                                    </select>
                                                    <small class="text-muted">Enable or disable the entire system</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-tools me-2"></i>Maintenance Mode
                                                    </label>
                                                    <select name="maintenance_mode" class="form-select">
                                                        <option value="0" <?php echo $maintenance_mode === '0' ? 'selected' : ''; ?>>Off</option>
                                                        <option value="1" <?php echo $maintenance_mode === '1' ? 'selected' : ''; ?>>On</option>
                                                    </select>
                                                    <small class="text-muted">Put system in maintenance mode</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-comment me-2"></i>Maintenance Message
                                            </label>
                                            <textarea name="maintenance_message" class="form-control" rows="2" 
                                                      placeholder="Message shown during maintenance"><?php echo htmlspecialchars($maintenance_message); ?></textarea>
                                            <small class="text-muted">Message displayed when system is in maintenance mode</small>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">
                                            <i class="fas fa-mobile-alt me-2 text-primary"></i>App Settings
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-code-branch me-2"></i>App Version
                                                    </label>
                                                    <input type="text" name="app_version" class="form-control" 
                                                           value="<?php echo htmlspecialchars($app_version); ?>" 
                                                           placeholder="e.g., 1.0.0" required>
                                                    <small class="text-muted">Current app version number</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-exclamation-triangle me-2"></i>Force Update
                                                    </label>
                                                    <select name="force_update" class="form-select">
                                                        <option value="0" <?php echo $force_update === '0' ? 'selected' : ''; ?>>No</option>
                                                        <option value="1" <?php echo $force_update === '1' ? 'selected' : ''; ?>>Yes</option>
                                                    </select>
                                                    <small class="text-muted">Force users to update the app</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="setting-item">
                                            <label class="form-label fw-bold">
                                                <i class="fas fa-bell me-2"></i>Update Message
                                            </label>
                                            <textarea name="update_message" class="form-control" rows="2" 
                                                      placeholder="Message shown when update is required"><?php echo htmlspecialchars($update_message); ?></textarea>
                                            <small class="text-muted">Message displayed when app update is required</small>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">
                                            <i class="fas fa-phone-alt me-2 text-success"></i>Consultation Types Settings
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-phone me-2"></i>Audio Call
                                                    </label>
                                                    <select name="audio_call_enabled" class="form-select">
                                                        <option value="on" <?php echo ($settings['audio_call_enabled'] ?? 'on') === 'on' ? 'selected' : ''; ?>>Enabled</option>
                                                        <option value="off" <?php echo ($settings['audio_call_enabled'] ?? 'on') === 'off' ? 'selected' : ''; ?>>Disabled</option>
                                                    </select>
                                                    <small class="text-muted">Allow users to book audio call consultations</small>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-video me-2"></i>Video Call
                                                    </label>
                                                    <select name="video_call_enabled" class="form-select">
                                                        <option value="on" <?php echo ($settings['video_call_enabled'] ?? 'on') === 'on' ? 'selected' : ''; ?>>Enabled</option>
                                                        <option value="off" <?php echo ($settings['video_call_enabled'] ?? 'on') === 'off' ? 'selected' : ''; ?>>Disabled</option>
                                                    </select>
                                                    <small class="text-muted">Allow users to book video call consultations</small>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-building me-2"></i>Office Meeting
                                                    </label>
                                                    <select name="office_meeting_enabled" class="form-select">
                                                        <option value="on" <?php echo ($settings['office_meeting_enabled'] ?? 'on') === 'on' ? 'selected' : ''; ?>>Enabled</option>
                                                        <option value="off" <?php echo ($settings['office_meeting_enabled'] ?? 'on') === 'off' ? 'selected' : ''; ?>>Disabled</option>
                                                    </select>
                                                    <small class="text-muted">Allow users to book office meeting consultations</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">
                                            <i class="fas fa-calendar-times me-2 text-danger"></i>Specific Date Blocking
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-calendar-minus me-2"></i>Block Specific Date
                                                    </label>
                                                    <div class="d-flex gap-2">
                                                        <input type="date" id="block_date" class="form-control" required 
                                                               min="<?php echo date('Y-m-d'); ?>" 
                                                               value="<?php echo date('Y-m-d'); ?>">
                                                        <input type="text" id="block_reason" class="form-control" 
                                                               placeholder="Reason (optional)" maxlength="255">
                                                        <button type="button" class="btn btn-danger" onclick="blockDate()">
                                                            <i class="fas fa-ban me-1"></i>Block
                                                        </button>
                                                    </div>
                                                    <small class="text-muted">Block bookings for a specific date (future dates only)</small>
                                                    <div id="date-validation-error" class="text-danger mt-2" style="display: none;"></div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-list me-2"></i>Currently Blocked Dates
                                                    </label>
                                                    <div class="blocked-dates-list">
                                                        <?php if (empty($blocked_dates)): ?>
                                                            <p class="text-muted">No dates are currently blocked</p>
                                                        <?php else: ?>
                                                            <?php foreach ($blocked_dates as $blocked): ?>
                                                                <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded mb-2">
                                                                    <div>
                                                                        <strong><?php echo date('d M Y', strtotime($blocked['block_date'])); ?></strong>
                                                                        <?php if ($blocked['reason']): ?>
                                                                            <br><small class="text-muted"><?php echo htmlspecialchars($blocked['reason']); ?></small>
                                                                        <?php endif; ?>
                                                                        <br><small class="text-muted">Blocked by: <?php echo htmlspecialchars($blocked['created_by'] ?? 'admin'); ?></small>
                                                                    </div>
                                                                    <button type="button" class="btn btn-sm btn-outline-success" onclick="unblockDate(<?php echo $blocked['id']; ?>)">
                                                                        <i class="fas fa-unlock me-1"></i>Unblock
                                                                    </button>
                                                                </div>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                    <small class="text-muted">Click unblock to remove date restrictions</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <div class="text-center mt-4">
                                            <button type="submit" name="update_settings" class="btn btn-save btn-lg" id="saveSettingsBtn">
                                                <i class="fas fa-save me-2"></i>Save All Settings
                                            </button>
                                    </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                        <div class="settings-card">
                                <div class="card-body">
                                    <h6 class="card-title text-warning">
                                        <i class="fas fa-info-circle me-2"></i>Current Settings
                                    </h6>
                                    
                                    <div class="mt-3">
                                        <p><strong>Help Mobile:</strong><br><?php echo htmlspecialchars($help_mobile); ?></p>
                                        <p><strong>Support Hours:</strong><br><?php echo htmlspecialchars($support_hours); ?></p>
                                        <p><strong>Support Email:</strong><br><?php echo htmlspecialchars($support_email); ?></p>
                                        <p><strong>Languages:</strong><br><?php echo htmlspecialchars($language_support); ?></p>
                                        
                                        <hr>
                                        
                                        <p><strong>Slot Duration:</strong><br><?php echo htmlspecialchars($slot_duration); ?> minutes</p>
                                        <p><strong>Slots Per Hour:</strong><br><?php echo htmlspecialchars($slots_per_hour); ?></p>
                                        <p><strong>Working Hours:</strong><br><?php echo htmlspecialchars($start_time); ?> - <?php echo htmlspecialchars($end_time); ?></p>
                                        <p><strong>Lunch Break:</strong><br><?php echo htmlspecialchars($lunch_start); ?> - <?php echo htmlspecialchars($lunch_end); ?></p>
                                        
                                        <hr>
                                        
                                        <p><strong>Tuesday Price:</strong><br>₹<?php echo htmlspecialchars($tuesday_price); ?></p>
                                        <p><strong>Saturday Price:</strong><br>₹<?php echo htmlspecialchars($saturday_price); ?></p>
                                        <p><strong>Sunday Price:</strong><br>₹<?php echo htmlspecialchars($sunday_price); ?></p>
                                        <p><strong>Other Days Price:</strong><br>₹<?php echo htmlspecialchars($other_days_price); ?></p>
                                        
                                        <hr>
                                        
                                        <p><strong>System Status:</strong><br><?php echo $system_enabled === '1' ? '✅ Enabled' : '❌ Disabled'; ?></p>
                                        <p><strong>Maintenance Mode:</strong><br><?php echo $maintenance_mode === '1' ? '🔧 On' : '✅ Off'; ?></p>
                                        <p><strong>App Version:</strong><br><?php echo htmlspecialchars($app_version); ?></p>
                                        <p><strong>Force Update:</strong><br><?php echo $force_update === '1' ? '⚠️ Yes' : '✅ No'; ?></p>
                                    </div>
                                    
                                    <hr>
                                    
                                    <div class="text-center">
                                        <button class="btn btn-outline-warning btn-sm" onclick="testWhatsApp()">
                                            <i class="fab fa-whatsapp me-2"></i>Test WhatsApp
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Edit Quote Modal -->
    <div class="modal fade" id="editQuoteModal" tabindex="-1" aria-labelledby="editQuoteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content bg-dark text-light">
                <div class="modal-header">
                    <h5 class="modal-title" id="editQuoteModalLabel">
                        <i class="fas fa-edit me-2"></i>Edit Quote
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="" id="editQuoteForm">
                    <div class="modal-body">
                        <input type="hidden" name="quote_action" value="update">
                        <input type="hidden" name="quote_id" id="edit_quote_id">
                        
                        <div class="row g-3">
                            <div class="col-12">
                                <label class="form-label">Quote Text</label>
                                <textarea name="quote_text" id="edit_quote_text" class="form-control" rows="4" 
                                          placeholder="Enter inspirational quote" required></textarea>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Author</label>
                                <input type="text" name="quote_author" id="edit_quote_author" class="form-control" 
                                       placeholder="Author name">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Category</label>
                                <select name="quote_category" id="edit_quote_category" class="form-select">
                                    <option value="astrology">Astrology</option>
                                    <option value="motivation">Motivation</option>
                                    <option value="spirituality">Spirituality</option>
                                    <option value="destiny">Destiny</option>
                                    <option value="cosmic">Cosmic</option>
                                    <option value="general">General</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Display Order</label>
                                <input type="number" name="quote_display_order" id="edit_quote_display_order" class="form-control" 
                                       min="0" max="100">
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="quote_is_active" id="edit_quote_is_active">
                                    <label class="form-check-label" for="edit_quote_is_active">
                                        Quote is active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Quote</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Form submission handling
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.querySelector('#mainSettingsForm');
            if (form) {
                form.addEventListener('submit', function(e) {
                    // Show loading state
                    const submitBtn = form.querySelector('button[name="update_settings"]');
                    if (submitBtn) {
                        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
                        submitBtn.disabled = true;
                    }
                });
            }
        });
        
        function openHelp() {
            const message = '<?php echo addslashes($whatsapp_message); ?>';
            const whatsappUrl = `https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $help_mobile); ?>?text=${encodeURIComponent(message)}`;
            window.open(whatsappUrl, '_blank');
        }
        
        function testWhatsApp() {
            const message = '<?php echo addslashes($whatsapp_message); ?>';
            const whatsappUrl = `https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $help_mobile); ?>`;
            window.open(whatsappUrl, '_blank');
        }
        
        function validateBlockDate() {
            const blockDateInput = document.getElementById('block_date');
            const blockReasonInput = document.querySelector('input[name="block_reason"]');
            const dateValidationError = document.getElementById('date-validation-error');

            if (blockDateInput.value < new Date().toISOString().slice(0, 10)) {
                dateValidationError.textContent = 'You cannot block past dates. Please select a future date.';
                dateValidationError.style.display = 'block';
                return false;
            }

            if (blockReasonInput.value.length > 255) {
                dateValidationError.textContent = 'Reason cannot exceed 255 characters.';
                dateValidationError.style.display = 'block';
                return false;
            }

            dateValidationError.style.display = 'none';
            return true;
        }
        



        





        
                 function blockDate() {
             const blockDateInput = document.getElementById('block_date');
             const blockReasonInput = document.getElementById('block_reason');
             const dateValidationError = document.getElementById('date-validation-error');
             
             if (!validateBlockDate()) {
                 return;
             }
             
             // Use AJAX to submit date blocking without affecting main form
             const formData = new FormData();
             formData.append('block_date', blockDateInput.value);
             formData.append('block_reason', blockReasonInput.value || 'Admin blocked');
             
             fetch(window.location.href, {
                 method: 'POST',
                 body: formData
             })
             .then(response => response.text())
             .then(data => {
                 console.log('Date blocked successfully');
                 // Reload page to show updated blocked dates
                 window.location.reload();
             })
             .catch(error => {
                 console.error('Error blocking date:', error);
                 dateValidationError.textContent = 'Error blocking date. Please try again.';
                 dateValidationError.style.display = 'block';
             });
         }
         
         function unblockDate(dateId) {
             if (confirm('Are you sure you want to unblock this date?')) {
                 // Use AJAX to submit unblock request without affecting main form
                 const formData = new FormData();
                 formData.append('date_id', dateId);
                 formData.append('unblock_date', '1');
                 
                 fetch(window.location.href, {
                     method: 'POST',
                     body: formData
                 })
                 .then(response => response.text())
                 .then(data => {
                     console.log('Date unblocked successfully');
                     // Reload page to show updated blocked dates
                     window.location.reload();
                 })
                 .catch(error => {
                     console.error('Error unblocking date:', error);
                     alert('Error unblocking date. Please try again.');
                 });
             }
        }
        
        // Quote management functions
        function editQuote(quoteData) {
            document.getElementById('edit_quote_id').value = quoteData.id;
            document.getElementById('edit_quote_text').value = quoteData.quote_text;
            document.getElementById('edit_quote_author').value = quoteData.author || '';
            document.getElementById('edit_quote_category').value = quoteData.category;
            document.getElementById('edit_quote_display_order').value = quoteData.display_order;
            document.getElementById('edit_quote_is_active').checked = quoteData.is_active == 1;
            
            const modal = new bootstrap.Modal(document.getElementById('editQuoteModal'));
            modal.show();
        }
        
        function deleteQuote(quoteId) {
            if (confirm('Are you sure you want to delete this quote? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="quote_action" value="delete">
                    <input type="hidden" name="quote_id" value="${quoteId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html> 