<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Kolkata');
$config = include($_SERVER['DOCUMENT_ROOT'] . "/pay/config.php");

$conn = new mysqli(
    $config['db_host'],
    $config['db_user'],
    $config['db_pass'],
    $config['db_name']
);

if ($conn->connect_error) {
    die("❌ DB Connection failed: " . $conn->connect_error);
}

// === RAW LOGGING ===
$raw = file_get_contents("php://input");
$logfile = __DIR__ . "/webhook_log_" . date("Y-m-d") . ".txt";
file_put_contents($logfile, "[" . date("H:i:s") . "] RAW: $raw\n", FILE_APPEND);

// === Extract UTR & Amount ===
preg_match('/UPI Ref\.?\s*No\.?\s*[:\-]?\s*(\d{12})/i', $raw, $utrMatch);
preg_match('/Rs\.?\s*([0-9]+\.\d{2})/i', $raw, $amtMatch);

$utr = $utrMatch[1] ?? '';
$amount = $amtMatch[1] ?? '';

if (!$utr || !$amount) {
    file_put_contents($logfile, "[" . date("H:i:s") . "] ❌ UTR or Amount not found\n", FILE_APPEND);
    exit;
}

// === STEP 1: Match transaction with same UTR AND Amount and status = 'pending'
$stmt = $conn->prepare("SELECT order_no, uid FROM transactions WHERE status = 'pending' AND utr_number = ? AND ABS(amount - ?) < 0.01 LIMIT 1");
$stmt->bind_param("sd", $utr, $amount);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    $order_no = $row['order_no'];
    $uid = $row['uid'];

    // Mark transaction as success
    $stmt_upd = $conn->prepare("UPDATE transactions SET status = 'success' WHERE order_no = ?");
    $stmt_upd->bind_param("s", $order_no);
    $stmt_upd->execute();

    if ($stmt_upd->error) {
        file_put_contents($logfile, "[" . date("H:i:s") . "] ❌ Transaction update error: " . $stmt_upd->error . "\n", FILE_APPEND);
    }

} else {
    file_put_contents($logfile, "[" . date("H:i:s") . "] ❌ No matching transaction for UTR $utr and Amount ₹$amount\n", FILE_APPEND);
    exit;
}

// === STEP 2: Recharge table UPDATE (based on orderid)
$stmt = $conn->prepare("UPDATE recharge SET status = 'success', created_at = NOW() WHERE orderid = ?");
$stmt->bind_param("s", $order_no);
$stmt->execute();

if ($stmt->error) {
    file_put_contents($logfile, "[" . date("H:i:s") . "] ❌ Recharge update error: " . $stmt->error . "\n", FILE_APPEND);
}

// === STEP 3: Wallet Update
$stmt = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
$stmt->bind_param("di", $amount, $uid);
$stmt->execute();

if ($stmt->error) {
    file_put_contents($logfile, "[" . date("H:i:s") . "] ❌ Wallet update error: " . $stmt->error . "\n", FILE_APPEND);
}

// === STEP 4: Thevani Insert
$orderid = uniqid("RID"); // new unique reference id
$mula = 'fastpay';

$stmt = $conn->prepare("INSERT INTO thevani 
(balakedara, motta, dharavahi, mula, payid, ullekha, duravani, ekikrtapavati, dinankavannuracisi, madari, pavatiaidi, sthiti) 
VALUES (?, ?, ?, ?, 0, ?, '1', '0', NOW(), 0, 0, 1)");

$stmt->bind_param("idsss", $uid, $amount, $orderid, $mula, $order_no);
$stmt->execute();

if ($stmt->error) {
    file_put_contents($logfile, "[" . date("H:i:s") . "] ❌ Thevani insert error: " . $stmt->error . "\n", FILE_APPEND);
}

file_put_contents($logfile, "[" . date("H:i:s") . "] ✅ Payment success: UID $uid, Order $order_no, ₹$amount, UTR $utr\n", FILE_APPEND);
?>