<?php
session_start();
require_once dirname(__DIR__, 2) . '/includes/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['patient_no'])) {
    echo json_encode(['status' => 'error', 'message' => 'Valid Patient Number required.']);
    exit();
}

$patient_no = $conn->real_escape_string($_POST['patient_no']);

// Generate a unique Appointment Number
$apt_no = "APT-" . date('Ymd') . "-" . rand(1000, 9999);
$visit_date = date('Y-m-d');
$visit_time = date('H:i:s');
$staff_id = $_SESSION['staff_id'] ?? 1; // Fallback to 1 if session expired

// Insert into visit_master explicitly as 'Diagnostic'
$stmt = $conn->prepare("INSERT INTO visit_master 
    (appointment_no, patient_no, primary_doctor_id, visit_date, visit_time, payment_category, nhis_service_type, status, attendance_type) 
    VALUES (?, ?, ?, ?, ?, 'Cash', 'Diagnostic', 'In Progress', 'EAE')");

$stmt->bind_param("ssiss", $apt_no, $patient_no, $staff_id, $visit_date, $visit_time);

if ($stmt->execute()) {
    $new_visit_id = $stmt->insert_id;
    echo json_encode(['status' => 'success', 'visit_id' => $new_visit_id]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to create visit: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
?>