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

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

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

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

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

$rota_id = isset($_POST['rota_id']) ? (int)$_POST['rota_id'] : 0;
$rota_date = isset($_POST['rota_date']) ? trim($_POST['rota_date']) : '';
$doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
$start_time = isset($_POST['start_time']) ? trim($_POST['start_time']) : '';
$end_time = isset($_POST['end_time']) ? trim($_POST['end_time']) : '';
$assignment = isset($_POST['assignment']) ? trim($_POST['assignment']) : '';
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $rota_date) || $doctor_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid date or doctor']);
    exit;
}

// Doctors can edit only their own row unless they are admin
$admin_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $admin_roles)) {
    $self = $conn->query("SELECT doctor_id FROM doctors WHERE user_id = " . (int)$_SESSION['user_id']);
    if ($self && $row = $self->fetch_assoc()) {
        if ((int)$row['doctor_id'] !== $doctor_id) {
            echo json_encode(['success' => false, 'message' => 'You can only edit your own rota']);
            exit;
        }
    }
}

// Normalize times to HH:MM or HH:MM:SS for TIME column; empty string = NULL
$start_sql = null;
$end_sql = null;
if ($start_time !== '') {
    if (preg_match('/^\d{1,2}(:\d{2})?(\s*(am|pm))?$/i', $start_time)) {
        $t = date('H:i:s', strtotime($start_time));
        if ($t) $start_sql = $t;
    } elseif (preg_match('/^\d{2}:\d{2}(:\d{2})?$/', $start_time)) {
        $start_sql = $start_time;
    }
}
if ($end_time !== '') {
    if (preg_match('/^\d{1,2}(:\d{2})?(\s*(am|pm))?$/i', $end_time)) {
        $t = date('H:i:s', strtotime($end_time));
        if ($t) $end_sql = $t;
    } elseif (preg_match('/^\d{2}:\d{2}(:\d{2})?$/', $end_time)) {
        $end_sql = $end_time;
    }
}

$assignment = mb_substr($assignment, 0, 100);
$notes = mb_substr($notes, 0, 2000);

$has_notes = false;
$chk_notes = @$conn->query("SHOW COLUMNS FROM doctor_rota LIKE 'notes'");
if ($chk_notes && $chk_notes->num_rows > 0) $has_notes = true;

// Check if doctor_rota has start_time/end_time (migration 019)
$cols = @$conn->query("SHOW COLUMNS FROM doctor_rota LIKE 'start_time'");
$has_times = $cols && $cols->num_rows > 0;

try {
    if ($has_times) {
        if ($rota_id > 0) {
            if ($has_notes) {
                $stmt = $conn->prepare("UPDATE doctor_rota SET assignment = ?, start_time = ?, end_time = ?, notes = ?, updated_at = NOW() WHERE rota_id = ? AND doctor_id = ?");
                $stmt->bind_param('ssssii', $assignment, $start_sql, $end_sql, $notes, $rota_id, $doctor_id);
            } else {
                $stmt = $conn->prepare("UPDATE doctor_rota SET assignment = ?, start_time = ?, end_time = ?, updated_at = NOW() WHERE rota_id = ? AND doctor_id = ?");
                $stmt->bind_param('sssii', $assignment, $start_sql, $end_sql, $rota_id, $doctor_id);
            }
            $stmt->execute();
            if ($stmt->affected_rows === 0) {
                throw new Exception('Slot not found or access denied');
            }
        } else {
            if ($has_notes) {
                $stmt = $conn->prepare("INSERT INTO doctor_rota (rota_date, doctor_id, assignment, start_time, end_time, notes) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->bind_param('sissss', $rota_date, $doctor_id, $assignment, $start_sql, $end_sql, $notes);
            } else {
                $stmt = $conn->prepare("INSERT INTO doctor_rota (rota_date, doctor_id, assignment, start_time, end_time) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param('sisss', $rota_date, $doctor_id, $assignment, $start_sql, $end_sql);
            }
            $stmt->execute();
        }
    } else {
        $display = $assignment;
        if ($start_time !== '' || $end_time !== '') {
            $display = trim($start_time . ' - ' . $end_time);
            if ($assignment !== '') $display .= ' ' . $assignment;
        }
        $display = mb_substr($display, 0, 100);
        if ($rota_id > 0) {
            $stmt = $conn->prepare("UPDATE doctor_rota SET assignment = ?, updated_at = NOW() WHERE rota_id = ? AND doctor_id = ?");
            $stmt->bind_param('sii', $display, $rota_id, $doctor_id);
            $stmt->execute();
        } else {
            $stmt = $conn->prepare("INSERT INTO doctor_rota (rota_date, doctor_id, assignment) VALUES (?, ?, ?)");
            $stmt->bind_param('sis', $rota_date, $doctor_id, $display);
            $stmt->execute();
        }
    }
    $new_id = $rota_id > 0 ? $rota_id : $conn->insert_id;
    echo json_encode(['success' => true, 'message' => 'Saved', 'rota_id' => (int)$new_id]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
