<?php
// public/check_phone_debug.php
require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../includes/helpers.php';

header('Content-Type: application/json; charset=utf-8');

$phone_raw = $_GET['phone'] ?? '';
$phone = preg_replace('/[^0-9]/', '', $phone_raw);

if (strlen($phone) !== 10) {
  echo json_encode([
    'ok' => true,
    'note' => 'phone must be 10 digits',
    'phone_received' => $phone_raw,
    'phone_normalized' => $phone,
    'count' => 0,
    'rows' => []
  ]);
  exit;
}

try {
  // count matching rows
  $stmt = $pdo->prepare('SELECT COUNT(*) AS cnt FROM residents WHERE phone = :phone');
  $stmt->execute(['phone' => $phone]);
  $cnt = (int)$stmt->fetchColumn();

  // also fetch any matching rows (for debugging)
  $stmt2 = $pdo->prepare('SELECT id, ward, house_no, name, phone, created_at FROM residents WHERE phone = :phone LIMIT 10');
  $stmt2->execute(['phone' => $phone]);
  $rows = $stmt2->fetchAll(PDO::FETCH_ASSOC);

  echo json_encode([
    'ok' => true,
    'phone_checked' => $phone,
    'count' => $cnt,
    'rows' => $rows
  ]);
} catch (Exception $e) {
  echo json_encode([
    'ok' => false,
    'error' => $e->getMessage()
  ]);
}
