<?php
// admin/users.php
session_start();
include '../config.php';
include 'auth_check.php';
include '../util/audit_logger.php';

// Auth Check handled by auth_check.php

$message = '';
$error = '';

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Suspend/Activate User
    if (isset($_POST['toggle_active_id'])) {
        $id = intval($_POST['toggle_active_id']);
        $status = intval($_POST['new_active_status']);
        $current_user_id = $_SESSION['user_id'] ?? 0;

        if ($id == $current_user_id) {
            $error = "You cannot deactivate your own account.";
        } else {
            $stmt = $conn->prepare("UPDATE users SET is_active = ? WHERE id = ?");
            $stmt->bind_param("ii", $status, $id);
            if ($stmt->execute()) {
                audit_log(
                    $conn,
                    'user_edit',
                    'users',
                    $id,
                    $id,
                    $current_user_id,
                    json_encode(['is_active' => ($status ? 0 : 1)]),
                    json_encode(['is_active' => $status]),
                    "User account " . ($status ? 'activated' : 'deactivated') . "."
                );
                $message = "User account " . ($status ? 'activated' : 'deactivated') . " successfully.";
            } else {
                $error = "Error updating account status.";
            }
        }
    }

    // Delete User
    if (isset($_POST['delete_id'])) {
        $delete_id = intval($_POST['delete_id']);
        $current_user_id = $_SESSION['user_id'] ?? 0;
        if ($delete_id == $current_user_id) {
            $error = "You cannot delete your own account.";
        } else {
            // Get user info before delete for audit
            $del_stmt = $conn->prepare("SELECT org_name, email FROM users WHERE id = ?");
            $del_stmt->bind_param("i", $delete_id);
            $del_stmt->execute();
            $del_user = $del_stmt->get_result()->fetch_assoc();

            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt->bind_param("i", $delete_id);
            if ($stmt->execute()) {
                audit_log(
                    $conn,
                    'user_deleted',
                    'users',
                    $delete_id,
                    $delete_id,
                    $current_user_id,
                    json_encode($del_user),
                    null,
                    "User deleted by admin."
                );
                $message = "User deleted successfully.";
            } else {
                $error = "Error deleting user: " . $conn->error;
            }
        }
    }

    // Toggle Enterprise
    if (isset($_POST['toggle_enterprise_id'])) {
        $id = intval($_POST['toggle_enterprise_id']);
        $status = intval($_POST['new_status']);
        $stmt = $conn->prepare("UPDATE users SET is_enterprise = ? WHERE id = ?");
        $stmt->bind_param("ii", $status, $id);
        if ($stmt->execute()) {
            $admin_id = $_SESSION['user_id'] ?? 0;
            audit_log(
                $conn,
                'user_edit',
                'users',
                $id,
                $id,
                $admin_id,
                json_encode(['is_enterprise' => ($status ? 0 : 1)]),
                json_encode(['is_enterprise' => $status]),
                "Enterprise status " . ($status ? 'enabled' : 'disabled') . "."
            );
            $message = "User enterprise status updated.";
        } else {
            $error = "Error updating status.";
        }
    }

    // Adjust Tokens
    if (isset($_POST['adjust_token_user_id'])) {
        $user_id = intval($_POST['adjust_token_user_id']);
        $amount = intval($_POST['amount']);
        $type = $_POST['type']; // 'add' or 'deduct'
        $reason = trim($_POST['reason']);
        $admin_id = $_SESSION['user_id'];

        if ($type === 'deduct') {
            $amount = -$amount; // Negative for deduction
        }

        if ($amount != 0 && !empty($reason)) {
            $conn->begin_transaction();
            try {
                // record transaction
                $desc = "Manual Adjustment by Admin: " . $reason;
                $stmt = $conn->prepare("INSERT INTO token_transactions (user_id, amount, transaction_type, description, reference_id) VALUES (?, ?, ?, ?, ?)");
                $ttype = ($amount > 0) ? 'credit' : 'debit';
                $ref = "ADM-MANUAL";
                $stmt->bind_param("iisss", $user_id, $amount, $ttype, $desc, $ref);
                $stmt->execute();

                // update sub
                $check = $conn->query("SELECT id FROM user_subscriptions WHERE user_id = $user_id AND status = 'active'");
                if ($check->num_rows > 0) {
                    $conn->query("UPDATE user_subscriptions SET tokens_remaining = tokens_remaining + $amount WHERE user_id = $user_id AND status = 'active'");
                } else {
                    // Create if positive
                    if ($amount > 0) {
                        $conn->query("INSERT INTO user_subscriptions (user_id, package_id, tokens_remaining, status) VALUES ($user_id, 1, $amount, 'active')");
                    }
                }

                $conn->commit();
                audit_log(
                    $conn,
                    'token_adjustment',
                    'user_subscriptions',
                    0,
                    $user_id,
                    $admin_id,
                    null,
                    json_encode(['amount' => $amount, 'type' => $ttype]),
                    $reason
                );
                $message = "Tokens adjusted successfully.";
            } catch (Exception $e) {
                $conn->rollback();
                $error = "Error adjusting tokens: " . $e->getMessage();
            }
        } else {
            $error = "Invalid amount or reason.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Manage Users - SaniBook Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</head>

<body class="bg-slate-100 font-sans text-slate-900">
    <?php include 'navbar.php'; ?>

    <div class="max-w-7xl mx-auto p-6">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-end gap-4 mb-6">
            <h2 class="text-2xl font-bold text-slate-800">Manage Users</h2>

            <div class="flex flex-col md:flex-row gap-3 w-full md:w-auto">
                <!-- Search Form -->
                <form method="GET" class="flex gap-2 w-full md:w-auto">
                    <div class="relative flex-grow md:w-64">
                        <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                            <i class="fa-solid fa-search text-slate-400"></i>
                        </div>
                        <input type="text" name="search"
                            value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>"
                            class="bg-white border border-slate-300 text-slate-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full pl-10 p-2.5"
                            placeholder="Search organization, email, phone...">
                    </div>
                    <button type="submit"
                        class="p-2.5 text-sm font-medium text-white bg-slate-700 rounded-lg border border-slate-700 hover:bg-slate-800 focus:ring-4 focus:outline-none focus:ring-slate-300">
                        Search
                    </button>
                    <?php if (isset($_GET['search']) && !empty($_GET['search'])): ?>
                        <a href="users.php"
                            class="p-2.5 text-sm font-medium text-slate-700 bg-white rounded-lg border border-slate-300 hover:bg-slate-100 focus:ring-4 focus:outline-none focus:ring-slate-200">
                            Clear
                        </a>
                    <?php endif; ?>
                </form>

                <a href="create-user.php"
                    class="px-4 py-2 rounded-lg bg-blue-600 text-white font-bold hover:bg-blue-700 shadow-sm transition-colors text-sm flex items-center justify-center whitespace-nowrap">
                    <i class="fa-solid fa-plus mr-2"></i> Add User
                </a>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="bg-green-100 text-green-700 p-4 rounded-lg mb-6 border border-green-200">
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="bg-red-100 text-red-700 p-4 rounded-lg mb-6 border border-red-200"><?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <div class="bg-white rounded-xl shadow-sm overflow-hidden border border-slate-200">
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead class="bg-slate-50 text-slate-500 uppercase text-xs font-bold tracking-wider">
                        <tr>
                            <th class="p-4 border-b">ID</th>
                            <th class="p-4 border-b">Organization</th>
                            <th class="p-4 border-b">Email</th>
                            <th class="p-4 border-b">Tokens</th>
                            <th class="p-4 border-b">Type</th>
                            <th class="p-4 border-b">Role</th>
                            <th class="p-4 border-b text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php
                        $search_query = "";
                        $params = [];
                        $types = "";

                        if (isset($_GET['search']) && !empty(trim($_GET['search']))) {
                            $search_term = "%" . trim($_GET['search']) . "%";
                            $search_query = " WHERE (org_name LIKE ? OR email LIKE ? OR personal_phone LIKE ? OR company_phone LIKE ?) ";
                            $params = [$search_term, $search_term, $search_term, $search_term];
                            $types = "ssss";
                        }

                        $sql = "SELECT id, org_name, email, role, is_verified, is_enterprise, IFNULL(is_active, 1) as is_active, created_at, 
                                (SELECT tokens_remaining FROM user_subscriptions WHERE user_id = users.id AND status = 'active' LIMIT 1) as tokens 
                                FROM users " . $search_query . " ORDER BY created_at DESC";

                        $stmt = $conn->prepare($sql);
                        if (!$stmt) {
                            echo '<tr><td colspan="8" class="p-4 text-red-500">Database query error. Please try again.</td></tr>';
                        } else {
                            if (!empty($params)) {
                                $stmt->bind_param($types, ...$params);
                            }
                            $stmt->execute();
                            $result = $stmt->get_result();

                            if ($result && $result->num_rows > 0):
                                while ($row = $result->fetch_assoc()):
                                    ?>
                                                <tr class="hover:bg-slate-50 transition-colors">
                                        <td class="p-4 text-sm text-slate-400">#<?= $row['id'] ?></td>
                                        <td class="p-4 font-semibold text-slate-800">
                                                        <?= htmlspecialchars($row['org_name']) ?>
                                                        <?php if ($row['is_verified']): ?>
                                                <i class="fa-solid fa-circle-check text-blue-500 ml-1" title="Verified"></i>
                                                        <?php endif; ?>
                                        </td>
                                        <td class="p-4 text-sm text-slate-600"><?= htmlspecialchars($row['email']) ?></td>
                                        <td class="p-4 text-sm font-bold text-slate-700">
                                                        <?= number_format($row['tokens'] ?? 0) ?>
                                        </td>
                                        <td class="p-4">
                                                        <?php if ($row['is_enterprise']): ?>
                                                <span
                                                    class="px-2 py-1 bg-purple-100 text-purple-700 text-[10px] font-bold uppercase rounded-full">Enterprise</span>
                                                        <?php else: ?>
                                                <span
                                                    class="px-2 py-1 bg-slate-100 text-slate-500 text-[10px] font-bold uppercase rounded-full">Standard</span>
                                                        <?php endif; ?>
                                                        <?php if (!$row['is_active']): ?>
                                                <span
                                                    class="mt-1 block w-fit px-2 py-1 bg-red-100 text-red-700 text-[10px] font-bold uppercase rounded-full">Deactivated</span>
                                          <?php endif; ?>
                                        </td>
                                        <td
                                            class="p-4 text-xs font-bold uppercase <?= ($row['role'] === 'admin') ? 'text-blue-600' : 'text-slate-500'; ?>">
                                           <?= htmlspecialchars($row['role']) ?>
                                        </td>
                                        <td class="p-4 text-right flex justify-end gap-2">
                                            <!-- View Detail -->
                                            <a href="user-detail.php?id=<?= $row['id'] ?>"
                                                class="p-2 bg-green-50 text-green-600 rounded hover:bg-green-100 border border-green-200 inline-block"
                                                title="View Details">
                                                <i class="fa-solid fa-eye"></i>
                                            </a>

                                            <!-- Token Adjust Button -->
                                            <button
                                                onclick="openTokenModal(<?= $row['id'] ?>, '<?= htmlspecialchars($row['org_name'], ENT_QUOTES) ?>')"
                                                class="p-2 bg-blue-50 text-blue-600 rounded hover:bg-blue-100 border border-blue-200"
                                                title="Manage Tokens">
                                                <i class="fa-solid fa-coins"></i>
                                            </button>

                                            <!-- Enterprise Toggle -->
                                            <form method="POST" class="inline">
                                                <input type="hidden" name="toggle_enterprise_id" value="<?= $row['id'] ?>">
                                                <input type="hidden" name="new_status" value="<?= $row['is_enterprise'] ? 0 : 1 ?>">
                                                <button type="submit"
                                                    class="p-2 bg-purple-50 text-purple-600 rounded hover:bg-purple-100 border border-purple-200"
                                                    title="<?= $row['is_enterprise'] ? 'Demote from Enterprise' : 'Promote to Enterprise' ?>">
                                                    <i class="fa-solid fa-building"></i>
                                                </button>
                                            </form>

                                            <!-- Deactivate / Activate -->
                                     <?php if ($row['id'] != ($_SESSION['user_id'] ?? 0)): ?>
                                                <form method="POST" class="inline"
                                                    onsubmit="return confirm('<?= $row['is_active'] ? 'Deactivate this user account? They will not be able to log in.' : 'Re-activate this user account?' ?>');">
                                                    <input type="hidden" name="toggle_active_id" value="<?= $row['id'] ?>">
                                                    <input type="hidden" name="new_active_status"
                                                        value="<?= $row['is_active'] ? 0 : 1 ?>">
                                                    <button type="submit"
                                                        class="p-2 <?= $row['is_active'] ? 'bg-orange-50 text-orange-600 hover:bg-orange-100 border-orange-200' : 'bg-emerald-50 text-emerald-600 hover:bg-emerald-100 border-emerald-200' ?> rounded border inline-block"
                                                        title="<?= $row['is_active'] ? 'Deactivate Account' : 'Activate Account' ?>">
                                                        <i
                                                            class="fa-solid <?= $row['is_active'] ? 'fa-user-slash' : 'fa-user-check' ?>"></i>
                                                    </button>
                                                </form>
                                          <?php endif; ?>

                                            <!-- Delete -->
                                     <?php if ($row['id'] != ($_SESSION['user_id'] ?? 0)): ?>
                                                <form method="POST"
                                                    onsubmit="return confirm('Are you sure you want to permanently delete this user? This cannot be undone.');"
                                                    class="inline">
                                                    <input type="hidden" name="delete_id" value="<?= $row['id'] ?>">
                                                    <button type="submit"
                                                        class="p-2 bg-red-50 text-red-600 rounded hover:bg-red-100 border border-red-200"
                                                        title="Delete">
                                                        <i class="fa-solid fa-trash"></i>
                                                    </button>
                                                </form>
                                          <?php endif; ?>
                                        </td>
                                    </tr>
                             <?php endwhile; else: ?>
                                <tr>
                                    <td colspan="7" class="p-8 text-center text-slate-400">No users found.</td>
                                </tr>
                          <?php endif; ?>
                        <?php } // end else (prepare succeeded) ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Token Modal -->
    <div id="tokenModal" class="fixed inset-0 bg-black/50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-sm">
            <h3 class="text-lg font-bold mb-4">Manage Tokens for <span id="modalUserName" class="text-blue-600"></span>
            </h3>
            <form method="POST">
                <input type="hidden" name="adjust_token_user_id" id="modalUserId">
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-1">Action</label>
                        <select name="type" class="w-full border border-slate-300 rounded p-2">
                            <option value="add">Add Tokens</option>
                            <option value="deduct">Deduct Tokens</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-1">Amount</label>
                        <input type="number" name="amount" required min="1"
                            class="w-full border border-slate-300 rounded p-2">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-1">Reason</label>
                        <input type="text" name="reason" required placeholder="e.g. Bonus, Correction"
                            class="w-full border border-slate-300 rounded p-2">
                    </div>
                    <div class="flex justify-end gap-3 mt-4">
                        <button type="button" onclick="document.getElementById('tokenModal').classList.add('hidden')"
                            class="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded">Cancel</button>
                        <button type="submit"
                            class="px-4 py-2 bg-blue-600 text-white rounded font-bold hover:bg-blue-700">Submit</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openTokenModal(id, name) {
            document.getElementById('modalUserId').value = id;
            document.getElementById('modalUserName').innerText = name;
            document.getElementById('tokenModal').classList.remove('hidden');
        }
    </script>
</body>

</html>
