<?php
require 'jwt/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

header('Content-Type: application/json');
require_once 'db.php';

/* ================= AES GCM CONFIG ================= */
define("AES_GCM_SECRET", "SHUVO_AES_GCM_SECRET_KEY_32B");

/* ================= AES GCM DECRYPT FUNCTION ================= */
function aes_gcm_decrypt($payload) {
    $json = json_decode($payload, true);
    if (!isset($json['iv'], $json['data'], $json['tag'])) {
        return false;
    }

    $iv   = base64_decode($json['iv']);
    $data = base64_decode($json['data']);
    $tag  = base64_decode($json['tag']);

    if (strlen($iv) !== 12 || strlen($tag) !== 16) {
        return false;
    }

    $key = str_pad(AES_GCM_SECRET, 32, "\0");

    return openssl_decrypt(
        $data,
        "aes-256-gcm",
        $key,
        OPENSSL_RAW_DATA,
        $iv,
        $tag
    );
}

/* ================= UNIQUE UID GENERATOR ================= */
function generate_unique_uid($conn) {
    do {
        $uid = str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT);
        $stmt = $conn->prepare("SELECT id FROM users WHERE uid = ? LIMIT 1");
        $stmt->bind_param("s", $uid);
        $stmt->execute();
        $stmt->store_result();
        $exists = $stmt->num_rows > 0;
        $stmt->close();
    } while ($exists);
    return $uid;
}

/* ================= JWT SECRET ================= */
$jwt_secret = "Shuvo_2025_SECURE49797567697979696967676967696979797969796f796f796f";

/* ================= POST ONLY ================= */
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    echo json_encode(["status" => "error", "message" => "Invalid Request Method"]);
    exit;
}

/* ================= DETECT TYPE ================= */
$type = strtolower(trim($_POST['type'] ?? 'manual'));

/* ================= IP LIMIT (common) ================= */
$logFile     = 'ip_log.json';
$ipAddress   = $_SERVER['REMOTE_ADDR'];
$currentTime = time();
$ipLog = file_exists($logFile) ? json_decode(file_get_contents($logFile), true) : [];

if (isset($ipLog[$ipAddress]) && ($currentTime - $ipLog[$ipAddress]) < 3600) {
    http_response_code(429);
    echo json_encode(["status" => "error", "message" => "You can only signup once per hour"]);
    exit;
}

/* ================= TYPE BASED DATA PARSING ================= */
if ($type === 'manual') {

    /* ---------- MANUAL: Encrypted payload ---------- */
    if (!isset($_POST['payload'])) {
        echo json_encode(["status" => "error", "message" => "Payload missing"]);
        exit;
    }

    $decrypted = aes_gcm_decrypt($_POST['payload']);
    if ($decrypted === false) {
        echo json_encode(["status" => "error", "message" => "Invalid encrypted data"]);
        exit;
    }

    $data = json_decode($decrypted, true);
    if (!is_array($data)) {
        echo json_encode(["status" => "error", "message" => "Invalid decrypted JSON"]);
        exit;
    }

    /* Security key check */
    $server_key_extra = "oyyououfYzuuziztiztJjfitziitzi";
    $client_key_extra = $data["Tastdhfjky"] ?? '';
    if ($client_key_extra !== $server_key_extra) {
        echo json_encode(["status" => "error", "message" => "Permissions Denied"]);
        exit;
    }

    /* Device ban check */
    $check_device_id = $data["DeVicE_iD"] ?? '';
    if (!empty($check_device_id)) {
        $stmt = $conn->prepare("SELECT ban_status FROM device_ban WHERE device_id = ? LIMIT 1");
        $stmt->bind_param("s", $check_device_id);
        $stmt->execute();
        $result  = $stmt->get_result();
        $ban_row = $result->fetch_assoc();
        $stmt->close();
        if ($ban_row && (int)$ban_row['ban_status'] === 1) {
            echo json_encode(["status" => "error", "message" => "Registration Blocked"]);
            $conn->close();
            exit;
        }
    }

    $username    = $data["username"]   ?? '';
    $email       = $data["email"]      ?? '';
    $number      = $data["number"]     ?? '';
    $password    = $data["password"]   ?? '';
    $device_id   = $data["DeVicE_iD"]  ?? '';
    $fcm_key     = $data["fcm_key"]    ?? '';
    $refer_code  = $data["refer_code"] ?? null;
    $profile_pic = null;
    $extra_json  = null;

} elseif ($type === 'telegram' || $type === 'whatsapp') {

    /* ---------- TELEGRAM / WHATSAPP: Plain POST, no encryption ---------- */

    /* Security key check (plain POST) */
    $server_key_extra = "oyyououfYzuuziztiztJjfitziitzi";
    $client_key_extra = $_POST["Tastdhfjky"] ?? '';
    if ($client_key_extra !== $server_key_extra) {
        echo json_encode(["status" => "error", "message" => "Permissions Denied"]);
        exit;
    }

    /* Device ban check */
    $check_device_id = $_POST["DeVicE_iD"] ?? '';
    if (!empty($check_device_id)) {
        $stmt = $conn->prepare("SELECT ban_status FROM device_ban WHERE device_id = ? LIMIT 1");
        $stmt->bind_param("s", $check_device_id);
        $stmt->execute();
        $result  = $stmt->get_result();
        $ban_row = $result->fetch_assoc();
        $stmt->close();
        if ($ban_row && (int)$ban_row['ban_status'] === 1) {
            echo json_encode(["status" => "error", "message" => "Registration Blocked"]);
            $conn->close();
            exit;
        }
    }

    $username    = $_POST["username"]    ?? '';
    $email       = $_POST["email"]       ?? '';
    $number      = $_POST["number"]      ?? '';
    $password    = $_POST["password"]    ?? '';
    $device_id   = $_POST["DeVicE_iD"]   ?? '';
    $fcm_key     = $_POST["fcm_key"]     ?? '';
    $refer_code  = $_POST["refer_code"]  ?? null;
    $profile_pic = $_POST["profile_pic"] ?? null;
    $extra_json  = $_POST["extra_json"]  ?? null;

    /* extra_json valid JSON কিনা check */
    if (!empty($extra_json)) {
        $decoded_extra = json_decode($extra_json, true);
        if (!is_array($decoded_extra)) {
            echo json_encode(["status" => "error", "message" => "extra_json must be valid JSON"]);
            exit;
        }
    }

} else {
    echo json_encode(["status" => "error", "message" => "Invalid type"]);
    exit;
}

