<?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;
}

$page_title = 'Manage Book Your Appointment';
$current_page = 'manage_booking_settings.php';

$pdo = getDBConnection();

$success_message = '';
$error_message = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['update_days'])) {
            // Update working days using existing system format
            $working_days = $_POST['working_days'] ?? [];
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            
            // Update individual day settings to match existing system
            $days_list = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            foreach ($days_list as $day) {
                $day_key = $day . '_booking';
                $day_value = in_array($day, $working_days) ? 'on' : 'off';
                $stmt->execute([$day_key, $day_value, $day_value]);
            }
            $success_message = "Working days updated successfully!";
        }
        
        if (isset($_POST['update_time_settings'])) {
            // Update time settings using existing system format
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            
            if (isset($_POST['slot_duration'])) {
                $stmt->execute(['slot_duration', (int)$_POST['slot_duration'], (int)$_POST['slot_duration']]);
            }
            
            if (isset($_POST['slots_per_hour'])) {
                $stmt->execute(['slots_per_hour', $_POST['slots_per_hour'], $_POST['slots_per_hour']]);
            }
            
            if (isset($_POST['start_time'])) {
                $stmt->execute(['start_time', $_POST['start_time'], $_POST['start_time']]);
            }
            
            if (isset($_POST['end_time'])) {
                $stmt->execute(['end_time', $_POST['end_time'], $_POST['end_time']]);
            }
            
            if (isset($_POST['advance_booking_days'])) {
                $stmt->execute(['advance_booking_days', (int)$_POST['advance_booking_days'], (int)$_POST['advance_booking_days']]);
            }
            
            $success_message = "Time settings updated successfully!";
        }
        
        if (isset($_POST['update_lunch_break'])) {
            // Update lunch break using existing system format
            $lunch_start = $_POST['lunch_start'];
            $lunch_end = $_POST['lunch_end'];
            $lunch_enabled = isset($_POST['lunch_enabled']) ? 1 : 0;
            
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            
            // Use existing lunch_start and lunch_end keys
            $stmt->execute(['lunch_start', $lunch_start, $lunch_start]);
            $stmt->execute(['lunch_end', $lunch_end, $lunch_end]);
            $stmt->execute(['lunch_break_enabled', $lunch_enabled, $lunch_enabled]);
            
            $success_message = "Lunch break settings updated successfully!";
        }
        
        if (isset($_POST['update_consultation_types'])) {
            // Update consultation types in consultation_types table
            if (isset($_POST['consultation_types'])) {
                foreach ($_POST['consultation_types'] as $type_code => $data) {
                    $is_active = isset($data['enabled']) ? 1 : 0;
                    $base_price = (float)$data['price'];
                    
                    $stmt = $pdo->prepare("UPDATE consultation_types SET is_active = ?, base_price = ? WHERE type_code = ?");
                    $stmt->execute([$is_active, $base_price, $type_code]);
                }
            }
            $success_message = "Consultation types updated successfully!";
        }
        
    } catch (Exception $e) {
        $error_message = "Error updating settings: " . $e->getMessage();
    }
}

// Get current settings
function getSetting($key, $default = '') {
    global $pdo;
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $result = $stmt->fetchColumn();
    return $result ? $result : $default;
}

// Get working days from existing system format
$working_days = [];
$days_list = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
foreach ($days_list as $day) {
    $day_setting = getSetting($day . '_booking', 'off');
    if ($day_setting === 'on') {
        $working_days[] = $day;
    }
}

// Get time settings from existing system format
$slot_duration = (int)getSetting('slot_duration', '20'); // Default to 20 minutes as per current DB
$slots_per_hour = getSetting('slots_per_hour', '1');
$start_time = getSetting('start_time', '09:00');
$end_time = getSetting('end_time', '18:00');
$advance_booking_days = (int)getSetting('advance_booking_days', '7');

// Get lunch break settings from existing system format
$lunch_start = getSetting('lunch_start', '12:30');
$lunch_end = getSetting('lunch_end', '13:30');
$lunch_enabled = getSetting('lunch_break_enabled', '1');

// Get consultation types from consultation_types table
$consultation_types = [];
try {
    $stmt = $pdo->prepare("SELECT type_name, type_code, base_price, is_active FROM consultation_types ORDER BY id ASC");
    $stmt->execute();
    $types = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($types as $type) {
        $consultation_types[$type['type_code']] = [
            'name' => $type['type_name'],
            'enabled' => (int)$type['is_active'],
            'price' => (float)$type['base_price']
        ];
    }
} catch (Exception $e) {
    // Fallback to empty array if table doesn't exist
    $consultation_types = [];
}

$days = [
    'monday' => 'Monday',
    'tuesday' => 'Tuesday',
    'wednesday' => 'Wednesday',
    'thursday' => 'Thursday',
    'friday' => 'Friday',
    'saturday' => 'Saturday',
    'sunday' => 'Sunday'
];

