<?php

session_start();

include($_SERVER['DOCUMENT_ROOT']."/SEAT/config/db.php");

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

if(
    !isset($_SESSION['role']) ||
    $_SESSION['role'] != "admin"
){
    echo json_encode([
        "status" => "error",
        "message" => "Unauthorized"
    ]);

    exit;
}

$user_id = (int)$_SESSION['id'];

$phone = trim($_POST['phone'] ?? '');

/* REMOVE NON NUMBER */

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

/* EMPTY */

if(empty($phone)){

    echo json_encode([
        "status" => "error",
        "message" => "Phone number is required"
    ]);

    exit;
}

/* FORMAT */

if(!preg_match('/^01[0-9]{8,9}$/', $phone)){

    echo json_encode([
        "status" => "error",
        "message" => "Invalid phone number format"
    ]);

    exit;
}

/* DUPLICATE */

$dup = mysqli_query($conn,"
SELECT id
FROM admins
WHERE phone_number = '$phone'
AND user_id != '$user_id'
LIMIT 1
");

if(mysqli_num_rows($dup) > 0){

    echo json_encode([
        "status" => "error",
        "message" => "Phone number already used"
    ]);

    exit;
}

/* UPDATE */

$update = mysqli_query($conn,"
UPDATE admins
SET phone_number = '$phone'
WHERE user_id = '$user_id'
");

if($update){

    echo json_encode([
        "status" => "success",
        "message" => "Profile updated successfully"
    ]);

}else{

    echo json_encode([
        "status" => "error",
        "message" => "Database update failed"
    ]);
}