<?php
session_start();
header('Content-Type: application/json');
require_once '../layouts/dbconn.php';
require_once '../layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Forbidden']);
    exit;
}

$doctor_id = isset($_GET['doctor_id']) ? (int)$_GET['doctor_id'] : 0;
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('n');

if (!$doctor_id) {
    echo json_encode(['success' => false, 'message' => 'Doctor ID required']);
    exit;
}

// Doctors can only view their own slots unless admin
if (!in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])) {
    $check_sql = "SELECT user_id FROM doctors WHERE doctor_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param('i', $doctor_id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    if (!$row || $row['user_id'] != $_SESSION['user_id']) {
        echo json_encode(['success' => false, 'message' => 'Forbidden']);
        exit;
    }
}

// Check if doctor_schedule_slots table exists (migration may not have run)
$table_check = $conn->query("SHOW TABLES LIKE 'doctor_schedule_slots'");
if ($table_check->num_rows === 0) {
    echo json_encode([
        'success' => true,
        'dates_with_slots' => [],
        'slots_by_date' => [],
        'message' => 'Run migration 010_add_doctor_schedule_slots.sql to enable monthly scheduling'
    ]);
    exit;
}

$start_date = sprintf('%04d-%02d-01', $year, $month);
$end_date = date('Y-m-t', strtotime($start_date));

$sql = "SELECT slot_id, doctor_id, schedule_date, start_time, end_time, location_type,
               facility_name, facility_address, facility_contact
        FROM doctor_schedule_slots
        WHERE doctor_id = ? AND schedule_date >= ? AND schedule_date <= ?
        ORDER BY schedule_date ASC, start_time ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iss', $doctor_id, $start_date, $end_date);
$stmt->execute();
$result = $stmt->get_result();

$slots_by_date = [];
$dates_with_slots = [];

while ($row = $result->fetch_assoc()) {
    $date = $row['schedule_date'];
    if (!isset($slots_by_date[$date])) {
        $slots_by_date[$date] = [];
        $dates_with_slots[] = $date;
    }
    $row['start_time'] = substr($row['start_time'], 0, 5);
    $row['end_time'] = substr($row['end_time'], 0, 5);
    $slots_by_date[$date][] = $row;
}

$conn->close();

echo json_encode([
    'success' => true,
    'year' => $year,
    'month' => $month,
    'dates_with_slots' => $dates_with_slots,
    'slots_by_date' => $slots_by_date
]);
