<?php

declare(strict_types=1);
require dirname(__DIR__) . '/app/bootstrap.php';
header('Content-Type: application/json; charset=utf-8');

try {
    verify_csrf();
    $branchId=(int)($_POST['branch_id']??public_request_branch_id()??0);
    if($branchId<1)throw new RuntimeException('Select a valid clinic branch.');

    $patientNo=trim((string)($_POST['patient_no']??''));
    $first=trim((string)($_POST['first_name']??''));
    $last=trim((string)($_POST['last_name']??''));
    $birth=trim((string)($_POST['birth_date']??''));
    $mobile=trim((string)($_POST['mobile']??''));
    $email=trim((string)($_POST['email']??''));
    $patientId=0;

    if($patientNo!==''&&preg_match('/^\d{4}-\d{2}-\d{2}$/',$birth)){
        $stmt=db()->prepare('SELECT id FROM `' . table('patients') . '` WHERE branch_id=? AND patient_no=? AND birth_date=? AND deleted_at IS NULL LIMIT 1');
        $stmt->execute([$branchId,$patientNo,$birth]);
        $patientId=(int)($stmt->fetchColumn()?:0);
    }
    if($patientId<1&&$first!==''&&$last!==''&&preg_match('/^\d{4}-\d{2}-\d{2}$/',$birth)&&($mobile!==''||$email!=='')){
        $stmt=db()->prepare(
            'SELECT id FROM `' . table('patients') . '` WHERE branch_id=? AND LOWER(first_name)=LOWER(?) AND LOWER(last_name)=LOWER(?) AND birth_date=? AND deleted_at IS NULL '
            . 'AND (mobile=? OR (? <> "" AND email=?)) LIMIT 1'
        );
        $stmt->execute([$branchId,$first,$last,$birth,$mobile,$email,$email]);
        $patientId=(int)($stmt->fetchColumn()?:0);
    }

    if($patientId<1){
        echo json_encode([
            'ok'=>true,
            'matched'=>false,
            'patient_id'=>0,
            'doctor_id'=>0,
            'doctor_name'=>'',
            'locked'=>false,
            'message'=>'No exact returning-patient match yet. Staff will verify the record before confirmation.',
        ],JSON_UNESCAPED_SLASHES);
        exit;
    }

    $primary=patient_primary_dentist($patientId);
    if(!$primary){
        echo json_encode([
            'ok'=>true,
            'matched'=>true,
            'patient_id'=>$patientId,
            'doctor_id'=>0,
            'doctor_name'=>'',
            'locked'=>false,
            'message'=>'Patient record found. No established dentist is locked, so staff can assign the appropriate available provider.',
        ],JSON_UNESCAPED_SLASHES);
        exit;
    }

    $doctorId=(int)$primary['id'];
    $binding=doctor_chair_binding($doctorId,$branchId);
    $locked=empty($binding['valid']);
    $message=$locked
        ? 'Patient record found, but the established dentist does not currently have a valid chair assignment at this branch. Choose Let the dental clinic decide or contact the clinic.'
        : 'Patient record found. Available dates and times are filtered to the established dentist unless you choose Let the dental clinic decide.';

    echo json_encode([
        'ok'=>true,
        'matched'=>true,
        'patient_id'=>$patientId,
        'doctor_id'=>$doctorId,
        'doctor_name'=>(string)($primary['name']??''),
        'locked'=>$locked,
        'message'=>$message,
    ],JSON_UNESCAPED_SLASHES);
} catch (Throwable $exception) {
    http_response_code(422);
    echo json_encode(['ok'=>false,'message'=>$exception->getMessage()],JSON_UNESCAPED_SLASHES);
}
