<?php
include_once '../config/connect.php';
require_once '../config/whatsapp.php';
require_once '../config/topup.php';
include_once __DIR__ . '/../../../../vendor/autoload.php';
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (isset($_POST['add_agent'])) {

    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);

    $agent_upline_raw = $purifier->purify($_POST['agent_upline'] ?? '');
    $agent_namex = $purifier->purify($_POST['agent_name']);
    $agent_whatsappx = $purifier->purify($_POST['agent_whatsapp'] ?? '');
    $agent_ratex = trim((string)$purifier->purify($_POST['agent_rate_coin'] ?? ''));

    $agent_upline = mysqli_real_escape_string($call, $agent_upline_raw);
    $agent_name = mysqli_real_escape_string($call, $agent_namex);
    $agent_whatsapp = wa_normalize_number($agent_whatsappx);
    $password = mysqli_real_escape_string($call, $_POST['agent_password']);
    $password_hashed = md5($password);

    $current_agent_level = $_SESSION['admin']['agent_level'] ?? ($_SESSION['agent_level'] ?? '');
    $current_agent_name = agent_public_name((array)($_SESSION['admin'] ?? []));
    $current_agent_refs = agent_identity_values((array)($_SESSION['admin'] ?? []));
    $new_agent_level = $purifier->purify($_POST['agent_level'] ?? '');

    $n_token = md5(str_acak(15));
    $n_secret = str_acak(10);
    $created = date("Y-m-d H:i:s");
    $agent_code = mysqli_real_escape_string($call, $n_token);

    $trxid = md5($current_agent_name . $n_token . $created);
    $secret_key = md5($n_secret . $agent_name . $password_hashed);

    if (!in_array($current_agent_level, ['admin', 'head_agent'], true) || $current_agent_name === '') {
        header('Location: ../index?page=AddAgent&msg=14');
        exit();
    }

    if ($agent_upline !== '' && !in_array($agent_upline, $current_agent_refs, true)) {
        header('Location: ../index?page=AddAgent&msg=14');
        exit();
    }

    $agent_upline = mysqli_real_escape_string($call, $current_agent_name);

    $cek_status = mysqli_query(
        $call,
        "SELECT agent_name FROM tb_agent 
         WHERE agent_name = '$agent_name'
            OR agent_code = '$agent_name'
            OR agent_code = '$agent_code'"
    );

    if (mysqli_num_rows($cek_status) > 0) {
        header('Location: ../index?page=AddAgent&msg=10');
        exit();
    }

    /* =========================
       FIX LOGIC LEVEL (ADMIN ONLY)
       ========================= */

    if ($current_agent_level === 'admin') {
        $allowed_levels = ['admin', 'head_agent', 'agent'];
    } else {
        $allowed_levels = ['agent'];
    }

    if (!in_array($new_agent_level, $allowed_levels)) {
        header('Location: ../index?page=AddAgent&msg=14');
        exit();
    }

    /* =========================
       END FIX
       ========================= */

    if (empty($agent_name) || empty($password)) {
        header('Location: ../index?page=AddAgent&msg=11');
        exit();
    }

    if ($agent_whatsappx !== '' && $agent_whatsapp === '') {
        header('Location: ../index?page=AddAgent&msg=50');
        exit();
    }

    topup_ensure_agent_rate_column($call);

    if ($current_agent_level === 'admin') {
        $agent_rate = $agent_ratex !== '' ? (float)str_replace(',', '.', $agent_ratex) : topup_get_global_rate($call);

        if ($agent_rate <= 0) {
            header('Location: ../index?page=AddAgent&msg=16');
            exit();
        }

        $agent_rate_sql = "'" . mysqli_real_escape_string($call, (string)$agent_rate) . "'";
    } else {
        $agent_rate_sql = "NULL";
    }

    $query = "INSERT INTO tb_agent (
        agent_code,
        agent_name,
        secret_key,
        agent_password,
        agent_upline,
        agent_created,
        agent_balance,
        rate_coin,
        agent_level,
        agent_status,
        agent_IP1,
        agent_IP2,
        original_password
    ) VALUES (
        '$agent_code',
        '$agent_name',
        '$secret_key',
        '$password_hashed',
        '$agent_upline',
        '$created',
        '0',
        $agent_rate_sql,
        '$new_agent_level',
        'active',
        '0',
        '0',
        '$password'
    )";

    if (mysqli_query($call, $query)) {
        if ($agent_whatsapp !== '') {
            wa_save_agent_whatsapp($call, $agent_name, $agent_whatsapp);
        }
        header('Location: ../index?page=AddAgent&msg=12');
        exit();
    } else {
        header('Location: ../index?page=AddAgent&msg=13');
        exit();
    }
}
?>
