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

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';
require_once __DIR__ . '/../../helpers/jwt_helper.php';

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

$data = json_decode(file_get_contents("php://input"), true);

$email = trim($data['email'] ?? '');
$phone = trim($data['phone'] ?? '');

if ($email === '' && $phone === '') {
    sendResponse(422, "Email or phone number is required.");
}

if ($email !== '') {

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendResponse(422, "Invalid email format.");
    }

    $field = 'email';
    $value = $email;

} else {

    if (!preg_match('/^\+[1-9]\d{7,14}$/', $phone)) {
        sendResponse(422, "Phone number must be 7-14 digits.");
    }

    $field = 'phone';
    $value = $phone;
}

try {
    $stmt = $conn->prepare("
        SELECT id
        FROM users
        WHERE $field = ?
        LIMIT 1
    ");
    $stmt->execute([$value]);

    if ($stmt->rowCount() > 0) {
        sendResponse(200, "User exists.", [
            'is_exists' => true
        ]);
    } else {
        sendResponse(200, "User does not exist.", [
            'is_exists' => false
        ]);
    }

} catch (PDOException $e) {
    sendResponse(500, "Database error.");
}
