<?php
session_start();
require 'config.php';

if (!isset($_SESSION['user_id'])) {
    echo "You must be logged in to withdraw.";
    exit;
}

$user_id = $_SESSION['user_id'];

// Fetch user info
$query = "SELECT balance, username, phone FROM users WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    echo "User not found.";
    exit;
}

$balance = $user['balance'];
$username = $user['username'];
$phone = $user['phone'];

$success_message = "";
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = floatval($_POST['amount']);
    $provider_input = strtolower(trim($_POST['provider']));

    $bank_codes = [
        'mtn' => 'MTN',
        'vodafone' => 'VODAFONE',
        'airteltigo' => 'AIRTELTIGO'
    ];

    if (!array_key_exists($provider_input, $bank_codes)) {
        $error = "Invalid Mobile Money provider.";
    } elseif ($amount <= 0 || $amount > $balance) {
        $error = "Invalid withdrawal amount.";
    } else {
        $paystackSecretKey = getPaystackSecretKey();
        $bank_code = $bank_codes[$provider_input];

        $recipientData = [
            'type' => 'mobile_money',
            'name' => $username,
            'account_number' => $phone,
            'bank_code' => $bank_code,
            'currency' => 'GHS'
        ];

        $recipientResponse = sendPaystackRequest('https://api.paystack.co/transferrecipient', $recipientData, $paystackSecretKey);

        if (!$recipientResponse['status']) {
            $error = "Recipient Creation Failed: " . $recipientResponse['message'];
        } else {
            $recipientCode = $recipientResponse['data']['recipient_code'];

            $transferData = [
                'source' => 'balance',
                'amount' => $amount * 100,
                'recipient' => $recipientCode,
                'reason' => 'User withdrawal request'
            ];

            $transferResponse = sendPaystackRequest('https://api.paystack.co/transfer', $transferData, $paystackSecretKey);

            if (!$transferResponse['status']) {
                $error = "Transfer Failed: " . $transferResponse['message'];
            } else {
                $paystack_transfer_code = $transferResponse['data']['transfer_code'];
                $status = 'approved';

                $withdrawStmt = $conn->prepare("INSERT INTO tbl_withdrawals (user_id, amount, status, created_at) VALUES (?, ?, ?, NOW())");
                $withdrawStmt->bind_param("ids", $user_id, $amount, $status);
                $withdrawStmt->execute();

                $admin_id = 1;
                $payoutStmt = $conn->prepare("INSERT INTO tbl_payouts (admin_id, recipient_name, phone, amount, status, paystack_transfer_code, created_at, approved_at) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())");
                $payoutStmt->bind_param("issdss", $admin_id, $username, $phone, $amount, $status, $paystack_transfer_code);
                $payoutStmt->execute();

                $updateStmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
                $updateStmt->bind_param("di", $amount, $user_id);
                $updateStmt->execute();

                $new_balance_query = "SELECT balance FROM users WHERE id = ?";
                $new_balance_stmt = $conn->prepare($new_balance_query);
                $new_balance_stmt->bind_param("i", $user_id);
                $new_balance_stmt->execute();
                $new_balance = $new_balance_stmt->get_result()->fetch_assoc()['balance'];
                $_SESSION['updated_balance'] = $new_balance;

                $success_message = "Withdrawal of GHS " . number_format($amount, 2) . " was successful! Your new balance is GHS " . number_format($new_balance, 2);

                $user_email_query = $conn->prepare("SELECT email FROM users WHERE id = ?");
                $user_email_query->bind_param("i", $user_id);
                $user_email_query->execute();
                $user_email = $user_email_query->get_result()->fetch_assoc()['email'];

                $user_subject = "Withdrawal Successful";
                $user_headers = "From: no-reply@yourdomain.com\r\nContent-Type: text/html; charset=UTF-8\r\n";
                $user_message = "
                <html><body>
                    <h3>Withdrawal Successful</h3>
                    <p>Hi <strong>$username</strong>,</p>
                    <p>Your withdrawal of <strong>GHS " . number_format($amount, 2) . "</strong> was successful.</p>
                    <p>Your new balance is <strong>GHS " . number_format($new_balance, 2) . "</strong>.</p>
                </body></html>";
                mail($user_email, $user_subject, $user_message, $user_headers);

                $admin_email = "justelsmoh@gmail.com";
                $admin_subject = "User Withdrawal Notification";
                $admin_headers = "From: no-reply@yourdomain.com\r\nContent-Type: text/html; charset=UTF-8\r\n";
                $admin_message = "
                <html><body>
                    <h3>User Withdrawal Alert</h3>
                    <p><strong>$username</strong> (Phone: $phone) made a withdrawal.</p>
                    <p>Amount: <strong>GHS " . number_format($amount, 2) . "</strong></p>
                    <p>Date: " . date("F j, Y, g:i a") . "</p>
                </body></html>";
                mail($admin_email, $admin_subject, $admin_message, $admin_headers);

                // Notifications
                $user_notice = "Your withdrawal of GHS " . number_format($amount, 2) . " was successful.";
                $admin_notice = "$username has made a withdrawal of GHS " . number_format($amount, 2) . ".";

                $insertUserNote = $conn->prepare("INSERT INTO notifications (user_id, message, is_read, created_at) VALUES (?, ?, 0, NOW())");
                $insertUserNote->bind_param("is", $user_id, $user_notice);
                $insertUserNote->execute();

                // Fetch all Super-Admin IDs
                $adminQuery = $conn->query("SELECT id FROM users WHERE role = 'super-admin'");
                while ($adminRow = $adminQuery->fetch_assoc()) {
                    $superAdminId = $adminRow['id'];
                    $insertAdminNote = $conn->prepare("INSERT INTO notifications (user_id, message, is_read, created_at) VALUES (?, ?, 0, NOW())");
                    $insertAdminNote->bind_param("is", $superAdminId, $admin_notice);
                    $insertAdminNote->execute();
                }

                echo "<script>
                    setTimeout(() => window.location.href = 'my-dashboard.php', 3000);
                </script>";
            }
        }
    }
}

