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

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

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

$paystack_secret_key = $_ENV['PAYSTACK_SECRET_KEY'];

// Format number nicely
function formatAmount($amount) {
    return number_format($amount, 2);
}

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

// ✅ DEPOSIT VERIFICATION (GET)
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['reference'])) {
    $reference = $_GET['reference'];

    $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);

    file_put_contents("paystack_debug.log", print_r($result, true), FILE_APPEND);

    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'];

        // Check if already processed
        $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);

        // Get user info
        $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);

        $phone = preg_replace("/[^0-9]/", "", $phone);
        if (strlen($phone) == 10) $phone = "+233" . substr($phone, 1);

        // Get super-admin ID
        $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();

            // Credit 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);
            $admin_updated = $stmt->execute();
            safe_stmt_close($stmt);

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

                $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);

                // Notify user
                $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);

                // Notify admin
                $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='color:green;'>Deposit successful! Redirecting...</h3>";
                echo "<script>
                    setTimeout(() => {
                        window.location.href = '" . ($role === 'super-admin' ? 'super-admin.php' : 'my-dashboard.php') . "';
                    }, 3000);
                </script>";
                exit();
            } else {
                $conn->rollback();
                echo "<h3>Failed to update balances.</h3>";
                exit();
            }
        } else {
            echo "<h3>User or Admin not found.</h3>";
            exit();
        }
    } else {
        echo "<h3>Payment verification failed.</h3>";
        exit();
    }
}

// ✅ HANDLE PAYSTACK WEBHOOK
$input = @file_get_contents("php://input");
$event = json_decode($input, true);
file_put_contents("paystack_webhook.log", $input . "\n\n", FILE_APPEND);

if (!$event || !isset($event['event'])) {
    http_response_code(400);
    echo "Invalid webhook event.";
    exit();
}

$eventType = $event['event'];

if ($eventType === 'charge.success') {
    // Deposit via webhook
    $reference = $event['data']['reference'];
    $amount = $event['data']['amount'] / 100;
    $email = $event['data']['customer']['email'];
    $formattedAmount = formatAmount($amount);

    $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 "Already processed.";
        exit();
    }
    safe_stmt_close($stmt);

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

    $phone = preg_replace("/[^0-9]/", "", $phone);
    if (strlen($phone) == 10) $phone = "+233" . substr($phone, 1);

    $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 webhook processed.";
    exit();
}

