<?php

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

require_once __DIR__ . "/../../config/database.php";

$db = new Database();
$pdo = $db->connect();

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

if (!$data) {
    echo json_encode([
        "success" => false,
        "message" => "Invalid request"
    ]);
    exit;
}

$email = trim($data["email"] ?? "");
$otp   = trim($data["otp"] ?? "");

if ($email == "" || $otp == "") {
    echo json_encode([
        "success" => false,
        "message" => "Email and OTP are required."
    ]);
    exit;
}

$stmt = $pdo->prepare("
SELECT
    id,
    verification_code,
    verification_expires,
    phone_verified,
    account_status
FROM printer_agents
WHERE email = ?
LIMIT 1
");

$stmt->execute([$email]);

$agent = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$agent) {
    echo json_encode([
        "success" => false,
        "message" => "Account not found."
    ]);
    exit;
}

if ($agent["phone_verified"] == 1) {

    echo json_encode([
        "success" => true,
        "message" => "Phone already verified."
    ]);

    exit;
}

if ($agent["verification_code"] != $otp) {

    echo json_encode([
        "success" => false,
        "message" => "Invalid verification code."
    ]);

    exit;
}

if (strtotime($agent["verification_expires"]) < time()) {

    echo json_encode([
        "success" => false,
        "message" => "Verification code expired."
    ]);

    exit;
}

$update = $pdo->prepare("
UPDATE printer_agents
SET
    phone_verified = 1,
    verification_code = NULL,
    verification_expires = NULL,
    account_status = 'ACTIVE'
WHERE id = ?
");

$update->execute([
    $agent["id"]
]);

echo json_encode([

    "success" => true,

    "message" => "Phone verified successfully.",

    "data" => [

        "agent_id" => $agent["id"],

        "phone_verified" => true,

        "account_status" => "ACTIVE"

    ]

]);