<?php
// --- LOGIC BLOCK ---
include 'admin-header.php';
require_once '../includes/partner-email-sender.php';

$message = '';
// Reliably get the current logged-in admin's ID from the session, which is fetched in admin-header.php
$current_admin_id = $admin_user['id'] ?? 0;

// --- ACTION HANDLING (ALL POST REQUESTS) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user_id_to_action = intval($_POST['user_id'] ?? 0);

    // --- CREDIT/DEBIT WALLET ---
    if (isset($_POST['credit_funds']) || isset($_POST['deduct_funds'])) {
        $amount = floatval($_POST['amount']);
        $admin_notes = $_POST['admin_notes'] ?? '';
        if (isset($_POST['credit_funds'])) {
            $type = 'Admin Credit'; $sql_op = '+'; $success_msg = 'credited to';
        } else {
            $type = 'Admin Debit'; $sql_op = '-'; $success_msg = 'deducted from';
        }
        if ($sql_op == '-') {
            $balance_check = $conn->query("SELECT wallet_balance FROM users WHERE id = $user_id_to_action")->fetch_assoc()['wallet_balance'];
            if ($balance_check < $amount) {
                $message = '<div class="alert alert-danger">Deduction failed. User only has ₱'.number_format($balance_check, 2).'.</div>';
            }
        }
        if (empty($message)) {
            $conn->begin_transaction();
            try {
                $stmt1 = $conn->prepare("UPDATE users SET wallet_balance = wallet_balance $sql_op ? WHERE id = ?");
                $stmt1->bind_param("di", $amount, $user_id_to_action); $stmt1->execute();
                $stmt2 = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, status, admin_notes) VALUES (?, ?, ?, 'Completed', ?)");
                $stmt2->bind_param("isds", $user_id_to_action, $type, $amount, $admin_notes); $stmt2->execute();
                $conn->commit();
                $message = '<div class="alert alert-success">Successfully '.$success_msg.' ₱'.number_format($amount, 2).' user #'.$user_id_to_action.'.</div>';
            } catch (mysqli_sql_exception $e) { $conn->rollback(); $message = '<div class="alert alert-danger">Error processing transaction.</div>'; }
        }
    }
    // --- USER STATUS MANAGEMENT ---
    elseif (isset($_POST['approve_partner'])) {
        $stmt = $conn->prepare("UPDATE users SET status = 'active' WHERE id = ? AND role LIKE '%_partner'");
        $stmt->bind_param("i", $user_id_to_action);
        if ($stmt->execute()) {
            $message = '<div class="alert alert-success">Partner account approved.</div>';
            sendPartnerNotification($conn, $user_id_to_action, "Your Partner Application has been Approved!", "Congratulations! You can now log in to your Partner Dashboard.");
        }
    }
    elseif (isset($_POST['suspend_user'])) {
        if ($user_id_to_action != $current_admin_id) {
            $stmt = $conn->prepare("UPDATE users SET status = 'suspended' WHERE id = ?");
            $stmt->bind_param("i", $user_id_to_action); $stmt->execute();
            $message = '<div class="alert alert-warning">User account suspended.</div>';
        }
    }
    elseif (isset($_POST['reactivate_user'])) {
        $stmt = $conn->prepare("UPDATE users SET status = 'active' WHERE id = ?");
        $stmt->bind_param("i", $user_id_to_action); $stmt->execute();
        $message = '<div class="alert alert-success">User account reactivated.</div>';
    }
    elseif (isset($_POST['toggle_verify'])) {
        $new_status = intval($_POST['current_status']) == 1 ? 0 : 1;
        $stmt = $conn->prepare("UPDATE users SET is_verified = ? WHERE id = ? AND role LIKE '%_partner'");
        $stmt->bind_param("ii", $new_status, $user_id_to_action);
        if ($stmt->execute()) {
            $message = '<div class="alert alert-success">Partner verification status updated.</div>';
            if ($new_status == 1) {
                sendPartnerNotification($conn, $user_id_to_action, "Congratulations! You are now a Verified Partner!", "Your account has been granted the 'Verified Partner' badge.");
            }
        }
    }
    elseif (isset($_POST['approve_page'])) {
        $stmt = $conn->prepare("UPDATE users SET profile_page_status = 'Active' WHERE id = ?");
        $stmt->bind_param("i", $user_id_to_action);
        $stmt->execute();
        $message = '<div class="alert alert-success">Partner storefront page has been approved.</div>';
    }
}

