<?php

include_once __DIR__ . '/secrets.php';
include 'db_connect.php';

$name        = $_POST['name'] ?? '';
$number      = $_POST['number'] ?? '';
$country     = $_POST['country'] ?? '';
$countrycode = $_POST['countrycode'] ?? '';
$email       = $_POST['email'] ?? '';
$time        = $_POST['time'] ?? '';
$password    = $_POST['password'] ?? '';
$key         = $_POST['key'] ?? '';

$security_key = decrypData($key);

header('Content-Type: application/json'); // JSON রেসপন্স

if ($security_key === false) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid encryption data']);
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN && strlen($number) > 0) {

    $con = dbConnect();

    // 🔍 Number OR Email already exists?
    $stmt = $con->prepare("SELECT id FROM signup WHERE number = ? OR email = ?");
    $stmt->bind_param("ss", $number, $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {

        // Unique User ID (UUID)
        $userid = str_pad(mt_rand(0, 99999999), 8, '0', STR_PAD_LEFT);

        $stmt = $con->prepare("INSERT INTO signup (userid, name, number, password, country, country_code, email, time) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssss", $userid, $name, $number, $password, $country, $countrycode, $email, $time);

        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'userid' => $userid, 'message' => 'Signup successful']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $stmt->error]);
        }

    } else {
        echo json_encode(['status' => 'error', 'message' => 'User already available! Change phone number or email and try again']);
    }

    $stmt->close();
    $con->close();
}
?>
