<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include_once('includes/db.php'); // Make sure $pdo is correctly initialized

// === TEST VARIABLES ===
$patient_id = 1; // <-- replace with an actual patient_id from your 'visits' table
$catchment_area = 'Zone';
$new_case = 'Yes';
$systolic = 120;
$diastolic = 80;
$heart_rate = 70;
$temperature = 36.6;
$resp_rate = 16;
$spo2 = 98;
$weight = 70;
$height = 170;
$vital_comment = 'Test comment';
$chief_complaints = 'Test complaints';

try {
    $pdo->beginTransaction();

    // Get next visit number
    $stmt = $pdo->prepare("SELECT MAX(visit_number) AS max_number FROM visit_tickets WHERE patient_id = ?");
    $stmt->execute([$patient_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $visit_number = ($row && $row['max_number']) ? $row['max_number'] + 1 : 1;

    // Insert into visit_tickets
    $stmt = $pdo->prepare("
        INSERT INTO visit_tickets
        (patient_id, visit_number, catchment_area, new_case, systolic, diastolic, heart_rate,
         temperature, resp_rate, spo2, weight, height, vital_comment, chief_complaints, visit_date)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
        $patient_id, $visit_number, $catchment_area, $new_case,
        $systolic, $diastolic, $heart_rate, $temperature,
        $resp_rate, $spo2, $weight, $height,
        $vital_comment, $chief_complaints
    ]);

    $pdo->commit();

    echo "✅ Insert successful! Visit number: $visit_number";

} catch (PDOException $e) {
    $pdo->rollBack();
    echo "❌ Error inserting ticket: " . $e->getMessage();
}
