<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$doctor_id = $_SESSION['user_id'];

// Get doctor's current availability settings from JSON in doctors table
$doctor_query = "SELECT availability FROM doctors WHERE user_id = ?";
$doctor_stmt = $conn->prepare($doctor_query);
$doctor_stmt->bind_param("i", $doctor_id);
$doctor_stmt->execute();
$doctor_result = $doctor_stmt->get_result()->fetch_assoc();
$availability = json_decode($doctor_result['availability'] ?? '{}', true);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $availability_data = [];
    $days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    
    foreach ($days as $day) {
        if (isset($_POST[$day . '_enabled'])) {
            $availability_data[$day] = [
                'enabled' => true,
                'start_time' => $_POST[$day . '_start'],
                'end_time' => $_POST[$day . '_end'],
                'break_start' => $_POST[$day . '_break_start'] ?? null,
                'break_end' => $_POST[$day . '_break_end'] ?? null
            ];
        } else {
            $availability_data[$day] = ['enabled' => false];
        }
    }
    
    $availability_json = json_encode($availability_data);
    
    $update_query = "UPDATE doctors SET availability = ? WHERE user_id = ?";
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param("si", $availability_json, $doctor_id);
    
    if ($update_stmt->execute()) {
        // Log activity
        $action = "UPDATE";
        $module = "DOCTOR_AVAILABILITY";
        $ip_address = $_SERVER['REMOTE_ADDR'];
        
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, ip_address) 
                    VALUES (?, ?, ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("issis", $_SESSION['user_id'], $action, $module, $doctor_id, $ip_address);
        $log_stmt->execute();
        
        $_SESSION['success_message'] = "Availability updated successfully!";
        header('Location: my_availability.php');
        exit();
    } else {
        $_SESSION['error_message'] = "Error updating availability";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Availability')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .day-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .day-card.active {
            border-color: #2d7a2d;
            background: #f8fef8;
        }
        
        .day-toggle {
            transform: scale(1.2);
        }
        
        .time-slot {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 6px;
            margin-top: 1rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">My Availability</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="ent_consultant_dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">My Availability</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <form method="POST" id="availabilityForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Weekly Schedule</h5>
                                    </div>
                                    <div class="card-body">
                                        <?php
                                        $days = [
                                            'monday' => 'Monday',
                                            'tuesday' => 'Tuesday',
                                            'wednesday' => 'Wednesday',
                                            'thursday' => 'Thursday',
                                            'friday' => 'Friday',
                                            'saturday' => 'Saturday',
                                            'sunday' => 'Sunday'
                                        ];
                                        
                                        foreach ($days as $day_key => $day_name):
                                            $day_data = $availability[$day_key] ?? ['enabled' => false];
                                            $is_enabled = $day_data['enabled'] ?? false;
                                        ?>
                                            <div class="day-card <?php echo $is_enabled ? 'active' : ''; ?>" id="card_<?php echo $day_key; ?>">
                                                <div class="row align-items-center">
                                                    <div class="col-md-3">
                                                        <div class="form-check form-switch">
                                                            <input class="form-check-input day-toggle" type="checkbox" 
                                                                   name="<?php echo $day_key; ?>_enabled" 
                                                                   id="<?php echo $day_key; ?>_enabled"
                                                                   <?php echo $is_enabled ? 'checked' : ''; ?>
                                                                   onchange="toggleDay('<?php echo $day_key; ?>')">
                                                            <label class="form-check-label fw-bold" for="<?php echo $day_key; ?>_enabled">
                                                                <?php echo $day_name; ?>
                                                            </label>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-9">
                                                        <div class="time-slot" id="<?php echo $day_key; ?>_times" 
                                                             style="display: <?php echo $is_enabled ? 'block' : 'none'; ?>;">
                                                            <div class="row">
                                                                <div class="col-md-6 mb-2">
                                                                    <label class="form-label">Working Hours</label>
                                                                    <div class="d-flex gap-2">
                                                                        <input type="time" class="form-control" 
                                                                               name="<?php echo $day_key; ?>_start" 
                                                                               value="<?php echo $day_data['start_time'] ?? '09:00'; ?>">
                                                                        <span class="align-self-center">to</span>
                                                                        <input type="time" class="form-control" 
                                                                               name="<?php echo $day_key; ?>_end" 
                                                                               value="<?php echo $day_data['end_time'] ?? '17:00'; ?>">
                                                                    </div>
                                                                </div>
                                                                <div class="col-md-6 mb-2">
                                                                    <label class="form-label">Break Time (Optional)</label>
                                                                    <div class="d-flex gap-2">
                                                                        <input type="time" class="form-control" 
                                                                               name="<?php echo $day_key; ?>_break_start" 
                                                                               value="<?php echo $day_data['break_start'] ?? ''; ?>">
                                                                        <span class="align-self-center">to</span>
                                                                        <input type="time" class="form-control" 
                                                                               name="<?php echo $day_key; ?>_break_end" 
                                                                               value="<?php echo $day_data['break_end'] ?? ''; ?>">
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <!-- Quick Actions -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Quick Actions</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <button type="button" class="btn btn-soft-primary" id="applyWeekdays">
                                                <i class="ri-calendar-line me-1"></i> Enable Weekdays Only
                                            </button>
                                            <button type="button" class="btn btn-soft-info" id="applyAllDays">
                                                <i class="ri-calendar-check-line me-1"></i> Enable All Days
                                            </button>
                                            <button type="button" class="btn btn-soft-warning" id="copyMonday">
                                                <i class="ri-file-copy-line me-1"></i> Copy Monday to All
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <!-- Save Button -->
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-success btn-lg">
                                                <i class="ri-save-line me-1"></i> Save Availability
                                            </button>
                                            <a href="ent_consultant_dashboard.php" class="btn btn-secondary btn-lg">
                                                <i class="ri-close-line me-1"></i> Cancel
                                            </a>
                                        </div>
                                    </div>
                                </div>

                                <!-- Info Card -->
                                <div class="card">
                                    <div class="card-body">
                                        <h6 class="card-title">Information</h6>
                                        <ul class="list-unstyled text-muted small mb-0">
                                            <li class="mb-2"><i class="ri-information-line me-1"></i> Set your weekly working hours</li>
                                            <li class="mb-2"><i class="ri-time-line me-1"></i> Break times are optional</li>
                                            <li class="mb-2"><i class="ri-calendar-event-line me-1"></i> Changes affect future appointments</li>
                                            <li><i class="ri-alert-line me-1"></i> Existing appointments remain unchanged</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        function toggleDay(day) {
            var checkbox = document.getElementById(day + '_enabled');
            var timesDiv = document.getElementById(day + '_times');
            var card = document.getElementById('card_' + day);
            
            if (checkbox.checked) {
                timesDiv.style.display = 'block';
                card.classList.add('active');
            } else {
                timesDiv.style.display = 'none';
                card.classList.remove('active');
            }
        }

        $(document).ready(function() {
            $('#applyWeekdays').on('click', function() {
                var weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
                var weekend = ['saturday', 'sunday'];
                
                weekdays.forEach(function(day) {
                    $('#' + day + '_enabled').prop('checked', true);
                    toggleDay(day);
                });
                
                weekend.forEach(function(day) {
                    $('#' + day + '_enabled').prop('checked', false);
                    toggleDay(day);
                });
                
                Swal.fire('Applied!', 'Weekdays enabled', 'success');
            });

            $('#applyAllDays').on('click', function() {
                var days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
                
                days.forEach(function(day) {
                    $('#' + day + '_enabled').prop('checked', true);
                    toggleDay(day);
                });
                
                Swal.fire('Applied!', 'All days enabled', 'success');
            });

            $('#copyMonday').on('click', function() {
                var mondayStart = $('input[name="monday_start"]').val();
                var mondayEnd = $('input[name="monday_end"]').val();
                var mondayBreakStart = $('input[name="monday_break_start"]').val();
                var mondayBreakEnd = $('input[name="monday_break_end"]').val();
                
                var days = ['tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
                
                days.forEach(function(day) {
                    $('input[name="' + day + '_start"]').val(mondayStart);
                    $('input[name="' + day + '_end"]').val(mondayEnd);
                    $('input[name="' + day + '_break_start"]').val(mondayBreakStart);
                    $('input[name="' + day + '_break_end"]').val(mondayBreakEnd);
                });
                
                Swal.fire('Copied!', 'Monday schedule copied to all days', 'success');
            });

            <?php if(isset($_SESSION['success_message'])): ?>
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: '<?php echo $_SESSION['success_message']; ?>'
                });
                <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>

            <?php if(isset($_SESSION['error_message'])): ?>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: '<?php echo $_SESSION['error_message']; ?>'
                });
                <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>
        });
    </script>
</body>
</html>