<?php
ini_set('display_errors', 0);
$logFile = __DIR__ . '/webhook_debug.txt';
$rawInput = file_get_contents('php://input');
file_put_contents($logFile, date('Y-m-d H:i:s') . " - HIT\n", FILE_APPEND);
$data = json_decode($rawInput, true);
if (!$data) {
    $data = $_POST;
}
$reference = $data['transaction']['reference'] ?? ($data['data']['transaction']['reference'] ?? ($data['data']['reference'] ?? ($data['reference'] ?? '')));
$status = strtolower($data['transaction']['status'] ?? ($data['data']['transaction']['status'] ?? ($data['data']['status'] ?? ($data['status'] ?? ''))));
if (empty($reference)) {
    file_put_contents($logFile, "NO REF\n", FILE_APPEND);
    die("No Ref");
}
$envPath = file_exists(__DIR__ . '/../.env') ? __DIR__ . '/../.env' : __DIR__ . '/.env';
$dbHost = '127.0.0.1';
$dbName = '';
$dbUser = '';
$dbPass = '';
if (file_exists($envPath)) {
    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        $parts = explode('=', $line, 2);
        if (count($parts) === 2) {
            $name = trim($parts[0]);
            $value = trim($parts[1], '"\' ');
            if ($name === 'DB_HOST') $dbHost = $value;
            if ($name === 'DB_DATABASE') $dbName = $value;
            if ($name === 'DB_USERNAME') $dbUser = $value;
            if ($name === 'DB_PASSWORD') $dbPass = $value;
        }
    }
}
try {
    $conn = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM deposits WHERE transaction_id=:ref LIMIT 1");
    $stmt->execute(['ref' => $reference]);
    $deposit = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($deposit) {
        if ($status === 'successful' || $status === 'completed' || $status === 'success') {
            if ($deposit['status'] !== 'approved') {
                $conn->prepare("UPDATE deposits SET status='approved' WHERE id=:id")->execute(['id' => $deposit['id']]);
                $conn->prepare("UPDATE users SET deposit_balance = deposit_balance + :amt WHERE id=:uid")->execute(['amt' => $deposit['amount'], 'uid' => $deposit['user_id']]);
                $dateStr = date('d-m-Y H:i');
                $conn->prepare("INSERT INTO user_ledgers (user_id, reason, perticulation, amount, debit, credit, status, date, created_at, updated_at) VALUES (:uid, 'payment_approved', 'Your payment already approved.', :amt, :amt, 0, 'approved', :dstr, NOW(), NOW())")->execute([
                    'uid' => $deposit['user_id'],
                    'amt' => $deposit['amount'],
                    'dstr' => $dateStr
                ]);
                file_put_contents($logFile, "SUCCESS: Funds Added\n", FILE_APPEND);
            }
        } elseif ($status === 'failed' || $status === 'cancelled' || $status === 'declined') {
            $conn->prepare("UPDATE deposits SET status='rejected' WHERE id=:id")->execute(['id' => $deposit['id']]);
            file_put_contents($logFile, "FAILED: Marked as rejected\n", FILE_APPEND);
        }
    }
} catch (Exception $e) {
    file_put_contents($logFile, "DB ERR: " . $e->getMessage() . "\n", FILE_APPEND);
}
echo "OK";
?>