// --- PRESENTATION BLOCK ---
?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Users</h1>
</div>
<?php echo $message; ?>
<div class="card shadow-sm">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark"><tr><th>Name / Email</th><th>Role</th><th>Status</th><th>Wallet</th><th class="text-center">Actions</th></tr></thead>
                <tbody>
                    <?php
                    $result = $conn->query("SELECT * FROM users ORDER BY FIELD(role, 'admin', 'tour_partner', 'hotel_partner', 'customer'), created_at DESC");
                    while($row = $result->fetch_assoc()):
                    ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($row['full_name']); ?></strong><?php if ($row['is_verified']): ?><span class="verified-badge ms-2"><i class="bi bi-patch-check-fill"></i> Verified</span><?php endif; ?><br><small class="text-muted"><?php echo htmlspecialchars($row['email']); ?></small></td>
                        <td><span class="badge bg-primary"><?php echo ucfirst(str_replace('_', ' ', $row['role'])); ?></span></td>
                        <td><span class="badge bg-<?php if($row['status'] == 'active') echo 'success'; elseif($row['status'] == 'pending') echo 'warning text-dark'; else echo 'danger'; ?>"><?php echo ucfirst($row['status']); ?></span><?php if($row['profile_page_status'] == 'Requested'): ?><span class="badge bg-info ms-1">Page Requested</span><?php endif; ?></td>
                        <td><?php echo ($row['role'] == 'customer') ? '₱'.number_format($row['wallet_balance'], 2) : 'N/A'; ?></td>
                        <td class="text-center">
                            <div class="btn-group">
                                <?php if ($row['id'] == $current_admin_id): ?>
                                    <button class="btn btn-sm btn-light" disabled>(Your Account)</button>
                                <?php else: ?>
                                    <?php if ($row['role'] == 'customer'): ?><button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#walletModal<?php echo $row['id']; ?>">Wallet</button><?php endif; ?>
                                    <?php if (in_array($row['role'], ['tour_partner', 'hotel_partner'])): ?>
                                        <a href="review-documents.php?partner_id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-secondary">Docs</a>
                                        <?php if ($row['status'] == 'pending'): ?><form method="POST" class="d-inline"><input type="hidden" name="user_id" value="<?php echo $row['id']; ?>"><button type="submit" name="approve_partner" class="btn btn-sm btn-success">Approve</button></form>
                                        <?php elseif ($row['status'] == 'active'): ?>
                                            <form method="POST" class="d-inline"><input type="hidden" name="user_id" value="<?php echo $row['id']; ?>"><input type="hidden" name="current_status" value="<?php echo $row['is_verified']; ?>"><button type="submit" name="toggle_verify" class="btn btn-sm <?php echo $row['is_verified'] ? 'btn-info' : 'btn-outline-info'; ?>"><?php echo $row['is_verified'] ? 'Un-verify' : 'Verify'; ?></button></form>
                                        <?php endif; ?>
                                        <?php if ($row['profile_page_status'] == 'Requested'): ?><form method="POST" class="d-inline"><input type="hidden" name="user_id" value="<?php echo $row['id']; ?>"><button type="submit" name="approve_page" class="btn btn-sm btn-info">Approve Page</button></form><?php endif; ?>
                                        <?php if ($row['profile_page_status'] == 'Active'): ?><a href="../partners/<?php echo htmlspecialchars($row['profile_slug']); ?>" class="btn btn-sm btn-outline-success" target="_blank">View Page</a><?php endif; ?>
                                    <?php endif; ?>
                                    <?php if ($row['status'] == 'active'): ?><form method="POST" class="d-inline" onsubmit="return confirm('Suspend user?');"><input type="hidden" name="user_id" value="<?php echo $row['id']; ?>"><button type="submit" name="suspend_user" class="btn btn-sm btn-outline-warning">Suspend</button></form>
                                    <?php elseif ($row['status'] == 'suspended'): ?><form method="POST" class="d-inline"><input type="hidden" name="user_id" value="<?php echo $row['id']; ?>"><button type="submit" name="reactivate_user" class="btn btn-sm btn-outline-success">Reactivate</button></form>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php if ($row['role'] == 'customer'): ?>
                    <div class="modal fade" id="walletModal<?php echo $row['id']; ?>" tabindex="-1">
                        <div class="modal-dialog"><div class="modal-content">
                            <div class="modal-header"><h5 class="modal-title">Manage Wallet for <?php echo htmlspecialchars($row['full_name']); ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                            <div class="modal-body"><ul class="nav nav-tabs" role="tablist"><li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#credit<?php echo $row['id']; ?>">Credit</button></li><li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#deduct<?php echo $row['id']; ?>">Debit</button></li></ul><div class="tab-content p-3 border border-top-0"><div class="tab-pane fade show active" id="credit<?php echo $row['id']; ?>"><form method="POST"><input type="hidden" name="user_id" value="<?php echo $row['id']; ?>"><div class="mb-3"><label>Amount</label><input type="number" name="amount" class="form-control" step="0.01" required></div><div class="mb-3"><label>Notes</label><input type="text" name="admin_notes" class="form-control"></div><button type="submit" name="credit_funds" class="btn btn-success">Credit Wallet</button></form></div><div class="tab-pane fade" id="deduct<?php echo $row['id']; ?>"><form method="POST"><input type="hidden" name="user_id" value="<?php echo $row['id']; ?>"><div class="mb-3"><label>Amount</label><input type="number" name="amount" class="form-control" step="0.01" required></div><div class="mb-3"><label>Notes</label><input type="text" name="admin_notes" class="form-control"></div><button type="submit" name="deduct_funds" class="btn btn-danger">Deduct from Wallet</button></form></div></div></div>
                        </div></div>
                    </div>
                    <?php endif; ?>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php include 'admin-footer.php'; ?>
