<?php
// 1. Start Session at the very top
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

include('./includes/config.php');

/* ---------------- GATEWAY CONFIGURATION ---------------- */
 $merchant_key = "MKEY_310de4bf541be8fff433c6543e8b8364"; 
 $secret_key   = "SKEY_dc28874bf63083c2c5b00896a771db1e";   

/* ---------------- HELPER FUNCTIONS ---------------- */
function renderSwalAndExit($title, $message, $icon = 'success', $redirectUrl = null, $asHtml = false) {
    $safeTitle = htmlspecialchars((string)$title, ENT_QUOTES, 'UTF-8');
    $safeRedirect = $redirectUrl !== null ? htmlspecialchars((string)$redirectUrl, ENT_QUOTES, 'UTF-8') : '';

    if ($asHtml) {
        $payload = json_encode((string)$message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $msgField = "html: {$payload}";
    } else {
        $payload = json_encode((string)$message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $msgField = "text: {$payload}";
    }

    $safeIcon = htmlspecialchars((string)$icon, ENT_QUOTES, 'UTF-8');

    echo '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<title>' . $safeTitle . '</title>';
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
    echo '</head><body>';
    echo '<script>';
    echo "Swal.fire({title: " . json_encode($safeTitle) . ", {$msgField}, icon: " . json_encode($safeIcon) . "})";
    if ($redirectUrl !== null && $redirectUrl !== '') {
        echo ".then(() => { window.location.href = " . json_encode($safeRedirect) . "; })";
    }
    echo ';';
    echo '</script>';
    echo '</body></html>';
    exit;
}

function http_request_post($url, $postData) {
    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($postData),
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}

function smartupi_create_order($request) {
    return http_request_post("https://gateway.mrhub.online/api/v1/order/create", $request);
}

function smartupi_status($merchant_key, $secret_key, $order_id) {
    return http_request_post("https://gateway.mrhub.online/api/v1/order/verify", [
        "merchant_key" => $merchant_key,
        "secret_key"   => $secret_key,
        "order_id"     => $order_id
    ]);
}

// Dynamic Callback URL
 $socket = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
 $current_url = $socket . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

/* ---------------- CALLBACK HANDLER (Payment Return) ---------------- */
if (isset($_POST['status']) && isset($_POST['tran_id'])) {
    $order_id = mysqli_real_escape_string($ahk_conn, $_POST['tran_id']);
    
    // Verify Signature with Gateway
    $response = smartupi_status($merchant_key, $secret_key, $order_id);

    if (isset($response['status']) && $response['status'] == 1 && $response['code'] == 786 && strtoupper($response['result']['txnStatus']) === "SUCCESS") {
        $result = $response['result'];
        $orderId = $result['orderId'];
        $amount = floatval($result['amount']);

        // Check Pending Transaction
        $stmt = mysqli_prepare($ahk_conn, "SELECT * FROM wallet WHERE txn_id = ? AND status='pending'");
        mysqli_stmt_bind_param($stmt, "s", $orderId);
        mysqli_stmt_execute($stmt);
        $res = mysqli_stmt_get_result($stmt);
        $txn_row = mysqli_fetch_assoc($res);
        mysqli_stmt_close($stmt);

        if ($txn_row) {
            $txn_phone = $txn_row['phone'];

            // 1. Update Wallet Status
            $stmt_w = mysqli_prepare($ahk_conn, "UPDATE wallet SET status='success' WHERE txn_id=?");
            mysqli_stmt_bind_param($stmt_w, "s", $orderId);
            mysqli_stmt_execute($stmt_w);
            mysqli_stmt_close($stmt_w);

            // 2. Activate User Account
            $stmt_u = mysqli_prepare($ahk_conn, "UPDATE users SET status='1' WHERE phone=?");
            mysqli_stmt_bind_param($stmt_u, "s", $txn_phone);
            mysqli_stmt_execute($stmt_u);
            mysqli_stmt_close($stmt_u);

            // 3. Get Password from Cookie (The Fix You Asked For)
            $display_pass = "********"; // Default
            $cookie_name = "reg_pass_" . $txn_phone;
            
            if(isset($_COOKIE[$cookie_name])) {
                $display_pass = $_COOKIE[$cookie_name];
                // Delete the cookie after reading (Security)
                setcookie($cookie_name, "", time() - 3600, "/");
            }

            // 4. Send WhatsApp Message
            if (!empty($txn_phone)) {
                $uq = mysqli_query($ahk_conn, "SELECT name, type FROM users WHERE phone='$txn_phone'");
                $udata = mysqli_fetch_assoc($uq);
                $u_name = $udata['name'] ?? 'User';
                $u_type = $udata['type'] ?? 'Member';

                $message = "🎉 Welcome to {$websiteName}!\n\nDear {$u_name},\n\nYour {$u_type} account has been activated.\n\n📱 Login ID: {$txn_phone}\n🔑 Password: {$display_pass}\n\nPlease keep your details safe.\n\n— Support Team";
                $msg = urlencode($message);
                $api_url = "https://{$whatsappurl}/send-message?api_key={$whapikey}&sender={$whsender}&number=91{$txn_phone}&message={$msg}";
                
                $ch = curl_init();
                curl_setopt_array($ch, [CURLOPT_URL => $api_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => false]);
                curl_exec($ch);
                curl_close($ch);
            }

            // 5. Set Success Message in Session & Redirect
            $_SESSION['swal_msg'] = [
                'type' => 'success',
                'title' => 'Payment Successful!',
                'html' => "<b>User ID:</b> $txn_phone<br><b>Password:</b> $display_pass"
            ];
            
            header("Location: " . $current_url);
            exit();
        }
    } else {
        $_SESSION['swal_msg'] = ['type' => 'error', 'title' => 'Payment Failed', 'text' => 'If payment was deducted, contact support!'];
        header("Location: " . $current_url);
        exit();
    }
}

/* ---------------- REFERRAL CODE ---------------- */
 $ref_code = '';
if (!empty($_GET['ref'])) {
    $ref_code = base64_decode(mysqli_real_escape_string($ahk_conn, $_GET['ref']));
}

/* ---------------- FORM SUBMIT ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['phone'])) {

    $name     = mysqli_real_escape_string($ahk_conn, $_POST['name']);
    $email    = mysqli_real_escape_string($ahk_conn, $_POST['email']);
    $phone    = mysqli_real_escape_string($ahk_conn, $_POST['phone']);
    $usertype = mysqli_real_escape_string($ahk_conn, $_POST['usertype']);
    $password = $_POST['password']; // Plain text password

    $order_id = "REG" . date("YmdHis") . rand(1000,99999);
    $date     = date("Y-m-d");

    if (strcasecmp($usertype, "admin") === 0) {
        renderSwalAndExit('Access Denied!', 'Invalid registration type.', 'error', 'register.php');
    }

    $check = mysqli_query($ahk_conn, "SELECT id FROM users WHERE phone='$phone' OR email='$email'");
    if (mysqli_num_rows($check) > 0) {
        renderSwalAndExit('Oops!', 'Email or phone already exists!', 'error', 'register.php');
    }

    $vpass = password_hash($password, PASSWORD_DEFAULT);

    if ($usertype === "retailer") {
        $amount = (int)$webdata['ret_reg_fee'];
    } elseif ($usertype === "distributor") {
        $amount = (int)$webdata['dist_reg_fee'];
    } else {
        $amount = 0; 
    }

    $isFree = ($amount == 0);

    if ($isFree) {
        $res = mysqli_query($ahk_conn, "INSERT INTO users (name, phone, email, password, type, status, referred_by, order_id, date) VALUES ('$name', '$phone', '$email', '$vpass', '$usertype', '1', '$ref_code', '$order_id', '$date')");

        if ($res) {
            if (!empty($ref_code)) {
                mysqli_query($ahk_conn, "INSERT INTO referal (phone, referred_by, txn_no, referral_balance, status) VALUES ('$phone', '$ref_code', 'REF" . rand(10000,99999) . "', '{$webdata['ref_bal']}', '1')");
            }

            // WhatsApp for Free Reg
            if (!empty($phone)) {
                $message = "🎉 Welcome to {$websiteName}!\n\nDear {$name},\n\nYour account is created.\n\n📱 Mobile: {$phone}\n🔑 Password: {$password}\n\n— Support Team";
                $msg = urlencode($message);
                $api_url = "https://{$whatsappurl}/send-message?api_key={$whapikey}&sender={$whsender}&number=91{$phone}&message={$msg}";
                $ch = curl_init();
                curl_setopt_array($ch, [CURLOPT_URL => $api_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => false]);
                curl_exec($ch);
                curl_close($ch);
            }

            renderSwalAndExit('Registration Successful!', 'Account created successfully. Please login to continue.', 'success', 'login.php');
        }
        exit;
    }

    /* ---------------- PAID REGISTRATION ---------------- */
    
    // SET COOKIE HERE: Store password in cookie for 10 minutes (600 seconds)
    // This allows us to retrieve it after payment callback
    setcookie("reg_pass_" . $phone, $password, time() + 600, "/");

    // Insert User (Inactive)
    $res = mysqli_query($ahk_conn, "INSERT INTO users (name, phone, email, password, type, status, referred_by, order_id, date) VALUES ('$name', '$phone', '$email', '$vpass', '$usertype', '0', '$ref_code', '$order_id', '$date')");

    if (!$res) {
        renderSwalAndExit('Error!', 'Database insertion failed!', 'error', 'register.php');
    }

    if (!empty($ref_code)) {
        mysqli_query($ahk_conn, "INSERT INTO referal (phone, referred_by, txn_no, referral_balance, status) VALUES ('$phone', '$ref_code', 'REF" . rand(10000,99999) . "', '{$webdata['ref_bal']}', '1')");
    }

    // Insert Pending Wallet Transaction
    $stmt = mysqli_prepare($ahk_conn, "INSERT INTO wallet (phone, amount, txn_id, email, status, date, PAYMENTMODE) VALUES (?, ?, ?, ?, 'pending', ?, 'REGFEE')");
    mysqli_stmt_bind_param($stmt, "sdsss", $phone, $amount, $order_id, $email, $date);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    // Call Gateway
    $request = [
        "merchant_key"     => $merchant_key,
        "secret_key"       => $secret_key,
        "amount"           => $amount,
        "customer_mobile"  => $phone,
        "customer_gmail"   => $email,
        "order_id"         => $order_id,
        "callback_url"     => $current_url, 
        "comment1"         => $name,
        "comment2"         => $usertype
    ];

    $response = smartupi_create_order($request);

    if (isset($response['status']) && $response['status'] === true) {
        $payment_url = $response['result']['payment_url'];
        header("Location: " . $payment_url);
        exit();
    } else {
        $err_msg = htmlspecialchars($response['message'] ?? 'Gateway Error');
        renderSwalAndExit('Error!', 'Payment Gateway Error: ' . $err_msg, 'error', 'register.php');
    }
}

// Include Template (Contains HTML Head & SweetAlert Library)
include('./template/ahkweb/authentication-signup.php');

// ---------------- DISPLAY SWEETALERT MESSAGE ---------------- 
if (isset($_SESSION['swal_msg'])) {
    $msg = $_SESSION['swal_msg'];
    unset($_SESSION['swal_msg']);
    echo "
    <script>
        Swal.fire({
            title: '{$msg['title']}',
            html: '{$msg['html']}',
            icon: '{$msg['type']}'
        }).then(() => {
            window.location.href = 'login.php';
        });
    </script>";
}
?>