/* ================= REQUIRED CHECK ================= */
$newDate = date("d-M-Y");

if (!$username || !$email || !$number || !$password || !$device_id) {
    echo json_encode(["status" => "error", "message" => "Required fields missing"]);
    $conn->close();
    exit;
}

/* ================= UNIQUE CHECK ================= */
$fields = ["username" => $username, "email" => $email, "number" => $number];
foreach ($fields as $field => $value) {
    $stmt = $conn->prepare("SELECT id FROM users WHERE $field = ?");
    $stmt->bind_param("s", $value);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        echo json_encode(["status" => "error", "message" => ucfirst($field) . " already exists"]);
        $stmt->close();
        $conn->close();
        exit;
    }
    $stmt->close();
}

$verify_badge = "NO";

/* ================= GENERATE UNIQUE UID ================= */
$uid = generate_unique_uid($conn);

/* ================= INSERT LOGIC ================= */
if (empty($refer_code)) {

    $stmt = $conn->prepare(
        "INSERT INTO users (uid, username, email, number, password, fcm_key, device_id, verify_badge, profile_pic, extra_json)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->bind_param(
        "ssssssssss",
        $uid, $username, $email, $number, $password,
        $fcm_key, $device_id, $verify_badge,
        $profile_pic, $extra_json
    );

    if ($stmt->execute()) {
        $token = JWT::encode(
            ["email" => $email, "device_id" => $device_id, "iat" => time()],
            $jwt_secret,
            "HS256"
        );

        $stmt2 = $conn->prepare("UPDATE users SET token=? WHERE email=?");
        $stmt2->bind_param("ss", $token, $email);
        $stmt2->execute();
        $stmt2->close();

        $ipLog[$ipAddress] = $currentTime;
        file_put_contents($logFile, json_encode($ipLog));

        echo json_encode([
            "status"   => "success",
            "message"  => "Registration Success",
            "username" => $username,
            "token"    => $token
        ]);
    }
    $stmt->close();

} else {

    $stmt = $conn->prepare("SELECT id FROM users WHERE username=?");
    $stmt->bind_param("s", $refer_code);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 0) {
        echo json_encode(["status" => "error", "message" => "Invalid Promo Code"]);
        $stmt->close();
        $conn->close();
        exit;
    }
    $stmt->close();

    $conn->begin_transaction();
    try {
        $balance = 0;

        $stmt = $conn->prepare(
            "INSERT INTO users (uid, username, email, number, password, balance, fcm_key, device_id, referred_by, verify_badge, profile_pic, extra_json)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );
        $stmt->bind_param(
            "ssssissssss s",
            $uid, $username, $email, $number, $password,
            $balance, $fcm_key, $device_id, $refer_code,
            $verify_badge, $profile_pic, $extra_json
        );
        $stmt->execute();
        $stmt->close();

        $stmt = $conn->prepare("UPDATE users SET total_refer=total_refer+1 WHERE username=?");
        $stmt->bind_param("s", $refer_code);
        $stmt->execute();
        $stmt->close();

        $stmt   = $conn->prepare("INSERT INTO refers (date, name, status, refer_by) VALUES (?, ?, ?, ?)");
        $status = "Registered";
        $stmt->bind_param("ssss", $newDate, $username, $status, $refer_code);
        $stmt->execute();
        $stmt->close();

        $conn->commit();

        $token = JWT::encode(
            ["email" => $email, "device_id" => $device_id, "iat" => time()],
            $jwt_secret,
            "HS256"
        );

        $stmt = $conn->prepare("UPDATE users SET token=? WHERE email=?");
        $stmt->bind_param("ss", $token, $email);
        $stmt->execute();
        $stmt->close();

        $ipLog[$ipAddress] = $currentTime;
        file_put_contents($logFile, json_encode($ipLog));

        echo json_encode([
            "status"   => "success",
            "message"  => "Registration & Refer Success",
            "username" => $username,
            "token"    => $token
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(["status" => "error", "message" => "Refer error"]);
    }
}

$conn->close();
exit;
?>