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

// Check if user is logged in (add your authentication logic here)
// if (!isset($_SESSION['admin_logged_in'])) {
//     header('Location: login.php');
//     exit();
// }

$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'
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Day Management - AstroSidhi 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, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .admin-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            margin: 20px;
            padding: 30px;
        }
        .header {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            color: white;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }
        .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>
</head>
<body>
    <div class="container-fluid">
        <div class="admin-container">
            <!-- Header -->
            <div class="header">
                <h1><i class="fas fa-calendar-alt me-3"></i>Day Management</h1>
                <p class="mb-0">Manage working days for Normal and Tatkal bookings</p>
            </div>

            <?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>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <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>
</body>
</html>
