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

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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'super-admin') {
    header("Location: login.php");
    exit();
}

$error = "";
$email = "";
$user_id = $_SESSION['user_id'];

// Fetch Super-Admin email
$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();

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 {
        require __DIR__ . '/vendor/autoload.php';
        $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
        $dotenv->load();

        $paystack_secret_key = $_ENV['PAYSTACK_SECRET_KEY'];
        if (!$paystack_secret_key) {
            die("Paystack secret key is missing.");
        }

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

        $data = [
            "email" => $email,
            "amount" => $amount * 100,
            "callback_url" => $callback_url,
            "metadata" => [
                "user_id" => $user_id,
                "role" => "super-admin",
                "action" => "admin_deposit"
            ]
        ];

        $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['status']) {
                $error = "Payment initialization failed: " . ($result['message'] ?? 'Unknown error');
            } else {
                header("Location: " . $result['data']['authorization_url']);
                exit();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Super-Admin Deposit</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            color: white;
        }
        .container {
            margin-top: 100px;
        }
        .hero-section {
            background: white;
            color: black;
            padding: 40px;
            border-radius: 12px;
            display: flex;
            justify-content: space-between;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .modal-content label {
            color: black;
            font-weight: bold;
        }
    </style>
    <script>
        function toggleModal(id, show) {
            document.getElementById(id).style.display = show ? 'block' : 'none';
        }
    </script>
</head>
<body>
    <div class="container">
        <div class="hero-section">
            <div>
                <h2>Welcome Super-Admin</h2>
                <p>Choose an action:</p>
                <button class="btn btn-primary" onclick="toggleModal('depositModal', true)">Deposit</button>
                <button class="btn btn-secondary ms-2" onclick="toggleModal('sendMoneyModal', true)">Send Money</button>
                <button class="btn btn-warning ms-2" onclick="toggleModal('bulkTransferModal', true)">Bulk Transfers</button>
            </div>
            <img src="images/paydeposit.jpg" alt="Deposit" style="width:300px;">
        </div>
    </div>

    <!-- Deposit Modal -->
    <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="margin:8% auto; padding:20px; width:50%; background:white; border-radius:10px;">
            <span class="btn-close float-end" onclick="toggleModal('depositModal', false)"></span>
            <h4>Deposit Money (Admin)</h4>
            <?php if ($error): ?>
                <div class="alert alert-danger"><?= $error; ?></div>
            <?php endif; ?>
            <form method="POST">
                <input type="hidden" name="action" value="deposit">
                <div class="mb-3">
                    <label>Amount (GHS)</label>
                    <input type="number" name="amount" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label>Phone Number</label>
                    <input type="text" name="phone" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($email); ?>" required>
                </div>
                <button type="submit" class="btn btn-success w-100">Proceed to Paystack</button>
            </form>
        </div>
    </div>

    <!-- Send Money Modal -->
    <div id="sendMoneyModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5);">
        <div class="modal-content" style="margin:8% auto; padding:20px; width:50%; background:white; border-radius:10px;">
            <span class="btn-close float-end" onclick="toggleModal('sendMoneyModal', false)"></span>
            <h4>Send Money to One User</h4>
            <form action="send_money_admin.php" method="POST">
                <div class="mb-3">
                    <label>Select User</label>
                    <select name="recipient_id" class="form-control" required>
                        <option value="">Choose user</option>
                        <?php
                        $users = $conn->query("SELECT id, username FROM users WHERE role != 'super-admin'");
                        while ($row = $users->fetch_assoc()) {
                            echo "<option value='{$row['id']}'>" . htmlspecialchars($row['username']) . "</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label>Amount (GHS)</label>
                    <input type="number" name="amount" class="form-control" required>
                </div>
                <button class="btn btn-primary w-100">Send Money</button>
            </form>
        </div>
    </div>

    <!-- Bulk Transfer Modal -->
    <div id="bulkTransferModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5);">
        <div class="modal-content" style="margin:5% auto; padding:20px; width:80%; max-height:90vh; overflow:auto; background:white; border-radius:10px;">
            <span class="btn-close float-end" onclick="toggleModal('bulkTransferModal', false)"></span>
            <h4>Bulk Transfers</h4>
            <form action="bulk_transfer.php" method="POST">
                <table class="table table-bordered">
                    <thead><tr><th>Select</th><th>Username</th><th>Email</th><th>Phone</th></tr></thead>
                    <tbody>
                        <?php
                        $allUsers = $conn->query("SELECT id, username, email, phone FROM users WHERE role != 'super-admin'");
                        while ($user = $allUsers->fetch_assoc()) {
                            echo "<tr>
                                    <td><input type='checkbox' name='user_ids[]' value='{$user['id']}'></td>
                                    <td>" . htmlspecialchars($user['username']) . "</td>
                                    <td>" . htmlspecialchars($user['email']) . "</td>
                                    <td>" . htmlspecialchars($user['phone']) . "</td>
                                  </tr>";
                        }
                        ?>
                    </tbody>
                </table>
                <div class="mb-3">
                    <label>Amount Per User (GHS)</label>
                    <input type="number" name="amount" class="form-control" required>
                </div>
                <button class="btn btn-warning w-100">Send to Selected</button>
            </form>
        </div>
    </div>
</body>
</html>

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