<?php
session_start();
require_once '../config/database.php';

$page_title = 'Day Management';
$current_page = 'day_management.php';

$pdo = getDBConnection();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $normalDays = $_POST['normal_days'] ?? [];
        $tatkalDays = $_POST['tatkal_days'] ?? [];
        
        // Update normal days (update both value and setting_value columns)
        $normalDaysUpdate = $pdo->prepare("UPDATE settings SET value = ?, setting_value = ? WHERE setting_key = ?");
        $normalDaysUpdate->execute([json_encode($normalDays), json_encode($normalDays), 'normal_days']);
        
        // Update tatkal days (update both value and setting_value columns)
        $tatkalDaysUpdate = $pdo->prepare("UPDATE settings SET value = ?, setting_value = ? WHERE setting_key = ?");
        $tatkalDaysUpdate->execute([json_encode($tatkalDays), json_encode($tatkalDays), 'tatkal_days']);
        
        $success_message = "Days updated successfully!";
    } catch (Exception $e) {
        $error_message = "Error updating days: " . $e->getMessage();
    }
}

// Get current settings (check both value and setting_value columns)
$normalDaysQuery = $pdo->prepare("SELECT COALESCE(value, setting_value) FROM settings WHERE setting_key = 'normal_days'");
$normalDaysQuery->execute();
$normalDays = json_decode($normalDaysQuery->fetchColumn() ?: '[]', true);

$tatkalDaysQuery = $pdo->prepare("SELECT COALESCE(value, setting_value) FROM settings WHERE setting_key = 'tatkal_days'");
$tatkalDaysQuery->execute();
$tatkalDays = json_decode($tatkalDaysQuery->fetchColumn() ?: '[]', true);

// Default days if not set
if (empty($normalDays)) {
    $normalDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
}

if (empty($tatkalDays)) {
    $tatkalDays = ['monday', 'tuesday', 'wednesday', 'friday'];
}

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

ob_start();
?>

