<?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;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid method']);
    exit;
}

// Check if doctor_schedule_slots table exists
$table_check = $conn->query("SHOW TABLES LIKE 'doctor_schedule_slots'");
if ($table_check->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Monthly scheduling not enabled. Run migration 010_add_doctor_schedule_slots.sql']);
    exit;
}

$action = $_POST['action'] ?? '';
$doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;

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

// Permission: doctors can only edit their own 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' => 'You can only edit your own schedule']);
        exit;
    }
}

function validateTime($t) {
    return preg_match('/^\d{1,2}:\d{2}$/', $t) || preg_match('/^\d{1,2}:\d{2}:\d{2}$/', $t);
}

try {
    switch ($action) {
        case 'save_slot':
            $date = $_POST['schedule_date'] ?? '';
            $start = trim($_POST['start_time'] ?? '');
            $end = trim($_POST['end_time'] ?? '');
            $location_type = $_POST['location_type'] ?? 'internal';
            $facility_name = trim($_POST['facility_name'] ?? '');
            $facility_address = trim($_POST['facility_address'] ?? '');
            $facility_contact = trim($_POST['facility_contact'] ?? '');

            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                throw new Exception('Invalid date format');
            }
            if (!$start || !$end || !validateTime($start) || !validateTime($end)) {
                throw new Exception('Valid start and end times required');
            }
            if ($location_type !== 'internal' && $location_type !== 'external') {
                $location_type = 'internal';
            }
            if ($location_type === 'external' && !$facility_name) {
                throw new Exception('Facility name required for external sessions');
            }

            if (strlen($start) === 5) $start .= ':00';
            if (strlen($end) === 5) $end .= ':00';
            if (strtotime($end) <= strtotime($start)) {
                throw new Exception('End time must be after start time');
            }

            $slot_id = isset($_POST['slot_id']) ? (int)$_POST['slot_id'] : 0;
            $facility_name = $location_type === 'external' ? $facility_name : null;
            $facility_address = $location_type === 'external' ? $facility_address : null;
            $facility_contact = $location_type === 'external' ? $facility_contact : null;

            if ($slot_id > 0) {
                $sql = "UPDATE doctor_schedule_slots SET start_time=?, end_time=?, location_type=?, facility_name=?, facility_address=?, facility_contact=? WHERE slot_id=? AND doctor_id=?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('ssssssii', $start, $end, $location_type, $facility_name, $facility_address, $facility_contact, $slot_id, $doctor_id);
            } else {
                $sql = "INSERT INTO doctor_schedule_slots (doctor_id, schedule_date, start_time, end_time, location_type, facility_name, facility_address, facility_contact) VALUES (?,?,?,?,?,?,?,?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('isssssss', $doctor_id, $date, $start, $end, $location_type, $facility_name, $facility_address, $facility_contact);
            }
            $stmt->execute();
            $new_id = $slot_id > 0 ? $slot_id : $conn->insert_id;
            $conn->close();
            echo json_encode(['success' => true, 'message' => 'Slot saved', 'slot_id' => $new_id]);
            break;

        case 'delete_slot':
            $slot_id = (int)($_POST['slot_id'] ?? 0);
            if ($slot_id <= 0) {
                throw new Exception('Invalid slot ID');
            }
            $sql = "DELETE FROM doctor_schedule_slots WHERE slot_id=? AND doctor_id=?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ii', $slot_id, $doctor_id);
            $stmt->execute();
            $conn->close();
            echo json_encode(['success' => true, 'message' => 'Slot removed']);
            break;

        case 'fill_month_from_template':
            $year = (int)($_POST['year'] ?? date('Y'));
            $month = (int)($_POST['month'] ?? date('n'));
            $start_date = sprintf('%04d-%02d-01', $year, $month);
            $end_date = date('Y-m-t', strtotime($start_date));

            // Remove existing slots for this month (replace, not append)
            $del_sql = "DELETE FROM doctor_schedule_slots WHERE doctor_id = ? AND schedule_date >= ? AND schedule_date <= ?";
            $del_stmt = $conn->prepare($del_sql);
            $del_stmt->bind_param('iss', $doctor_id, $start_date, $end_date);
            $del_stmt->execute();

            $doctor_sql = "SELECT availability_schedule FROM doctors WHERE doctor_id = ?";
            $stmt = $conn->prepare($doctor_sql);
            $stmt->bind_param('i', $doctor_id);
            $stmt->execute();
            $dr = $stmt->get_result()->fetch_assoc();
            if (!$dr || empty($dr['availability_schedule'])) {
                throw new Exception('No weekly template to copy from');
            }
            $schedule = json_decode($dr['availability_schedule'], true);
            if (!is_array($schedule)) {
                throw new Exception('Invalid weekly schedule format');
            }

            $days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
            $inserted = 0;
            $current = strtotime($start_date);
            $end_ts = strtotime($end_date);

            $ins_sql = "INSERT INTO doctor_schedule_slots (doctor_id, schedule_date, start_time, end_time, location_type, facility_name, facility_address, facility_contact) VALUES (?,?,?,?,?,?,?,?)";
            $ins_stmt = $conn->prepare($ins_sql);

            while ($current <= $end_ts) {
                $date_str = date('Y-m-d', $current);
                $day_name = strtolower(date('l', $current));
                if (isset($schedule[$day_name]['sessions']) && !empty($schedule[$day_name]['sessions'])) {
                    foreach ($schedule[$day_name]['sessions'] as $s) {
                        $start = $s['start'] ?? '';
                        $end = $s['end'] ?? '';
                        $loc = $s['location_type'] ?? 'internal';
                        $fn = ($loc === 'external') ? ($s['facility_name'] ?? '') : null;
                        $fa = ($loc === 'external') ? ($s['facility_address'] ?? '') : null;
                        $fc = ($loc === 'external') ? ($s['facility_contact'] ?? '') : null;
                        if (strlen($start) === 5) $start .= ':00';
                        if (strlen($end) === 5) $end .= ':00';
                        $ins_stmt->bind_param('isssssss', $doctor_id, $date_str, $start, $end, $loc, $fn, $fa, $fc);
                        $ins_stmt->execute();
                        $inserted++;
                    }
                }
                $current = strtotime('+1 day', $current);
            }
            $conn->close();
            echo json_encode(['success' => true, 'message' => "Added $inserted slots from weekly template", 'inserted' => $inserted]);
            break;

        case 'copy_week':
            $from_date = $_POST['from_date'] ?? '';
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from_date)) {
                throw new Exception('Invalid from date');
            }
            $days_to_copy = (int)($_POST['days'] ?? 7);
            if ($days_to_copy < 1 || $days_to_copy > 14) $days_to_copy = 7;

            $sql = "SELECT 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 < DATE_ADD(?, INTERVAL ? DAY)
                    ORDER BY schedule_date, start_time";
            $stmt = $conn->prepare($sql);
            $end_from = date('Y-m-d', strtotime($from_date . " +{$days_to_copy} days"));
            $stmt->bind_param('issi', $doctor_id, $from_date, $from_date, $days_to_copy);
            $stmt->execute();
            $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            $to_start = $_POST['to_start_date'] ?? date('Y-m-d', strtotime($from_date . " +7 days"));
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to_start)) {
                $to_start = date('Y-m-d', strtotime($from_date . " +7 days"));
            }

            $inserted = 0;
            $ins_sql = "INSERT INTO doctor_schedule_slots (doctor_id, schedule_date, start_time, end_time, location_type, facility_name, facility_address, facility_contact) VALUES (?,?,?,?,?,?,?,?)";
            $ins_stmt = $conn->prepare($ins_sql);
            $from_ts = strtotime($from_date);
            $to_ts = strtotime($to_start);
            $offset_days = ($to_ts - $from_ts) / 86400;

            $by_date = [];
            foreach ($rows as $r) {
                $by_date[$r['schedule_date']][] = $r;
            }
            foreach ($by_date as $orig_date => $slots) {
                $new_date = date('Y-m-d', strtotime($orig_date . " +{$offset_days} days"));
                foreach ($slots as $s) {
                    $ins_stmt->bind_param('isssssss', $doctor_id, $new_date, $s['start_time'], $s['end_time'], $s['location_type'], $s['facility_name'], $s['facility_address'], $s['facility_contact']);
                    $ins_stmt->execute();
                    $inserted++;
                }
            }
            $conn->close();
            echo json_encode(['success' => true, 'message' => "Copied $inserted slots", 'inserted' => $inserted]);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    if (isset($conn)) $conn->close();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