function sendPaystackRequest($url, $data, $secretKey) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $secretKey",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        return ['status' => false, 'message' => curl_error($ch)];
    }
    curl_close($ch);
    return json_decode($result, true);
}
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Withdraw Funds</title>
    <link rel="stylesheet" href="style.css">
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            background: #f3f4f6;
            padding: 40px;
            background: url('images/withdrawal.jpg') no-repeat center center/cover;
            height: 100vh;
        }
        .container {
            max-width: 450px;
            background: white;
            padding: 30px;
            margin: auto;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .container h2 {
            margin-bottom: 20px;
            font-size: 24px;
            color: #111827;
        }
        label {
            display: block;
            margin-top: 10px;
            color: #374151;
        }
        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            margin-top: 5px;
        }
        button {
            margin-top: 20px;
            background: #2563eb;
            color: white;
            padding: 12px;
            width: 100%;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
        }
        .message {
            margin-top: 20px;
            padding: 15px;
            border-radius: 6px;
            font-size: 15px;
        }
        .success {
            background-color: #dcfce7;
            color: #166534;
        }
        .error {
            background-color: #fee2e2;
            color: #991b1b;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Withdraw Funds</h2>

    <?php if ($success_message): ?>
        <div class="message success"><?php echo $success_message; ?></div>
    <?php elseif ($error): ?>
        <div class="message error"><?php echo $error; ?></div>
    <?php endif; ?>

    <form method="post">
        <label for="amount">Amount (GHS)</label>
        <input type="number" name="amount" id="amount" required>

        <label for="provider">Select Mobile Money Provider</label>
        <select name="provider" id="provider" required>
            <option value="">-- Choose --</option>
            <option value="mtn">MTN</option>
            <option value="vodafone">Telecel</option>
            <option value="airteltigo">AirtelTigo</option>
        </select>

        <button type="submit">Withdraw</button>
    </form>
</div>

</body>
</html>