ob_start();
?>

<style>
.settings-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 25px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    border-left: 4px solid #667eea;
}

.settings-card h4 {
    color: #2c3e50;
    margin-bottom: 20px;
    font-weight: 600;
}

.day-toggle {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 10px;
    border: 2px solid transparent;
    transition: all 0.3s ease;
}

.day-toggle.active {
    background: #e8f5e8;
    border-color: #28a745;
}

/* Time slot items removed - using form controls now */

.consultation-type-card {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 15px;
    border: 2px solid transparent;
    transition: all 0.3s ease;
}

.consultation-type-card.enabled {
    background: #e8f5e8;
    border-color: #28a745;
}

.consultation-type-card.disabled {
    background: #fff3cd;
    border-color: #ffc107;
    opacity: 0.7;
}

.lunch-break-card {
    background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
    border-radius: 12px;
    padding: 20px;
    border: 2px solid #ff9800;
}

.btn-save {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 25px;
    padding: 12px 30px;
    color: white;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-save:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
    color: white;
}

.form-check-input:checked {
    background-color: #667eea;
    border-color: #667eea;
}

.form-control:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.price-input {
    max-width: 120px;
}

@media (max-width: 768px) {
    .settings-card {
        padding: 15px;
        margin-bottom: 15px;
    }
    
    /* Time slot items removed */
    
    .consultation-type-card {
        padding: 15px;
        margin-bottom: 10px;
    }
    
    .day-toggle {
        padding: 10px;
        margin-bottom: 8px;
    }
    
    .lunch-break-card .row {
        gap: 15px;
    }
    
    .lunch-break-card .col-md-3 {
        margin-bottom: 15px;
    }
}

@media (max-width: 576px) {
    .settings-card {
        padding: 12px;
        margin-bottom: 12px;
    }
    
    .settings-card h4 {
        font-size: 1.2rem;
        margin-bottom: 15px;
    }
    
    /* Time slot items removed */
    
    .consultation-type-card {
        padding: 12px;
    }
    
    .consultation-type-card h6 {
        font-size: 1rem;
    }
    
    .day-toggle {
        padding: 8px;
    }
    
    .btn-save {
        width: 100%;
        margin-top: 10px;
    }
    
    .lunch-break-card {
        padding: 15px;
    }
    
    .lunch-break-card .col-md-3 {
        width: 100%;
        margin-bottom: 10px;
    }
    
    .input-group-text {
        font-size: 0.9rem;
    }
    
    .form-control {
        font-size: 0.9rem;
    }
    
    .price-input {
        max-width: 100%;
    }
}
</style>

<?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 $success_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i>
        <?php echo $error_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<!-- Working Days Settings -->
<div class="settings-card">
    <h4><i class="fas fa-calendar-week me-2"></i>Working Days</h4>
    <p class="text-muted mb-4">Select which days appointments can be booked</p>
    
    <form method="POST">
        <div class="row">
            <?php foreach ($days as $day_key => $day_name): ?>
                <div class="col-6 col-md-6 col-lg-4 mb-3">
                    <div class="day-toggle <?php echo in_array($day_key, $working_days) ? 'active' : ''; ?>">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="working_days[]" 
                                   value="<?php echo $day_key; ?>" id="day_<?php echo $day_key; ?>"
                                   <?php echo in_array($day_key, $working_days) ? 'checked' : ''; ?>>
                            <label class="form-check-label fw-bold" for="day_<?php echo $day_key; ?>">
                                <?php echo $day_name; ?>
                            </label>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <button type="submit" name="update_days" class="btn btn-save">
            <i class="fas fa-save me-2"></i>Update Working Days
        </button>
    </form>
</div>

<!-- Time Settings -->
<div class="settings-card">
    <h4><i class="fas fa-clock me-2"></i>Time Settings</h4>
    <p class="text-muted mb-4">Configure appointment timing and booking settings</p>
    
    <form method="POST">
        <div class="row">
            <div class="col-md-6 mb-3">
                <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">
                    <option value="10" <?php echo $slot_duration == 10 ? 'selected' : ''; ?>>10 minutes</option>
                    <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="25" <?php echo $slot_duration == 25 ? 'selected' : ''; ?>>25 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</option>
                    <option value="90" <?php echo $slot_duration == 90 ? 'selected' : ''; ?>>90 minutes</option>
                    <option value="120" <?php echo $slot_duration == 120 ? 'selected' : ''; ?>>120 minutes</option>
                </select>
            </div>
            
            <div class="col-md-6 mb-3">
                <label class="form-label fw-bold">
                    <i class="fas fa-list-ol me-2"></i>Slots Per Hour
                </label>
                <select name="slots_per_hour" class="form-select">
                    <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>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label fw-bold">
                    <i class="fas fa-play me-2"></i>Start Time
                </label>
                <input type="time" class="form-control" name="start_time" 
                       value="<?php echo $start_time; ?>" required>
            </div>
            
            <div class="col-md-6 mb-3">
                <label class="form-label fw-bold">
                    <i class="fas fa-stop me-2"></i>End Time
                </label>
                <input type="time" class="form-control" name="end_time" 
                       value="<?php echo $end_time; ?>" required>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label fw-bold">
                    <i class="fas fa-calendar-plus me-2"></i>Advance Booking Days
                </label>
                <input type="number" class="form-control" name="advance_booking_days" 
                       value="<?php echo $advance_booking_days; ?>" min="1" max="365" required>
                <small class="text-muted">How many days in advance can users book appointments</small>
            </div>
        </div>
        
        <button type="submit" name="update_time_settings" class="btn btn-save">
            <i class="fas fa-save me-2"></i>Update Time Settings
        </button>
    </form>
