<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'config.php'; // Database connection
require __DIR__ . '/vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$paystack_secret_key = $_ENV['PAYSTACK_SECRET_KEY'];

function safe_stmt_close($stmt) {
    if ($stmt && $stmt instanceof mysqli_stmt) {
        $stmt->close();
    }
}

function formatAmount($amount) {
    return number_format($amount, 2);
}

// ✅ Handle GET (redirect from Paystack)
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['reference'])) {
    $reference = $_GET['reference'];

    // Verify transaction
    $ch = curl_init("https://api.paystack.co/transaction/verify/" . $reference);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $paystack_secret_key",
        "Content-Type: application/json"
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] && $result['data']['status'] === 'success') {
        $amount = $result['data']['amount'] / 100;
        $formattedAmount = formatAmount($amount);
        $email = $result['data']['customer']['email'];
        $transaction_id = $result['data']['reference'];

        // Prevent duplicate entry
        $stmt = $conn->prepare("SELECT id FROM tbl_deposits WHERE transaction_id = ?");
        $stmt->bind_param("s", $transaction_id);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            safe_stmt_close($stmt);
            echo "<h3>Transaction already processed.</h3>";
            exit();
        }
        safe_stmt_close($stmt);

        // Fetch user
        $stmt = $conn->prepare("SELECT id, username, phone, role FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->bind_result($user_id, $username, $phone, $role);
        $stmt->fetch();
        safe_stmt_close($stmt);

        // Get Super Admin
        $stmt = $conn->prepare("SELECT id FROM users WHERE role = 'super-admin' LIMIT 1");
        $stmt->execute();
        $stmt->bind_result($super_admin_id);
        $stmt->fetch();
        safe_stmt_close($stmt);

        if ($user_id && $super_admin_id) {
            $conn->begin_transaction();

            // Update balances
            $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->bind_param("di", $amount, $user_id);
            $user_updated = $stmt->execute();
            safe_stmt_close($stmt);

            $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->bind_param("di", $amount, $super_admin_id);
            $super_admin_updated = $stmt->execute();
            safe_stmt_close($stmt);

            if ($user_updated && $super_admin_updated) {
                $conn->commit();

                // Save deposit
                $stmt = $conn->prepare("INSERT INTO tbl_deposits (user_id, amount, email, phone, transaction_id, status) VALUES (?, ?, ?, ?, ?, 'successful')");
                $stmt->bind_param("idsss", $user_id, $amount, $email, $phone, $transaction_id);
                $stmt->execute();
                safe_stmt_close($stmt);

                // Notifications
                $userMsg = "Your deposit of GHS $formattedAmount was successful.";
                $stmt = $conn->prepare("INSERT INTO notifications (user_id, message, is_read) VALUES (?, ?, 0)");
                $stmt->bind_param("is", $user_id, $userMsg);
                $stmt->execute();
                safe_stmt_close($stmt);

                $adminMsg = "$username has made a deposit of GHS $formattedAmount.";
                $stmt = $conn->prepare("INSERT INTO notifications (user_id, message, is_read) VALUES (?, ?, 0)");
                $stmt->bind_param("is", $super_admin_id, $adminMsg);
                $stmt->execute();
                safe_stmt_close($stmt);

                echo "<h3 style='text-align:center; color:green;'>Deposit successful! Redirecting...</h3>";
                echo "<script>
                        setTimeout(function() { 
                            window.location.href = '" . ($role === 'super-admin' ? 'super-admin.php' : 'my-dashboard.php') . "';
                        }, 3000);
                      </script>";
                exit();
            } else {
                $conn->rollback();
                echo "<h3>Error updating balances.</h3>";
            }
        } else {
            echo "<h3>User or Super-Admin not found.</h3>";
        }
    } else {
        echo "<h3>Payment verification failed.</h3>";
    }
    exit();
}

// ✅ Handle POST Webhook
$input = @file_get_contents("php://input");
$event = json_decode($input, true);

if ($event && isset($event['event']) && $event['event'] === 'charge.success') {
    $reference = $event['data']['reference'];
    $amount = $event['data']['amount'] / 100;
    $formattedAmount = formatAmount($amount);
    $email = $event['data']['customer']['email'];

    $stmt = $conn->prepare("SELECT id FROM tbl_deposits WHERE transaction_id = ?");
    $stmt->bind_param("s", $reference);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        safe_stmt_close($stmt);
        http_response_code(200);
        echo "Transaction already processed.";
        exit();
    }
    safe_stmt_close($stmt);

    $stmt = $conn->prepare("SELECT id, username, phone, role FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->bind_result($user_id, $username, $phone, $role);
    $stmt->fetch();
    safe_stmt_close($stmt);

    // Save deposit
    $stmt = $conn->prepare("INSERT INTO tbl_deposits (user_id, amount, email, phone, transaction_id, status) VALUES (?, ?, ?, ?, ?, 'successful')");
    $stmt->bind_param("idsss", $user_id, $amount, $email, $phone, $reference);
    $stmt->execute();
    safe_stmt_close($stmt);

    $msg = "Your deposit of GHS $formattedAmount was successful.";
    $stmt = $conn->prepare("INSERT INTO notifications (user_id, message, is_read) VALUES (?, ?, 0)");
    $stmt->bind_param("is", $user_id, $msg);
    $stmt->execute();
    safe_stmt_close($stmt);

    http_response_code(200);
    echo "Deposit recorded successfully.";
    exit();
}

// 🚫 Invalid request
http_response_code(400);
echo "Invalid event received.";
?>
