<?php
require_once 'auth.php';

// Require admin login
requireAdminLogin();

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

// Get database connection
require_once '../config/database.php';
$pdo = getDBConnection();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $normalDays = $_POST['normal_days'] ?? [];
        $tatkalDays = $_POST['tatkal_days'] ?? [];
        
        // Update individual day settings for normal bookings
        $daySettings = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
        foreach ($daySettings as $day) {
            $isEnabled = in_array($day, $normalDays) ? 'on' : 'off';
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$day . '_booking', $isEnabled, $isEnabled]);
        }
        
        // Update individual day settings for tatkal bookings
        foreach ($daySettings as $day) {
            $isEnabled = in_array($day, $tatkalDays) ? '1' : '0';
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute(['tatkal_' . $day . '_enabled', $isEnabled, $isEnabled]);
        }
        
        $success_message = "Days updated successfully!";
    } catch (Exception $e) {
        $error_message = "Error updating days: " . $e->getMessage();
    }
}

// Get current settings for normal bookings
$normalDays = [];
$daySettings = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
foreach ($daySettings as $day) {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$day . '_booking']);
    $value = $stmt->fetchColumn();
    if ($value === 'on') {
        $normalDays[] = $day;
    }
}

// Get current settings for tatkal bookings
$tatkalDays = [];
foreach ($daySettings as $day) {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute(['tatkal_' . $day . '_enabled']);
    $value = $stmt->fetchColumn();
    if ($value === '1') {
        $tatkalDays[] = $day;
    }
}

// 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();
?>

<style>
.day-card {
    background: white;
    border-radius: 15px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    border: 2px solid transparent;
    transition: all 0.3s ease;
}
.day-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}
.day-card.normal {
    border-color: #28a745;
}
.day-card.tatkal {
    border-color: #ffc107;
}
.day-card.disabled {
    opacity: 0.6;
    background: #f8f9fa;
}
.form-check-input:checked {
    background-color: #28a745;
    border-color: #28a745;
}
.btn-save {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    border: none;
    padding: 12px 30px;
    border-radius: 25px;
    color: white;
    font-weight: bold;
    transition: all 0.3s ease;
}
.btn-save:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(40, 167, 69, 0.4);
}
.status-badge {
    padding: 5px 15px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: bold;
}
.status-enabled {
    background: #d4edda;
    color: #155724;
}
.status-disabled {
    background: #f8d7da;
    color: #721c24;
}
.section-title {
    color: #1a1a2e;
    font-weight: bold;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 3px solid #28a745;
}
.tatkal-section .section-title {
    border-bottom-color: #ffc107;
}
</style>

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

<form method="POST">
    <div class="row">
        <!-- Normal Days Section -->
        <div class="col-md-6">
            <div class="normal-section">
                <h3 class="section-title">
                    <i class="fas fa-calendar-check me-2"></i>Normal Booking Days
                </h3>
                <p class="text-muted mb-4">Select days when normal appointments are available</p>
                
                <?php foreach ($days as $dayKey => $dayName): ?>
                    <div class="day-card normal">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <div class="form-check form-switch me-3">
                                    <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' : ''; ?>>
                                </div>
                                <div>
                                    <h5 class="mb-1"><?php echo $dayName; ?></h5>
                                    <small class="text-muted">Normal appointments</small>
                                </div>
                            </div>
                            <span class="status-badge <?php echo in_array($dayKey, $normalDays) ? 'status-enabled' : 'status-disabled'; ?>">
                                <?php echo in_array($dayKey, $normalDays) ? 'Enabled' : 'Disabled'; ?>
                            </span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Tatkal Days Section -->
        <div class="col-md-6">
            <div class="tatkal-section">
                <h3 class="section-title">
                    <i class="fas fa-bolt me-2"></i>Tatkal Booking Days
                </h3>
                <p class="text-muted mb-4">Select days when tatkal appointments are available</p>
                
                <?php foreach ($days as $dayKey => $dayName): ?>
                    <div class="day-card tatkal">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <div class="form-check form-switch me-3">
                                    <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' : ''; ?>>
                                </div>
                                <div>
                                    <h5 class="mb-1"><?php echo $dayName; ?></h5>
                                    <small class="text-muted">Tatkal appointments</small>
                                </div>
                            </div>
                            <span class="status-badge <?php echo in_array($dayKey, $tatkalDays) ? 'status-enabled' : 'status-disabled'; ?>">
                                <?php echo in_array($dayKey, $tatkalDays) ? 'Enabled' : 'Disabled'; ?>
                            </span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

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

<!-- Current Status Summary -->
<div class="row mt-5">
    <div class="col-md-6">
        <div class="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><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><strong>Total:</strong> <?php echo count($enabledNormal); ?> days</p>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="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><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><strong>Total:</strong> <?php echo count($enabledTatkal); ?> days</p>
            </div>
        </div>
    </div>
</div>

<script>
// Update status badges when checkboxes change
document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const statusBadge = this.closest('.day-card').querySelector('.status-badge');
        if (this.checked) {
            statusBadge.textContent = 'Enabled';
            statusBadge.className = 'status-badge status-enabled';
        } else {
            statusBadge.textContent = 'Disabled';
            statusBadge.className = 'status-badge status-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';
?>
