<?php
header('Content-Type: application/json');
session_start();

// Quick JSON responder
function respond($success, $message = '', $extra = []) {
    echo json_encode(array_merge(['success' => $success, 'message' => $message], $extra));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(false, 'Invalid request method.');
}

require_once 'db.php';

try {
    // 🔍 Check if userID already exists
    if (!empty($_POST['userID'])) {
        $stmt = $pdo->prepare("SELECT 1 FROM users WHERE userID = :userID");
        $stmt->execute([':userID' => $_POST['userID']]);
        if ($stmt->fetch()) {
            respond(false, 'User ID already exists.');
        }
    }

    // 🔍 Check if email already exists
    $stmt = $pdo->prepare("SELECT 1 FROM users WHERE email = :email");
    $stmt->execute([':email' => $_POST['email']]);
    if ($stmt->fetch()) {
        respond(false, 'Email already exists.');
    }

    $pdo->beginTransaction();

    // 1. Insert into users table
    $stmt = $pdo->prepare("
        INSERT INTO users (userID, email, password, name, phone, address, created_at, user_type, is_verified, is_approved)
        VALUES (:userid, :email, :password, :name, :phone, :address, NOW(), 'Patient', 0, 0)
    ");
    $stmt->execute([
        ':userid'    => $_POST['userID'],
        ':email'     => $_POST['email'],
        ':password'  => password_hash($_POST['password'], PASSWORD_BCRYPT),
        ':name'      => $_POST['name'],
        ':phone'     => $_POST['phone'],
        ':address'   => $_POST['address']
    ]);

    $user_id = $pdo->lastInsertId();

    // 2. Insert into patients table
    $stmt = $pdo->prepare("
        INSERT INTO patients 
            (userID, phone2, dob, gender, nationality, state_of_origin, lga, religion, blood_group, genotype, adverse_reactions,
             nok_name, nok_relationship, nok_phone, nok_phone2, nok_address)
        VALUES
            (:userID, :phone2, :dob, :gender, :nationality, :state_of_origin, :lga, :religion, :blood_group, :genotype, :adverse_reactions,
             :nok_name, :nok_relationship, :nok_phone1, :nok_phone2, :nok_address)
    ");
    $stmt->execute([
        ':userID'           => $_POST['userID'],
        ':phone2'           => $_POST['phone2'],
        ':dob'              => $_POST['dob'],
        ':gender'           => $_POST['gender'],
        ':nationality'      => $_POST['nationality'],
        ':state_of_origin'  => $_POST['state'],
        ':lga'              => $_POST['lga'],
        ':religion'         => $_POST['religion'],
        ':blood_group'      => $_POST['blood_group'],
        ':genotype'         => $_POST['genotype'],
        ':adverse_reactions'=> $_POST['adverse_reactions'],
        ':nok_name'         => $_POST['nok_name'],
        ':nok_relationship' => $_POST['nok_relationship'],
        ':nok_phone1'       => $_POST['nok_phone'],
        ':nok_phone2'       => $_POST['nok_phone2'],
        ':nok_address'      => $_POST['nok_address']
    ]);

    $patient_id = $pdo->lastInsertId();

    // 3. Insert into audit_log table
    $stmt = $pdo->prepare("
        INSERT INTO audit_log
            (user_id, user_email, action_type, table_name, record_id, old_data, new_data, ip_address, user_agent, performed_at, ref_id, system_tag)
        VALUES
            (:user_id, :user_email, :action_type, :table_name, :record_id, :old_data, :new_data, :ip_address, :user_agent, NOW(), :ref_id, :system_tag)
    ");
    $stmt->execute([
        ':user_id'    => $_SESSION['userID'] ?? $user_id,
        ':user_email' => $_SESSION['email'] ?? $_POST['email'],
        ':action_type'=> 'INSERT',
        ':table_name' => 'patients',
        ':record_id'  => $patient_id,
        ':old_data'   => null,
        ':new_data'   => json_encode($_POST),
        ':ip_address' => $_SERVER['REMOTE_ADDR'],
        ':user_agent' => $_SERVER['HTTP_USER_AGENT'],
        ':ref_id'     => uniqid('audit_', true),
        ':system_tag' => 'patient_registration'
    ]);

    $pdo->commit();

    respond(true, 'Patient registered successfully.');

} catch (Exception $e) {
    $pdo->rollBack();
    respond(false, 'Error saving patient: ' . $e->getMessage());
}