<?php
// lookup_contact.php

// Database connection (adjust with your actual credentials)
$host = 'localhost';
$db   = 'havenclean_Jonathan';
$user = 'havenclean_Jonathan';
$pass = 'Baseline77@!';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

if (!isset($_GET['number'])) {
    http_response_code(400);
    echo json_encode(['error' => 'No number provided']);
    exit;
}

$phone = trim($_GET['number']);

// Optional: Clean/normalize phone number (remove spaces, dashes, etc.)
$phone_clean = preg_replace('/[^0-9+]/', '', $phone);

$stmt = $pdo->prepare("SELECT name FROM Contact WHERE from_number = ? OR to_number = ? LIMIT 1");
$stmt->execute([$phone_clean, $phone_clean]);
$result = $stmt->fetch();

header('Content-Type: application/json');

if ($result && !empty($result['name'])) {
    echo json_encode(['name' => trim($result['name'])]);
} else {
    echo json_encode(['name' => null, 'number' => $phone]); // fallback to number
}
?>