<?php

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

require_once __DIR__ . "/../../config/database.php";
require_once __DIR__ . "/../../classes/OTPService.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 JSON request"
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| INPUTS
|--------------------------------------------------------------------------
*/

$owner        = trim($data["owner_name"] ?? "");
$business     = trim($data["business_name"] ?? "");
$email        = strtolower(trim($data["email"] ?? ""));
$phone        = preg_replace('/\D/', '', $data["phone"] ?? "");
$payoutPhone  = preg_replace('/\D/', '', $data["payout_phone"] ?? "");
$password     = $data["password"] ?? "";
$computerName = trim($data["computer_name"] ?? "");

/*
|--------------------------------------------------------------------------
| VALIDATION
|--------------------------------------------------------------------------
*/

if (
    empty($owner) ||
    empty($business) ||
    empty($email) ||
    empty($phone) ||
    empty($payoutPhone) ||
    empty($password)
) {

    echo json_encode([
        "success" => false,
        "message" => "All required fields are required."
    ]);

    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

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

    exit;
}

if (strlen($password) < 6) {

    echo json_encode([
        "success" => false,
        "message" => "Password must be at least 6 characters."
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| DUPLICATE EMAIL
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("SELECT id FROM printer_agents WHERE email=? LIMIT 1");
$stmt->execute([$email]);

if ($stmt->fetch()) {

    echo json_encode([
        "success" => false,
        "message" => "Email already registered."
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| DUPLICATE PHONE
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
SELECT id
FROM printer_agents
WHERE phone=? OR payout_phone=?
LIMIT 1
");

$stmt->execute([$phone, $payoutPhone]);

if ($stmt->fetch()) {

    echo json_encode([
        "success" => false,
        "message" => "Phone number already exists."
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| SECURITY
|--------------------------------------------------------------------------
*/

$passwordHash = password_hash($password, PASSWORD_DEFAULT);

$deviceId = "PRN-" . strtoupper(substr(md5(uniqid("", true)), 0, 8));

$agentToken = bin2hex(random_bytes(32));

$otp = str_pad(random_int(0, 999999), 6, "0", STR_PAD_LEFT);

$expires = date("Y-m-d H:i:s", strtotime("+10 minutes"));

/*
|--------------------------------------------------------------------------
| INSERT
|--------------------------------------------------------------------------
*/

$sql = "

INSERT INTO printer_agents
(
owner_name,
business_name,
email,
phone,
payout_phone,
password,
device_id,
computer_name,
agent_token,
phone_verified,
verification_code,
verification_expires,
email_verified,
account_status,
balance,
total_earned,
total_withdrawn
)

VALUES
(
?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
)

";

$stmt = $pdo->prepare($sql);

$stmt->execute([

    $owner,
    $business,
    $email,
    $phone,
    $payoutPhone,
    $passwordHash,
    $deviceId,
    $computerName,
    $agentToken,
    0,
    $otp,
    $expires,
    0,
    "PENDING",
    0,
    0,
    0

]);

$agentId = $pdo->lastInsertId();

$smsResult = OTPService::sendOTP($phone, $otp);

if (!$smsResult["success"]) {

    echo json_encode([
        "success" => false,
        "message" => "Registration completed, but failed to send verification SMS.",
        "error" => $smsResult["message"]
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| RESPONSE
|--------------------------------------------------------------------------
*/

echo json_encode([

    "success" => true,

    "message" => "Registration successful. Verify your phone.",

    "data" => [

        "agent_id" => $agentId,

        "device_id" => $deviceId,

        "agent_token" => $agentToken,

        "account_status" => "PENDING"

    ],

], JSON_PRETTY_PRINT);