if ($eventType === 'transfer.success') {
    // ✅ Payout succeeded
    $transfer_code = $event['data']['reference'] ?? '';
    $amount = $event['data']['amount'] / 100;
    $formattedAmount = formatAmount($amount);
    $recipient = $event['data']['recipient']['name'] ?? 'User';

    if (!empty($transfer_code)) {
        // Update status in database
        $stmt = $conn->prepare("UPDATE tbl_payouts SET status = 'Approved', approved_at = NOW() WHERE paystack_transfer_code = ?");
        $stmt->bind_param("s", $transfer_code);
        $stmt->execute();
        safe_stmt_close($stmt);
        
        // Get user information associated with this transfer
        $stmt = $conn->prepare("SELECT p.recipient_name, p.phone, u.email, u.id 
                               FROM tbl_payouts p 
                               JOIN tbl_withdrawals w ON p.recipient_name = (SELECT username FROM users WHERE id = w.user_id)
                               JOIN users u ON w.user_id = u.id
                               WHERE p.paystack_transfer_code = ? LIMIT 1");
        $stmt->bind_param("s", $transfer_code);
        $stmt->execute();
        $stmt->bind_result($username, $phone, $user_email, $user_id);
        $found = $stmt->fetch();
        safe_stmt_close($stmt);
        
        // Send email to user
        if ($found && !empty($user_email)) {
            $user_subject = "Withdrawal Transfer Confirmation";
            $user_headers = "From: no-reply@yourdomain.com\r\nContent-Type: text/html; charset=UTF-8\r\n";
            $user_message = "
            <html><body>
                <h3>Withdrawal Transfer Confirmation</h3>
                <p>Hi <strong>$username</strong>,</p>
                <p>Your withdrawal transfer of <strong>GHS $formattedAmount</strong> has been successfully completed.</p>
                <p>Transfer Code: <strong>$transfer_code</strong></p>
                <p>Date: " . date("F j, Y, g:i a") . "</p>
            </body></html>";
            mail($user_email, $user_subject, $user_message, $user_headers);
            
            // Also send a notification
            $user_notice = "Your withdrawal transfer of GHS $formattedAmount has been successfully completed.";
            $notify_stmt = $conn->prepare("INSERT INTO notifications (user_id, message, is_read, created_at) VALUES (?, ?, 0, NOW())");
            $notify_stmt->bind_param("is", $user_id, $user_notice);
            $notify_stmt->execute();
            safe_stmt_close($notify_stmt);
        }
        
        // Send email to admin
        $admin_email = "justelsmoh@gmail.com";
        $admin_subject = "Transfer Success Notification";
        $admin_headers = "From: no-reply@yourdomain.com\r\nContent-Type: text/html; charset=UTF-8\r\n";
        $admin_message = "
        <html><body>
            <h3>Transfer Success Alert</h3>
            <p>A transfer to <strong>$recipient</strong> was successful.</p>
            <p>Amount: <strong>GHS $formattedAmount</strong></p>
            <p>Transfer Code: <strong>$transfer_code</strong></p>
            <p>Date: " . date("F j, Y, g:i a") . "</p>
        </body></html>";
        mail($admin_email, $admin_subject, $admin_message, $admin_headers);

        file_put_contents("paystack_payouts.log", "✅ Success: $transfer_code - Emails sent to user and admin\n", FILE_APPEND);
        http_response_code(200);
        echo "Payout marked approved and notifications sent.";
        exit();
    }
}

if ($eventType === 'transfer.failed') {
    // ❌ Payout failed
    $transfer_code = $event['data']['reference'] ?? '';
    $amount = $event['data']['amount'] / 100;
    $formattedAmount = formatAmount($amount);
    $recipient = $event['data']['recipient']['name'] ?? 'User';
    $reason = $event['data']['reason'] ?? 'Unknown reason';

    if (!empty($transfer_code)) {
        // Update status in database
        $stmt = $conn->prepare("UPDATE tbl_payouts SET status = 'Rejected' WHERE paystack_transfer_code = ?");
        $stmt->bind_param("s", $transfer_code);
        $stmt->execute();
        safe_stmt_close($stmt);
        
        // Get user information associated with this transfer
        $stmt = $conn->prepare("SELECT p.recipient_name, p.phone, u.email, u.id 
                               FROM tbl_payouts p 
                               JOIN tbl_withdrawals w ON p.recipient_name = (SELECT username FROM users WHERE id = w.user_id)
                               JOIN users u ON w.user_id = u.id
                               WHERE p.paystack_transfer_code = ? LIMIT 1");
        $stmt->bind_param("s", $transfer_code);
        $stmt->execute();
        $stmt->bind_result($username, $phone, $user_email, $user_id);
        $found = $stmt->fetch();
        safe_stmt_close($stmt);
        
        // Credit back user's balance
        if ($found && $user_id) {
            $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->bind_param("di", $amount, $user_id);
            $stmt->execute();
            safe_stmt_close($stmt);
            
            // Update withdrawal record
            $stmt = $conn->prepare("UPDATE tbl_withdrawals SET status = 'failed' 
                                   WHERE user_id = ? AND status = 'approved' 
                                   ORDER BY created_at DESC LIMIT 1");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            safe_stmt_close($stmt);
        }
        
        // Send email to user
        if ($found && !empty($user_email)) {
            $user_subject = "Withdrawal Transfer Failed";
            $user_headers = "From: no-reply@yourdomain.com\r\nContent-Type: text/html; charset=UTF-8\r\n";
            $user_message = "
            <html><body>
                <h3>Withdrawal Transfer Failed</h3>
                <p>Hi <strong>$username</strong>,</p>
                <p>Unfortunately, your withdrawal transfer of <strong>GHS $formattedAmount</strong> has failed.</p>
                <p>Reason: $reason</p>
                <p>Your balance has been restored. Please try again or contact support if you continue to experience issues.</p>
                <p>Transfer Code: <strong>$transfer_code</strong></p>
                <p>Date: " . date("F j, Y, g:i a") . "</p>
            </body></html>";
            mail($user_email, $user_subject, $user_message, $user_headers);
            
            // Also send a notification
            $user_notice = "Your withdrawal transfer of GHS $formattedAmount has failed. Your balance has been restored.";
            $notify_stmt = $conn->prepare("INSERT INTO notifications (user_id, message, is_read, created_at) VALUES (?, ?, 0, NOW())");
            $notify_stmt->bind_param("is", $user_id, $user_notice);
            $notify_stmt->execute();
            safe_stmt_close($notify_stmt);
        }
        
        // Send email to admin
        $admin_email = "justelsmoh@gmail.com";
        $admin_subject = "Transfer Failed Notification";
        $admin_headers = "From: no-reply@yourdomain.com\r\nContent-Type: text/html; charset=UTF-8\r\n";
        $admin_message = "
        <html><body>
            <h3>Transfer Failed Alert</h3>
            <p>A transfer to <strong>$recipient</strong> has failed.</p>
            <p>Amount: <strong>GHS $formattedAmount</strong></p>
            <p>Reason: $reason</p>
            <p>Transfer Code: <strong>$transfer_code</strong></p>
            <p>Date: " . date("F j, Y, g:i a") . "</p>
        </body></html>";
        mail($admin_email, $admin_subject, $admin_message, $admin_headers);

        file_put_contents("paystack_payouts.log", "❌ Failed: $transfer_code - Emails sent to user and admin\n", FILE_APPEND);
        http_response_code(200);
        echo "Payout marked rejected and notifications sent.";
        exit();
    }
}

http_response_code(200);
echo "Unhandled event: $eventType";
?>