<?php

require_once __DIR__ . '/config.php';

require_admin_login();

// Handle POST actions for adding, updating, and deleting resellers

if (is_post()) {

    verify_csrf();

    // Add a new reseller

    if (isset($_POST['add_reseller'])) {

        $name = trim($_POST['name']);

        $email = trim($_POST['email']);

        $password = $_POST['password'];

        $initial_balance = (float)($_POST['balance'] ?? 0);

        if (!empty($name) && !empty($email) && !empty($password)) {

            $password_hash = password_hash($password, PASSWORD_DEFAULT);

            // Generate a unique, secure API key

            $api_key = 'KEY_' . bin2hex(random_bytes(16));

            $stmt = $pdo->prepare("INSERT INTO resellers (name, email, password, balance, api_key) VALUES (?, ?, ?, ?, ?)");

            $stmt->execute([$name, $email, $password_hash, $initial_balance, $api_key]);

            set_flash("Reseller created successfully!", "success");

        } else {

            set_flash("Please fill all required fields.", "danger");

        }

        redirect('resellers.php');

    }

    

    // Update reseller balance

    if (isset($_POST['update_balance'])) {

        $reseller_id = (int)$_POST['reseller_id'];

        $amount = (float)$_POST['amount'];

        $action = $_POST['action'];

        if ($action === 'add') {

            $stmt = $pdo->prepare("UPDATE resellers SET balance = balance + ? WHERE id = ?");

            $stmt->execute([$amount, $reseller_id]);

            set_flash("Balance added successfully.", "success");

        } elseif ($action === 'remove') {

            // Add a check to prevent balance from going below zero

            $stmt = $pdo->prepare("UPDATE resellers SET balance = GREATEST(0, balance - ?) WHERE id = ?");

            $stmt->execute([$amount, $reseller_id]);

            set_flash("Balance removed successfully.", "success");

        }

        redirect('resellers.php');

    }

    // Toggle active status

    if (isset($_POST['toggle_active'])) {

        $reseller_id = (int)$_POST['reseller_id'];

        $stmt = $pdo->prepare("UPDATE resellers SET is_active = NOT is_active WHERE id = ?");

        $stmt->execute([$reseller_id]);

        set_flash("Reseller status updated.", "success");

        redirect('resellers.php');

    }

}

// Fetch all resellers from the database

$resellers = $pdo->query("SELECT * FROM resellers ORDER BY id DESC")->fetchAll();

require_once 'header.php';

?>

<h1 class="h3 mb-4 text-gray-800">Reseller Management</h1>

<?php show_flash(); ?>

<!-- Add New Reseller Card -->

<div class="card shadow-sm mb-4">

    <div class="card-header py-3">

        <h6 class="m-0 fw-bold text-primary"><i class="bi bi-person-plus-fill me-2"></i>Add New Reseller</h6>

    </div>

    <div class="card-body">

        <form method="post" class="row g-3">

            <?php csrf_field(); ?>

            <div class="col-md-3"><input type="text" name="name" class="form-control" placeholder="Full Name" required></div>

            <div class="col-md-3"><input type="email" name="email" class="form-control" placeholder="Email Address" required></div>

            <div class="col-md-3"><input type="password" name="password" class="form-control" placeholder="Password" required></div>

            <div class="col-md-3"><input type="number" step="0.01" name="balance" class="form-control" placeholder="Initial Balance (e.g., 100)"></div>

            <div class="col-12"><button type="submit" name="add_reseller" class="btn btn-success">Create Reseller</button></div>

        </form>

    </div>

</div>

<!-- Existing Resellers Table -->

<div class="card shadow-sm mb-4">

    <div class="card-header py-3"><h6 class="m-0 fw-bold text-primary"><i class="bi bi-people-fill me-2"></i>All Resellers</h6></div>

    <div class="card-body">

        <div class="table-responsive">

            <table class="table table-bordered table-striped table-hover align-middle">

                <thead class="table-light">

                    <tr>

                        <th>ID</th>

                        <th>Name</th>

                        <th>Email</th>

                        <th>Balance</th>

                        <th>API Key</th>

                        <th>Status</th>

                        <th class="text-center">Actions</th>

                    </tr>

                </thead>

                <tbody>

                    <?php foreach ($resellers as $reseller): ?>

                    <tr>

                        <td><?php echo $reseller['id']; ?></td>

                        <td><?php echo h($reseller['name']); ?></td>

                        <td><?php echo h($reseller['email']); ?></td>

                        <td>৳ <?php echo number_format($reseller['balance'], 2); ?></td>

                        <td><code class="user-select-all"><?php echo h($reseller['api_key']); ?></code></td>

                        <td>

                            <?php if ($reseller['is_active']): ?>

                                <span class="badge bg-success">Active</span>

                            <?php else: ?>

                                <span class="badge bg-danger">Inactive</span>

                            <?php endif; ?>

                        </td>

                        <td class="text-center">

                            <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#balanceModal<?php echo $reseller['id']; ?>">Manage Balance</button>

                            <form method="post" class="d-inline">

                                <?php csrf_field(); ?>

                                <input type="hidden" name="reseller_id" value="<?php echo $reseller['id']; ?>">

                                <button type="submit" name="toggle_active" class="btn btn-sm <?php echo $reseller['is_active'] ? 'btn-warning' : 'btn-success'; ?>">

                                    <?php echo $reseller['is_active'] ? 'Deactivate' : 'Activate'; ?>

                                </button>

                            </form>

                        </td>

                    </tr>

                    <?php endforeach; ?>

                </tbody>

            </table>

        </div>

    </div>

</div>

<!-- Balance Management Modals -->

<?php foreach ($resellers as $reseller): ?>

<div class="modal fade" id="balanceModal<?php echo $reseller['id']; ?>" tabindex="-1">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-header">

                <h5 class="modal-title">Manage Balance for <?php echo h($reseller['name']); ?></h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

            </div>

            <form method="post">

                <div class="modal-body">

                    <?php csrf_field(); ?>

                    <input type="hidden" name="reseller_id" value="<?php echo $reseller['id']; ?>">

                    <p>Current Balance: <strong>৳ <?php echo number_format($reseller['balance'], 2); ?></strong></p>

                    <div class="mb-3">

                        <label for="amount<?php echo $reseller['id']; ?>" class="form-label">Amount</label>

                        <input type="number" step="0.01" class="form-control" id="amount<?php echo $reseller['id']; ?>" name="amount" required>

                    </div>

                    <div class="mb-3">

                        <label class="form-label">Action</label>

                        <select name="action" class="form-select">

                            <option value="add">Add to Balance</option>

                            <option value="remove">Remove from Balance</option>

                        </select>

                    </div>

                </div>

                <div class="modal-footer">

                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

                    <button type="submit" name="update_balance" class="btn btn-primary">Update Balance</button>

                </div>

            </form>

        </div>

    </div>

</div>

<?php endforeach; ?>

<?php require_once 'footer.php'; ?>