<!-- Alerts -->
<?php if (isset($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 (isset($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; ?>

<!-- Day Management Form -->
<div class="content-card">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">
            <i class="fas fa-calendar-alt me-2 text-primary"></i>
            Day Management
        </h2>
        <div class="text-muted">
            <i class="fas fa-info-circle me-1"></i>
            Manage working days for bookings
        </div>
    </div>

    <form method="POST" id="dayManagementForm">
        <div class="row">
            <!-- Normal Days Section -->
            <div class="col-lg-6">
                <div class="card h-100 border-success">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0">
                            <i class="fas fa-calendar-check me-2"></i>
                            Normal Booking Days
                        </h5>
                        <small>Select days when normal appointments are available</small>
                    </div>
                    <div class="card-body">
                        <?php foreach ($days as $dayKey => $dayName): ?>
                            <div class="form-check form-switch mb-3 p-3 border rounded">
                                <input class="form-check-input" type="checkbox" 
                                       id="normal_<?php echo $dayKey; ?>" 
                                       name="normal_days[]" 
                                       value="<?php echo $dayKey; ?>"
                                       <?php echo in_array($dayKey, $normalDays) ? 'checked' : ''; ?>>
                                <label class="form-check-label w-100" for="normal_<?php echo $dayKey; ?>">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <strong><?php echo $dayName; ?></strong>
                                            <br>
                                            <small class="text-muted">Normal appointments</small>
                                        </div>
                                        <span class="badge bg-<?php echo in_array($dayKey, $normalDays) ? 'success' : 'secondary'; ?>">
                                            <?php echo in_array($dayKey, $normalDays) ? 'Enabled' : 'Disabled'; ?>
                                        </span>
                                    </div>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Tatkal Days Section -->
            <div class="col-lg-6">
                <div class="card h-100 border-warning">
                    <div class="card-header bg-warning text-dark">
                        <h5 class="mb-0">
                            <i class="fas fa-bolt me-2"></i>
                            Tatkal Booking Days
                        </h5>
                        <small>Select days when tatkal appointments are available</small>
                    </div>
                    <div class="card-body">
                        <?php foreach ($days as $dayKey => $dayName): ?>
                            <div class="form-check form-switch mb-3 p-3 border rounded">
                                <input class="form-check-input" type="checkbox" 
                                       id="tatkal_<?php echo $dayKey; ?>" 
                                       name="tatkal_days[]" 
                                       value="<?php echo $dayKey; ?>"
                                       <?php echo in_array($dayKey, $tatkalDays) ? 'checked' : ''; ?>>
                                <label class="form-check-label w-100" for="tatkal_<?php echo $dayKey; ?>">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <strong><?php echo $dayName; ?></strong>
                                            <br>
                                            <small class="text-muted">Tatkal appointments</small>
                                        </div>
                                        <span class="badge bg-<?php echo in_array($dayKey, $tatkalDays) ? 'warning' : 'secondary'; ?>">
                                            <?php echo in_array($dayKey, $tatkalDays) ? 'Enabled' : 'Disabled'; ?>
                                        </span>
                                    </div>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Save Button -->
        <div class="text-center mt-4">
            <button type="submit" class="btn btn-primary btn-lg px-5">
                <i class="fas fa-save me-2"></i>
                Save Changes
            </button>
        </div>
    </form>
</div>

<!-- Summary Cards -->
<div class="row">
    <div class="col-md-6">
        <div class="content-card">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0">
                    <i class="fas fa-calendar-check me-2"></i>
                    Normal Days Summary
                </h5>
            </div>
            <div class="card-body">
                <p class="mb-2">
                    <strong>Enabled Days:</strong> 
                    <?php 
                    $enabledNormal = array_intersect($normalDays, array_keys($days));
                    echo empty($enabledNormal) ? 'None' : implode(', ', array_map(function($day) use ($days) { return $days[$day]; }, $enabledNormal));
                    ?>
                </p>
                <p class="mb-0">
                    <strong>Total:</strong> 
                    <span class="badge bg-success"><?php echo count($enabledNormal); ?> days</span>
                </p>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="content-card">
            <div class="card-header bg-warning text-dark">
                <h5 class="mb-0">
                    <i class="fas fa-bolt me-2"></i>
                    Tatkal Days Summary
                </h5>
            </div>
            <div class="card-body">
                <p class="mb-2">
                    <strong>Enabled Days:</strong> 
                    <?php 
                    $enabledTatkal = array_intersect($tatkalDays, array_keys($days));
                    echo empty($enabledTatkal) ? 'None' : implode(', ', array_map(function($day) use ($days) { return $days[$day]; }, $enabledTatkal));
                    ?>
                </p>
                <p class="mb-0">
                    <strong>Total:</strong> 
                    <span class="badge bg-warning"><?php echo count($enabledTatkal); ?> days</span>
                </p>
            </div>
        </div>
    </div>
</div>

<script>
// Update status badges when checkboxes change
document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const badge = this.closest('.form-check').querySelector('.badge');
        if (this.checked) {
            badge.textContent = 'Enabled';
            badge.className = 'badge bg-success';
        } else {
            badge.textContent = 'Disabled';
            badge.className = 'badge bg-secondary';
        }
    });
});

// Form validation
document.getElementById('dayManagementForm').addEventListener('submit', function(e) {
    const normalDays = document.querySelectorAll('input[name="normal_days[]"]:checked');
    const tatkalDays = document.querySelectorAll('input[name="tatkal_days[]"]:checked');
    
    if (normalDays.length === 0) {
        e.preventDefault();
        alert('Please select at least one normal booking day.');
        return;
    }
    
    if (tatkalDays.length === 0) {
        e.preventDefault();
        alert('Please select at least one tatkal booking day.');
        return;
    }
});
</script>

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