<?php
/**
 * AJAX: Check if a phone number is already registered to an adult patient (18+).
 * Used on registration form to warn before submit. Under-18 allows duplicate phones.
 */

session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'found' => false, 'error' => 'Unauthorized']);
    exit();
}

$phone_primary = trim($_POST['phone_primary'] ?? $_GET['phone_primary'] ?? '');
$date_of_birth = trim($_POST['date_of_birth'] ?? $_GET['date_of_birth'] ?? '');

$response = ['success' => true, 'found' => false, 'patient' => null];

if (empty($phone_primary) || empty($date_of_birth)) {
    echo json_encode($response);
    exit();
}

try {
    $dob_obj = new DateTime($date_of_birth);
    $age_years = $dob_obj->diff(new DateTime())->y;
    if ($age_years < 18) {
        echo json_encode($response);
        exit();
    }

    $phone_digits = preg_replace('/[^0-9]/', '', $phone_primary);
    if (strlen($phone_digits) < 8) {
        echo json_encode($response);
        exit();
    }

    $phone_variants = [$phone_primary, $phone_digits];
    if (strlen($phone_digits) === 12 && substr($phone_digits, 0, 3) === '254') {
        $phone_variants[] = '0' . substr($phone_digits, 3, 9);
    } elseif (strlen($phone_digits) === 9 && substr($phone_digits, 0, 1) === '7') {
        $phone_variants[] = '254' . $phone_digits;
        $phone_variants[] = '+254' . $phone_digits;
    }
    $placeholders = implode(',', array_fill(0, count($phone_variants), '?'));
    $sql = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary, u.date_of_birth, u.gender
            FROM patients p
            INNER JOIN users u ON p.user_id = u.user_id
            WHERE u.user_type = 'PATIENT' AND p.is_active = 1
            AND u.phone_primary IN ($placeholders)
            LIMIT 1";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $types = str_repeat('s', count($phone_variants));
        $stmt->bind_param($types, ...$phone_variants);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_assoc();
        $stmt->close();
        if ($row) {
            $response['found'] = true;
            $response['patient'] = [
                'patient_id' => (int) $row['patient_id'],
                'patient_number' => $row['patient_number'],
                'full_name' => $row['full_name'],
                'phone_primary' => $row['phone_primary'],
                'date_of_birth' => $row['date_of_birth'],
                'gender' => $row['gender'],
            ];
            echo json_encode($response);
            exit();
        }
    }

    $sql2 = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary, u.date_of_birth, u.gender
             FROM patients p
             INNER JOIN users u ON p.user_id = u.user_id
             WHERE u.user_type = 'PATIENT' AND p.is_active = 1
             AND u.phone_primary IS NOT NULL AND TRIM(u.phone_primary) != ''
             AND LENGTH(TRIM(u.phone_primary)) BETWEEN 9 AND 20";
    $res2 = $conn->query($sql2);
    if ($res2) {
        while ($row = $res2->fetch_assoc()) {
            $existing_digits = preg_replace('/[^0-9]/', '', $row['phone_primary']);
            if ($existing_digits === $phone_digits) {
                $response['found'] = true;
                $response['patient'] = [
                    'patient_id' => (int) $row['patient_id'],
                    'patient_number' => $row['patient_number'],
                    'full_name' => $row['full_name'],
                    'phone_primary' => $row['phone_primary'],
                    'date_of_birth' => $row['date_of_birth'],
                    'gender' => $row['gender'],
                ];
                break;
            }
        }
    }
} catch (Exception $e) {
    $response['success'] = false;
    $response['error'] = $e->getMessage();
}

echo json_encode($response);