</div>

<!-- Lunch Break Settings -->
<div class="settings-card">
    <h4><i class="fas fa-utensils me-2"></i>Lunch Break</h4>
    <p class="text-muted mb-4">Configure lunch break timing</p>
    
    <form method="POST">
        <div class="lunch-break-card">
            <div class="row">
                <div class="col-12 col-md-3 mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="lunch_enabled" 
                               id="lunch_enabled" <?php echo $lunch_enabled ? 'checked' : ''; ?>>
                        <label class="form-check-label fw-bold" for="lunch_enabled">
                            Enable Lunch Break
                        </label>
                    </div>
                </div>
                <div class="col-6 col-md-3 mb-3">
                    <label class="form-label">Start Time</label>
                    <input type="time" class="form-control" name="lunch_start" 
                           value="<?php echo $lunch_start; ?>" required>
                </div>
                <div class="col-6 col-md-3 mb-3">
                    <label class="form-label">End Time</label>
                    <input type="time" class="form-control" name="lunch_end" 
                           value="<?php echo $lunch_end; ?>" required>
                </div>
                <div class="col-12 col-md-3 mb-3 d-flex align-items-end">
                    <button type="submit" name="update_lunch_break" class="btn btn-save w-100">
                        <i class="fas fa-save me-2"></i>Update
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>

<!-- Consultation Types Settings -->
<div class="settings-card">
    <h4><i class="fas fa-video me-2"></i>Consultation Types & Pricing</h4>
    <p class="text-muted mb-4">Manage consultation types and their prices</p>
    
    <form method="POST">
        <div class="row">
            <?php 
            // Define icons for different consultation types
            $type_icons = [
                'office_meeting' => 'fas fa-building',
                'video_call' => 'fas fa-video',
                'audio_call' => 'fas fa-phone',
                'tatkal_booking' => 'fas fa-bolt'
            ];
            
            foreach ($consultation_types as $type_code => $type_data): 
                $icon = isset($type_icons[$type_code]) ? $type_icons[$type_code] : 'fas fa-cog';
            ?>
                <div class="col-12 col-md-4 mb-3">
                    <div class="consultation-type-card <?php echo $type_data['enabled'] ? 'enabled' : 'disabled'; ?>">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">
                                <i class="<?php echo $icon; ?> me-2"></i><?php echo $type_data['name']; ?>
                            </h6>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" 
                                       name="consultation_types[<?php echo $type_code; ?>][enabled]" 
                                       id="<?php echo $type_code; ?>_enabled"
                                       <?php echo $type_data['enabled'] ? 'checked' : ''; ?>>
                            </div>
                        </div>
                        <div class="input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" class="form-control" 
                                   name="consultation_types[<?php echo $type_code; ?>][price]" 
                                   value="<?php echo $type_data['price']; ?>"
                                   min="0" step="10">
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <button type="submit" name="update_consultation_types" class="btn btn-save">
            <i class="fas fa-save me-2"></i>Update Consultation Types
        </button>
    </form>
</div>

<script>
// Update day toggle visual state
document.querySelectorAll('input[name="working_days[]"]').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const dayToggle = this.closest('.day-toggle');
        if (this.checked) {
            dayToggle.classList.add('active');
        } else {
            dayToggle.classList.remove('active');
        }
    });
});

// No time slot checkboxes anymore - using dropdowns and inputs

// Update consultation type visual state
document.querySelectorAll('input[type="checkbox"][name*="consultation_types"]').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const card = this.closest('.consultation-type-card');
        if (this.checked) {
            card.classList.remove('disabled');
            card.classList.add('enabled');
        } else {
            card.classList.remove('enabled');
            card.classList.add('disabled');
        }
    });
});

// Auto-hide alerts after 5 seconds
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        const bsAlert = new bootstrap.Alert(alert);
        bsAlert.close();
    });
}, 5000);
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>
