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

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

// Check if user is a doctor
$user_id = $_SESSION['user_id'];
$doc_sql = "SELECT * FROM doctors WHERE user_id = ?";
$stmt = $conn->prepare($doc_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$doctor = $stmt->get_result()->fetch_assoc();

if (!$doctor) {
    $_SESSION['error'] = "Access denied. Only doctors can set availability.";
    header('Location: dashboard.php');
    exit();
}

$doctor_id = $doctor['doctor_id'];
$schedule = json_decode($doctor['availability_schedule'] ?? '[]', true);
$days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_schedule = [];
    
    foreach ($days as $day) {
        $is_avail = isset($_POST['available'][$day]) ? true : false;
        $slots = [];
        
        if ($is_avail && isset($_POST['start'][$day])) {
            $starts = $_POST['start'][$day];
            $ends = $_POST['end'][$day];
            
            for ($i = 0; $i < count($starts); $i++) {
                if (!empty($starts[$i]) && !empty($ends[$i])) {
                    $slots[] = ['start' => $starts[$i], 'end' => $ends[$i]];
                }
            }
        }
        
        $new_schedule[$day] = [
            'available' => $is_avail,
            'slots' => $slots
        ];
    }
    
    $json_schedule = json_encode($new_schedule);
    $upd = $conn->prepare("UPDATE doctors SET availability_schedule = ? WHERE doctor_id = ?");
    $upd->bind_param("si", $json_schedule, $doctor_id);
    
    if ($upd->execute()) {
        $_SESSION['success'] = "Availability updated successfully.";
        $schedule = $new_schedule; // Refresh
    } else {
        $_SESSION['error'] = "Failed to update availability.";
    }
}
?>
<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Set Availability')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>
<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                   <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 Schedule & Availability</h4>
                            </div>
                        </div>
                    </div>

                    <?php if(isset($_SESSION['success'])): ?>
                        <div class="alert alert-success"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
                    <?php endif; ?>
                    <?php if(isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Weekly Schedule Settings</h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST">
                                        <div class="accordion" id="scheduleAccordion">
                                            <?php foreach ($days as $index => $day): 
                                                $day_data = $schedule[$day] ?? ['available' => false, 'slots' => []];
                                            ?>
                                            <div class="accordion-item">
                                                <h2 class="accordion-header" id="heading<?php echo $day; ?>">
                                                    <button class="accordion-button <?php echo $index > 0 ? 'collapsed' : ''; ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?php echo $day; ?>">
                                                        <?php echo ucfirst($day); ?>
                                                        <span class="ms-2 badge <?php echo $day_data['available'] ? 'bg-success' : 'bg-secondary'; ?>">
                                                            <?php echo $day_data['available'] ? 'Available' : 'Off'; ?>
                                                        </span>
                                                    </button>
                                                </h2>
                                                <div id="collapse<?php echo $day; ?>" class="accordion-collapse collapse <?php echo $index === 0 ? 'show' : ''; ?>" data-bs-parent="#scheduleAccordion">
                                                    <div class="accordion-body">
                                                        <div class="form-check form-switch mb-3">
                                                            <input class="form-check-input" type="checkbox" name="available[<?php echo $day; ?>]" id="avail_<?php echo $day; ?>" value="1" <?php echo $day_data['available'] ? 'checked' : ''; ?> onchange="toggleSlots('<?php echo $day; ?>')">
                                                            <label class="form-check-label" for="avail_<?php echo $day; ?>">I am available on <?php echo ucfirst($day); ?></label>
                                                        </div>
                                                        
                                                        <div id="slots_<?php echo $day; ?>" style="display: <?php echo $day_data['available'] ? 'block' : 'none'; ?>;">
                                                            <h6>Time Slots</h6>
                                                            <div id="slot_container_<?php echo $day; ?>">
                                                                <?php 
                                                                $slots = $day_data['slots'] ?? [];
                                                                if (empty($slots)) {
                                                                     // Default slot
                                                                     $slots[] = ['start' => '09:00', 'end' => '17:00'];
                                                                }
                                                                foreach($slots as $slot):
                                                                ?>
                                                                <div class="row mb-2 slot-row">
                                                                    <div class="col-md-3">
                                                                        <input type="time" name="start[<?php echo $day; ?>][]" class="form-control" value="<?php echo $slot['start']; ?>">
                                                                    </div>
                                                                    <div class="col-md-auto align-self-center">to</div>
                                                                    <div class="col-md-3">
                                                                        <input type="time" name="end[<?php echo $day; ?>][]" class="form-control" value="<?php echo $slot['end']; ?>">
                                                                    </div>
                                                                    <div class="col-md-2">
                                                                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeSlot(this)"><i class="ri-delete-bin-line"></i></button>
                                                                    </div>
                                                                </div>
                                                                <?php endforeach; ?>
                                                            </div>
                                                            <button type="button" class="btn btn-outline-primary btn-sm mt-2" onclick="addSlot('<?php echo $day; ?>')">+ Add Slot</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endforeach; ?>
                                        </div>
                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">Save Schedule</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        function toggleSlots(day) {
            var checked = document.getElementById('avail_' + day).checked;
            document.getElementById('slots_' + day).style.display = checked ? 'block' : 'none';
        }

        function addSlot(day) {
            var container = document.getElementById('slot_container_' + day);
            var div = document.createElement('div');
            div.className = 'row mb-2 slot-row';
            div.innerHTML = `
                <div class="col-md-3">
                    <input type="time" name="start[${day}][]" class="form-control">
                </div>
                <div class="col-md-auto align-self-center">to</div>
                <div class="col-md-3">
                    <input type="time" name="end[${day}][]" class="form-control">
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeSlot(this)"><i class="ri-delete-bin-line"></i></button>
                </div>
            `;
            container.appendChild(div);
        }

        function removeSlot(btn) {
            btn.closest('.slot-row').remove();
        }
    </script>
</body>
</html>
