<?php
require_once __DIR__ . "/../includes/admin_auth.php"; // Must be first
require_once '../includes/db.php';

// ==========================
// DELETE USER (SAFE HANDLING)
// ==========================
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['delete_user_id'])) {

    $delete_id = intval($_POST['delete_user_id']);

    // Optional: prevent deleting yourself (recommended)
    if ($delete_id > 0) {

        // Delete related account first (if exists)
        $stmt1 = $conn->prepare("DELETE FROM accounts WHERE user_id = ?");
        $stmt1->bind_param("i", $delete_id);
        $stmt1->execute();

        // Delete user
        $stmt2 = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt2->bind_param("i", $delete_id);
        $stmt2->execute();

        header("Location: users.php?msg=deleted");
        exit;
    }
}

// ==========================
// SEARCH
// ==========================
$search = $_GET['search'] ?? '';

$sql = "
    SELECT 
        u.id,
        u.first_name,
        u.last_name,
        u.email,
        u.profile_photo,
        u.status,
        a.account_number,
        a.balance,
        a.currency
    FROM users u
    LEFT JOIN accounts a ON u.id = a.user_id
    WHERE u.role = 'user'
";

$params = [];
$types = "";

if (!empty($search)) {
    $sql .= " AND (
        u.first_name LIKE ? OR
        u.last_name LIKE ? OR
        u.email LIKE ? OR
        a.account_number LIKE ?
    )";

    $searchTerm = "%$search%";
    $params = [$searchTerm, $searchTerm, $searchTerm, $searchTerm];
    $types = "ssss";
}

$sql .= " ORDER BY u.id DESC";

$stmt = $conn->prepare($sql);

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

ob_start();
?>

<div class="main-content">

    <h2 class="page-title">Users Overview</h2>

    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'deleted'): ?>
        <div class="alert success">User deleted successfully.</div>
    <?php endif; ?>

    <!-- SEARCH -->
    <div class="panel">

        <form method="GET" class="filter-form">

            <input type="text" name="search"
                   placeholder="Search name, email, account..."
                   value="<?= htmlspecialchars($search) ?>">

            <button type="submit" class="btn-small">Search</button>

        </form>

    </div>

    <!-- USERS TABLE -->
    <div class="panel">

        <table class="table">

            <thead>
                <tr>
                    <th>Photo</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Account #</th>
                    <th>Balance</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>

            <tbody>

                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($user = $result->fetch_assoc()): ?>

                        <tr>

                            <td>
                                <img src="../uploads/profile_photos/<?= htmlspecialchars($user['profile_photo'] ?? 'default_profile.png') ?>"
                                     style="width:40px;height:40px;border-radius:50%;">
                            </td>

                            <td>
                                <?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>
                            </td>

                            <td><?= htmlspecialchars($user['email']) ?></td>

                            <td><?= htmlspecialchars($user['account_number'] ?? 'N/A') ?></td>

                            <td>
                                <?= htmlspecialchars($user['currency'] ?? 'USD') ?>
                                <?= number_format($user['balance'] ?? 0, 2) ?>
                            </td>

                            <td>
                                <span class="status <?= htmlspecialchars($user['status']) ?>">
                                    <?= ucfirst($user['status']) ?>
                                </span>
                            </td>

                            <td style="display:flex; gap:5px;">

                                <!-- EDIT -->
                                <a class="btn-small"
                                   href="edit_user.php?id=<?= $user['id'] ?>">
                                   Edit
                                </a>

                                <!-- CREDIT -->
                                <a class="btn-small success"
                                   href="credit_user.php?user_id=<?= $user['id'] ?>">
                                   Credit
                                </a>

                                <!-- DELETE (SAFE FORM) -->
                                <form method="POST"
                                      onsubmit="return confirm('Are you sure you want to delete this user?');">

                                    <input type="hidden" name="delete_user_id" value="<?= $user['id'] ?>">

                                    <button type="submit" class="btn-small danger">
                                        Delete
                                    </button>

                                </form>

                            </td>

                        </tr>

                    <?php endwhile; ?>
                <?php else: ?>

                    <tr>
                        <td colspan="7">No users found.</td>
                    </tr>

                <?php endif; ?>

            </tbody>

        </table>

    </div>

</div>

<?php
$content = ob_get_clean();
$page_title = "Users";
include '../components/admin_layout.php';
?>