<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../helpers.php';

header('Content-Type: application/json');

$db = db();
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

if ($method === 'GET') {
    $doctor_id = $_GET['doctor_id'] ?? null;
    if (!$doctor_id) {
        echo json_encode(['success' => false, 'error' => 'Missing doctor_id']);
        exit;
    }

    $stmt = $db->prepare("SELECT * FROM doctor_holidays WHERE doctor_id = ? ORDER BY start_date DESC");
    $stmt->execute([$doctor_id]);
    $holidays = $stmt->fetchAll();

    echo json_encode(['success' => true, 'holidays' => $holidays]);
    exit;
}

if ($method === 'POST') {
    $action = $input['action'] ?? '';

    if ($action === 'create') {
        $doctor_id = $input['doctor_id'] ?? null;
        $start_date = $input['start_date'] ?? null;
        $end_date = $input['end_date'] ?? null;
        $note = $input['note'] ?? '';

        if ($doctor_id && $start_date && $end_date) {
            $stmt = $db->prepare("INSERT INTO doctor_holidays (doctor_id, start_date, end_date, note) VALUES (?, ?, ?, ?)");
            $stmt->execute([$doctor_id, $start_date, $end_date, $note]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Missing fields']);
        }
    } elseif ($action === 'delete') {
        $id = $input['id'] ?? null;
        if ($id) {
            $stmt = $db->prepare("DELETE FROM doctor_holidays WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Missing ID']);
        }
    }
    exit;
}
