<?php
if (!defined('ADDFUNDS')) {
    http_response_code(404);
    die();
}

$email = $methodExtras["email"];
$password = $methodExtras["password"];
$PhonePeTransactionId = htmlspecialchars(trim($_POST["PhonePeTransactionId"]));

if (empty($PhonePeTransactionId)) {
    errorExit("The Transaction ID cannot be empty.");
}

if (!countRow(['table' => 'payments', 'where' => ['payment_extra' => $PhonePeTransactionId, "payment_status" => 3, "payment_delivery" => 2]])) {

    // "INBOX" hata kar generic rakha hai taaki sab folders check ho sakein (kuch servers par)
    $hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX'; 
    $inbox = imap_open($hostname, $email, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
    
    // Sirf Transaction ID se search karein
    $emails = imap_search($inbox, 'TEXT "' . $PhonePeTransactionId . '"');

    $transaction = array();
    
    if ($emails) {
        foreach ($emails as $email_id) {
            // Email body nikalne ke liye behtar tarika (Plain text ya HTML dono check karega)
            $body = imap_fetchbody($inbox, $email_id, 1.1); // 1.1 plain text ke liye
            if(empty($body)) {
                $body = imap_fetchbody($inbox, $email_id, 1);
            }

            // Clean the body (HTML tags hatane ke liye agar zarurat ho)
            $body = quoted_printable_decode($body);
            $body = strip_tags($body);

            // Screenshot ke pattern ke hisaab se Regex
            $amount_exp = '/Received\s+₹\s*([\d,.]+)/i';
            $tid_exp    = '/Txn\.\s*ID\s*:\s*([A-Z0-9]+)/i';
            $status_exp = '/Txn\.\s*Status\s*:\s*(Successful|Success)/i';

            preg_match($amount_exp, $body, $amount_match);
            preg_match($tid_exp, $body, $tid_match);
            preg_match($status_exp, $body, $status_match);

            $clean_tid = isset($tid_match[1]) ? trim($tid_match[1]) : "";
            
            // Transaction ID match hona chahiye
            if (strpos($clean_tid, $PhonePeTransactionId) !== false || $clean_tid == $PhonePeTransactionId) {
                $transaction["amount"] = isset($amount_match[1]) ? floatval(str_replace(',', '', $amount_match[1])) : 0;
                $transaction["tid"] = $clean_tid;
                $transaction["status"] = isset($status_match[1]) ? "Successful" : "Pending";
                break;
            }
        }
    }
    
    imap_close($inbox);

    if(empty($transaction)){
        errorExit("Transaction ID not found. Make sure the email has arrived in your Gmail (Check Updates/Promotions too).");
    }
    
    // Amount Match logic
    if($transaction["amount"] != floatval($paymentAmount)){
         errorExit("Amount Mismatch! Found: " . $transaction["amount"] . " but you entered: " . $paymentAmount);
    }

    if ($transaction["status"] == "Successful") {
        // --- INSERT AND UPDATE DATABASE CODE START ---
        $insert = $conn->prepare("INSERT INTO payments SET client_id=:client_id, payment_amount=:amount, payment_method=:method, payment_mode=:mode, payment_create_date=:date, payment_ip=:ip, payment_extra=:extra");
        $insert->execute(["client_id" => $user["client_id"], "amount" => $paymentAmount, "method" => $methodId, "mode" => "Automatic", "date" => date("Y.m.d H:i:s"), "ip" => GetIP(), "extra" => $PhonePeTransactionId]);

        $paymentId = $conn->lastInsertId();
        $paidAmount = floatval($paymentAmount);

        if ($paymentFee > 0) { $paidAmount -= ($paidAmount * ($paymentFee / 100)); }
        if ($paymentBonusStartAmount != 0 && $paidAmount >= $paymentBonusStartAmount) { $paidAmount += ($paidAmount * ($paymentBonus / 100)); }

        $paidAmount = from_to($currencies_array, $methodCurrency, $settings["site_base_currency"], $paidAmount);

        $update = $conn->prepare('UPDATE payments SET client_balance=:balance, payment_amount=:payment_amount, payment_status=:status, payment_delivery=:delivery WHERE payment_id=:id');
        $update->execute(['balance' => $user['balance'], "payment_amount" => $paidAmount, 'status' => 3, 'delivery' => 2, 'id' => $paymentId]);

        $updateBalance = $conn->prepare("UPDATE clients SET balance=:balance WHERE client_id=:id");
        $updateBalance->execute(["balance" => $user["balance"] + $paidAmount, "id" => $user["client_id"]]);

        $response["success"] = true;
        $response["message"] = "Money added successfully!";
        $response["content"] = '<script type="text/javascript">window.location.reload();</script>';
        // --- INSERT AND UPDATE DATABASE CODE END ---
    } else {
        errorExit("Transaction is not successful yet.");
    }

} else {
    errorExit("This Transaction ID is already used.");
}