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

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$error = "";
$success = "";
$email = ""; // Default value
$user_id = $_SESSION['user_id'];

// Fetch user's email to prefill the form
$stmt = $conn->prepare("SELECT email FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($fetched_email);
if ($stmt->fetch()) {
    $email = $fetched_email;
}
$stmt->close();

// Handle deposit form
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] === 'deposit') {
    $amount = floatval($_POST['amount']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);

    if ($amount <= 0) {
        $error = "Invalid deposit amount.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } elseif (!preg_match('/^\d{10,15}$/', $phone)) {
        $error = "Invalid phone number format.";
    } else {
        $paystack_secret_key = getPaystackSecretKey();

        if (!$paystack_secret_key) {
            die("Error: Paystack secret key is missing.");
        }

        $callback_url = "http://localhost/myfintech/callback.php";

        $data = [
            "email" => $email,
            "amount" => $amount * 100,
            "callback_url" => $callback_url
        ];

        $ch = curl_init("https://api.paystack.co/transaction/initialize");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer {$paystack_secret_key}",
            "Content-Type: application/json"
        ]);

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

        if ($error_curl) {
            $error = "Curl error: " . $error_curl;
        } else {
            $result = json_decode($response, true);
            if (!$result || !isset($result['status']) || !$result['status']) {
                $error = "Payment initialization failed: " . ($result['message'] ?? 'Unknown error');
            } else {
                header("Location: " . $result['data']['authorization_url']);
                exit();
            }
        }
    }
}

// Do NOT close $conn here since we need it for form rendering below
?>

<!-- HTML Part Begins -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Deposit Money</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            color: white;
        }
        .container {
            margin-top: 100px;
        }
        .hero-section {
            background: white;
            color: black;
            padding: 50px;
            border-radius: 10px;
            display: flex;
            justify-content: space-between;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        .hero-text {
            flex: 1;
        }
        .hero-image img {
            width: 80%;
            max-width: 400px;
        }
        .modal-content label {
            color: black;
            font-weight: bold;
        }
    </style>
    <script>
        function showDepositForm() {
            document.getElementById('depositModal').style.display = 'block';
        }
        function closeDepositForm() {
            document.getElementById('depositModal').style.display = 'none';
        }
        function showSendMoneyForm() {
            document.getElementById('sendMoneyModal').style.display = 'block';
        }
        function closeSendMoneyForm() {
            document.getElementById('sendMoneyModal').style.display = 'none';
        }
    </script>
</head>
<body>
    <div class="container">
        <div class="hero-section">
            <div class="hero-text">
                <h1>Secure Online Deposit</h1>
                <button class="btn btn-primary" onclick="showDepositForm()">Make a Deposit</button>
                <button class="btn btn-secondary ms-3" onclick="showSendMoneyForm()">Send Money</button>
            </div>
            <div class="hero-image">
                <img src="images/paydeposit.jpg" alt="Deposit Illustration">
            </div>
        </div>
    </div>

    <!-- Deposit Form -->
    <div id="depositModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background-color:rgba(0,0,0,0.5);">
        <div class="modal-content" style="background:white; padding:20px; margin:10% auto; width:50%; border-radius:8px;">
            <span class="btn-close float-end" onclick="closeDepositForm()">&times;</span>
            <h4>Deposit Money</h4>
            <?php if ($error): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
            <?php endif; ?>
            <form action="deposit.php" method="POST">
                <input type="hidden" name="action" value="deposit">
                <div class="mb-3">
                    <label class="form-label">Amount:</label>
                    <input type="number" name="amount" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Phone:</label>
                    <input type="text" name="phone" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Email:</label>
                    <input type="email" name="email" class="form-control" required value="<?php echo htmlspecialchars($email); ?>">
                </div>
                <button type="submit" class="btn btn-success w-100">Deposit</button>
            </form>
        </div>
    </div>

    <!-- Send Money Form -->
    <div id="sendMoneyModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background-color:rgba(0,0,0,0.5);">
        <div class="modal-content" style="background:white; padding:20px; margin:10% auto; width:50%; border-radius:8px;">
            <span class="btn-close float-end" onclick="closeSendMoneyForm()">&times;</span>
            <h4>Send Money</h4>
            <form action="send_money.php" method="POST">
                <div class="mb-3">
                    <label class="form-label">Select Recipient:</label>
                    <select name="recipient_id" class="form-control" required>
                        <option value="">-- Choose a user --</option>
                        <?php
                        $stmt = $conn->prepare("SELECT id, username FROM users WHERE id != ? AND role != 'super-admin'");
                        $stmt->bind_param("i", $_SESSION['user_id']);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        while ($row = $result->fetch_assoc()) {
                            echo '<option value="' . $row['id'] . '">' . htmlspecialchars($row['username']) . '</option>';
                        }
                        $stmt->close();
                        ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Amount:</label>
                    <input type="number" name="amount" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-success w-100">Transfer</button>
            </form>
        </div>
    </div>
</body>
</html>

<?php $conn->close(); ?>
