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

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

$user_id = intval($_GET['id'] ?? 0);
if ($user_id <= 0) {
    header("Location: users.php");
    exit;
}

// Handle EDIT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $admin_id = $_SESSION['user_id'] ?? 0;

    if ($_POST['action'] === 'edit_user') {
        // Get old values for audit
        $old_stmt = $conn->prepare("SELECT org_name, email, phone, bio, role, is_enterprise, county, website, counties, service_chains, enabling_pillars, org_sector FROM users WHERE id = ?");
        $old_stmt->bind_param("i", $user_id);
        $old_stmt->execute();
        $old_user = $old_stmt->get_result()->fetch_assoc();

        $user_type_edit = trim($_POST['user_type'] ?? 'organization');
        $salutation = trim($_POST['salutation'] ?? '');
        $personal_name = trim($_POST['personal_name'] ?? '');
        $personal_email = trim($_POST['personal_email'] ?? '');
        $personal_phone = trim($_POST['personal_phone'] ?? '');
        $company_email = trim($_POST['company_email'] ?? '');
        $company_phone = trim($_POST['company_phone'] ?? '');
        $designation = trim($_POST['designation'] ?? '');
        $org_name = trim($_POST['org_name'] ?? '');
        // For individuals, copy personal_name into org_name as display name
        if ($user_type_edit === 'individual' && !empty($personal_name)) {
            $org_name = $personal_name;
        }
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $bio = trim($_POST['bio'] ?? '');
        $role = $_POST['role'] ?? 'user';
        $is_enterprise = isset($_POST['is_enterprise']) ? 1 : 0;
        $website = trim($_POST['website'] ?? '');

        // JSON array fields
        $counties_arr = $_POST['counties'] ?? [];
        $county = $counties_arr[0] ?? trim($_POST['county'] ?? '');
        $counties_json = json_encode($counties_arr);
        $service_chains_json = json_encode($_POST['service_chains'] ?? []);
        $enabling_pillars_json = json_encode($_POST['enabling_pillars'] ?? []);
        $org_sector_json = isset($_POST['org_sector']) ? json_encode($_POST['org_sector']) : null;

        $stmt = $conn->prepare("UPDATE users SET user_type=?, salutation=?, org_name=?, personal_email=?, personal_phone=?, company_email=?, company_phone=?, designation=?, email=?, bio=?, role=?, is_enterprise=?, county=?, website=?, counties=?, service_chains=?, enabling_pillars=?, org_sector=? WHERE id=?");
        $stmt->bind_param("sssssssssssississsi", $user_type_edit, $salutation, $org_name, $personal_email, $personal_phone, $company_email, $company_phone, $designation, $email, $bio, $role, $is_enterprise, $county, $website, $counties_json, $service_chains_json, $enabling_pillars_json, $org_sector_json, $user_id);
        if ($stmt->execute()) {
            $new_values = [
                'org_name' => $org_name, 'email' => $email, 'phone' => $phone,
                'bio' => $bio, 'role' => $role, 'is_enterprise' => $is_enterprise,
                'county' => $county, 'website' => $website,
                'counties' => $counties_json, 'service_chains' => $service_chains_json,
                'enabling_pillars' => $enabling_pillars_json, 'org_sector' => $org_sector_json
            ];
            audit_log($conn, 'user_edit', 'users', $user_id, $user_id, $admin_id,
                json_encode($old_user), json_encode($new_values),
                "User profile updated by admin."
            );
            $message = "User updated successfully.";
        } else {
            $error = "Error updating user: " . $conn->error;
        }
    }

    if ($_POST['action'] === 'change_package') {
        $new_package_id = intval($_POST['package_id']);
        // Get old subscription
        $old_sub = $conn->query("SELECT us.*, sp.name as pkg_name FROM user_subscriptions us LEFT JOIN subscription_packages sp ON us.package_id = sp.id WHERE us.user_id = $user_id AND us.status = 'active' LIMIT 1")->fetch_assoc();
        
        // Get new package info
        $new_pkg = $conn->query("SELECT name, token_amount FROM subscription_packages WHERE id = $new_package_id")->fetch_assoc();

        $conn->begin_transaction();
        try {
            // Deactivate old subscription
            $conn->query("UPDATE user_subscriptions SET status = 'expired' WHERE user_id = $user_id AND status = 'active'");
            
            // Create new subscription
            $tokens = $new_pkg['token_amount'] ?? 0;
            $stmt = $conn->prepare("INSERT INTO user_subscriptions (user_id, package_id, tokens_remaining, status, start_date, end_date) VALUES (?, ?, ?, 'active', CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 YEAR))");
            $stmt->bind_param("iii", $user_id, $new_package_id, $tokens);
            $stmt->execute();

            // Record transaction
            $desc = "Package changed to " . ($new_pkg['name'] ?? 'Unknown') . " by admin";
            $stmt2 = $conn->prepare("INSERT INTO token_transactions (user_id, amount, transaction_type, description, reference_id) VALUES (?, ?, 'credit', ?, 'ADM-PKG-CHANGE')");
            $stmt2->bind_param("iis", $user_id, $tokens, $desc);
            $stmt2->execute();

            audit_log($conn, 'subscription_change', 'user_subscriptions', $user_id, $user_id, $admin_id,
                json_encode(['package' => $old_sub['pkg_name'] ?? 'None', 'tokens' => $old_sub['tokens_remaining'] ?? 0]),
                json_encode(['package' => $new_pkg['name'], 'tokens' => $tokens]),
                "Subscription package changed by admin."
            );
            $conn->commit();
            $message = "Subscription changed to " . htmlspecialchars($new_pkg['name']) . " with $tokens tokens.";
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Error: " . $e->getMessage();
        }
    }

    if ($_POST['action'] === 'reset_password') {
        $new_password = bin2hex(random_bytes(4)); // 8-char random password
        $hash = password_hash($new_password, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
        $stmt->bind_param("si", $hash, $user_id);
        if ($stmt->execute()) {
            audit_log($conn, 'password_reset', 'users', $user_id, $user_id, $admin_id,
                null, null, "Password reset by admin.");
            $message = "Password reset to: <strong class='font-mono bg-yellow-100 px-2 py-1 rounded'>" . htmlspecialchars($new_password) . "</strong> — share this with the user securely.";
        } else {
            $error = "Error resetting password.";
        }
    }

    if ($_POST['action'] === 'update_categories') {
        $categories = isset($_POST['categories']) ? json_encode(array_map('intval', $_POST['categories'])) : '[]';
        $stmt = $conn->prepare("UPDATE users SET categories = ? WHERE id = ?");
        $stmt->bind_param("si", $categories, $user_id);
        if ($stmt->execute()) {
            audit_log($conn, 'user_edit', 'users', $user_id, $user_id, $admin_id,
                null, json_encode(['categories' => $categories]),
                "User categories updated by admin."
            );
            $message = "Categories updated.";
        } else {
            $error = "Error updating categories.";
        }
    }
}

// Fetch User
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    header("Location: users.php");
    exit;
}

// Fetch active subscription
$sub = $conn->query("SELECT us.*, sp.name as pkg_name, sp.price, sp.token_amount as pkg_tokens
                      FROM user_subscriptions us 
                      LEFT JOIN subscription_packages sp ON us.package_id = sp.id 
                      WHERE us.user_id = $user_id AND us.status = 'active' 
                      LIMIT 1")->fetch_assoc();

// Fetch subscription history
$sub_history = $conn->query("SELECT us.*, sp.name as pkg_name
                              FROM user_subscriptions us 
                              LEFT JOIN subscription_packages sp ON us.package_id = sp.id 
                              WHERE us.user_id = $user_id 
                              ORDER BY us.created_at DESC LIMIT 10");

// Fetch transactions
$transactions = $conn->query("SELECT * FROM token_transactions WHERE user_id = $user_id ORDER BY created_at DESC LIMIT 20");

// Fetch orders
$orders = $conn->query("SELECT o.*, sp.name as pkg_name FROM token_orders o LEFT JOIN subscription_packages sp ON o.package_id = sp.id WHERE o.user_id = $user_id ORDER BY o.created_at DESC LIMIT 20");

// Fetch available packages
$packages = $conn->query("SELECT * FROM subscription_packages WHERE is_active = 1 ORDER BY price ASC");

// Fetch categories
$categories_result = $conn->query("SELECT * FROM categories ORDER BY name ASC");
$user_categories = json_decode($user['categories'] ?? '[]', true) ?: [];

// Fetch submissions count
$submissions_count = $conn->query("SELECT COUNT(*) as cnt FROM submissions WHERE user_id = $user_id")->fetch_assoc()['cnt'] ?? 0;

// Fetch audit history
$audit_history = get_user_audit_history($conn, $user_id, 30);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>User: <?= htmlspecialchars($user['org_name']) ?> - 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" />
    <style>
        body { font-family: 'Inter', system-ui, sans-serif; }
    </style>
</head>

<body class="bg-gradient-to-br from-slate-50 to-blue-50/30 min-h-screen">
    <?php include 'navbar.php'; ?>

    <div class="max-w-7xl mx-auto p-6">
        <!-- Back + Title -->
        <div class="flex items-center gap-4 mb-6">
            <a href="users.php" class="p-2 bg-white rounded-lg shadow-sm hover:bg-slate-50 border border-slate-200">
                <i class="fa-solid fa-arrow-left text-slate-600"></i>
            </a>
            <div>
                <h2 class="text-2xl font-bold text-slate-900 flex items-center gap-3">
                    <?= htmlspecialchars($user['org_name']) ?>
                    <?php if ($user['is_verified'] ?? false): ?>
                        <i class="fa-solid fa-circle-check text-blue-500" title="Verified"></i>
                    <?php endif; ?>
                    <?php if ($user['is_enterprise'] ?? false): ?>
                        <span class="px-2 py-1 bg-purple-100 text-purple-700 text-xs font-bold uppercase rounded-full">Enterprise</span>
                    <?php endif; ?>
                </h2>
                <p class="text-slate-500 text-sm">User #<?= $user['id'] ?> · Joined <?= date('M d, Y', strtotime($user['created_at'])) ?></p>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="bg-green-50 border-l-4 border-green-500 text-green-800 p-4 rounded-lg mb-6 flex items-center gap-3 shadow-sm">
                <i class="fa-solid fa-check-circle text-xl"></i>
                <span class="font-medium"><?= $message ?></span>
            </div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="bg-red-50 border-l-4 border-red-500 text-red-800 p-4 rounded-lg mb-6 flex items-center gap-3 shadow-sm">
                <i class="fa-solid fa-exclamation-triangle text-xl"></i>
                <span class="font-medium"><?= htmlspecialchars($error) ?></span>
            </div>
        <?php endif; ?>

        <!-- Quick Stats -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow-sm p-4 border-l-4 border-blue-500">
                <p class="text-slate-500 text-xs font-semibold uppercase">Current Package</p>
                <p class="text-lg font-bold text-blue-900 mt-1"><?= htmlspecialchars($sub['pkg_name'] ?? 'None') ?></p>
            </div>
            <div class="bg-white rounded-xl shadow-sm p-4 border-l-4 border-green-500">
                <p class="text-slate-500 text-xs font-semibold uppercase">Tokens Remaining</p>
                <p class="text-lg font-bold text-green-900 mt-1"><?= number_format(floatval($sub['tokens_remaining'] ?? 0)) ?></p>
            </div>
            <div class="bg-white rounded-xl shadow-sm p-4 border-l-4 border-yellow-500">
                <p class="text-slate-500 text-xs font-semibold uppercase">Submissions</p>
                <p class="text-lg font-bold text-yellow-900 mt-1"><?= number_format($submissions_count) ?></p>
            </div>
            <div class="bg-white rounded-xl shadow-sm p-4 border-l-4 border-cyan-500">
                <p class="text-slate-500 text-xs font-semibold uppercase">Role</p>
                <p class="text-lg font-bold text-cyan-900 mt-1 uppercase"><?= htmlspecialchars($user['role'] ?? 'user') ?></p>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Left Column: User Edit Form -->
            <div class="lg:col-span-1 space-y-6">
                <!-- Edit Profile -->
                <div class="bg-white rounded-xl shadow-sm p-6 border border-slate-200">
                    <h3 class="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-user-edit text-blue-500"></i> Edit Profile
                    </h3>
                    <?php
                    $admin_decoded_counties = json_decode($user['counties'] ?? '[]', true) ?: [];
                    $admin_decoded_service = json_decode($user['service_chains'] ?? '[]', true) ?: [];
                    $admin_decoded_pillars = json_decode($user['enabling_pillars'] ?? '[]', true) ?: [];
                    $admin_org_sector = json_decode($user['org_sector'] ?? '{}', true) ?: [];
                    ?>
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="action" value="edit_user">

                        <!-- User Type Toggle -->
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1">Account Type</label>
                            <select name="user_type" id="admin-user-type" onchange="toggleAdminUserType()"
                                class="w-full border border-slate-300 rounded-lg p-2.5 text-sm">
                                <option value="organization" <?= ($user['user_type'] ?? 'organization') === 'organization' ? 'selected' : '' ?>>Organization</option>
                                <option value="individual" <?= ($user['user_type'] ?? 'organization') === 'individual' ? 'selected' : '' ?>>Individual</option>
                            </select>
                        </div>

                        <!-- Representative / Individual Details -->
                        <div class="bg-slate-50 rounded-lg p-3 space-y-2 border border-slate-100">
                            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Representative Details</p>
                            <div class="grid grid-cols-3 gap-2">
                                <select name="salutation" class="border border-slate-300 rounded-lg p-2 text-sm">
                                    <?php foreach (['Mr.','Ms.','Dr.','Prof.'] as $sal): ?>
                                        <option value="<?= $sal ?>" <?= ($user['salutation'] ?? '') === $sal ? 'selected' : '' ?>><?= $sal ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <input type="text" name="personal_name" value="<?= htmlspecialchars($user['org_name'] ?? '') ?>"
                                    class="col-span-2 border border-slate-300 rounded-lg p-2 text-sm" placeholder="Full Name">
                            </div>
                            <div class="grid grid-cols-2 gap-2">
                                <input type="email" name="personal_email" value="<?= htmlspecialchars($user['personal_email'] ?? '') ?>"
                                    class="border border-slate-300 rounded-lg p-2 text-sm" placeholder="Personal Email">
                                <input type="tel" name="personal_phone" value="<?= htmlspecialchars($user['personal_phone'] ?? '') ?>"
                                    class="border border-slate-300 rounded-lg p-2 text-sm" placeholder="Personal Phone">
                            </div>
                        </div>

                        <!-- Organization Section -->
                        <div id="admin-org-section" class="<?= ($user['user_type'] ?? 'organization') === 'individual' ? 'hidden' : '' ?>">
                            <div>
                                <label class="block text-sm font-bold text-slate-700 mb-1">Organization Name</label>
                                <input type="text" name="org_name" value="<?= htmlspecialchars($user['org_name'] ?? '') ?>"
                                    class="w-full border border-slate-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            </div>
                            <div class="grid grid-cols-2 gap-2 mt-2">
                                <input type="email" name="company_email" value="<?= htmlspecialchars($user['company_email'] ?? '') ?>"
                                    class="border border-slate-300 rounded-lg p-2 text-sm" placeholder="Company Email">
                                <input type="tel" name="company_phone" value="<?= htmlspecialchars($user['company_phone'] ?? '') ?>"
                                    class="border border-slate-300 rounded-lg p-2 text-sm" placeholder="Company Phone">
                            </div>
                            <div class="mt-2">
                                <input type="text" name="designation" value="<?= htmlspecialchars($user['designation'] ?? '') ?>"
                                    class="w-full border border-slate-300 rounded-lg p-2 text-sm" placeholder="Designation / Role">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1">Email</label>
                            <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required
                                class="w-full border border-slate-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1">Phone</label>
                            <input type="text" name="phone" value="<?= htmlspecialchars($user['phone'] ?? $user['mobile'] ?? '') ?>"
                                class="w-full border border-slate-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                placeholder="+254 7XX XXX XXX">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1">Website</label>
                            <input type="text" name="website" value="<?= htmlspecialchars($user['website'] ?? '') ?>"
                                class="w-full border border-slate-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                placeholder="https://...">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1">Counties</label>
                            <div class="p-2.5 border border-slate-300 rounded-lg bg-slate-50 max-h-36 overflow-y-auto text-xs space-y-1">
                                <?php
                                $all_counties = ["Mombasa", "Kwale", "Kilifi", "Tana River", "Lamu", "Taita Taveta", "Garissa", "Wajir", "Mandera", "Marsabit", "Isiolo", "Meru", "Tharaka-Nithi", "Embu", "Kitui", "Machakos", "Makueni", "Nyandarua", "Nyeri", "Kirinyaga", "Murang'a", "Kiambu", "Turkana", "West Pokot", "Samburu", "Trans-Nzoia", "Uasin Gishu", "Elgeyo-Marakwet", "Nandi", "Baringo", "Laikipia", "Nakuru", "Narok", "Kajiado", "Kericho", "Bomet", "Kakamega", "Vihiga", "Bungoma", "Busia", "Siaya", "Kisumu", "Homa Bay", "Migori", "Kisii", "Nyamira", "Nairobi"];
                                foreach ($all_counties as $c):
                                ?>
                                    <label class="flex items-center gap-2">
                                        <input type="checkbox" name="counties[]" value="<?= $c ?>" <?= in_array($c, $admin_decoded_counties) ? 'checked' : '' ?>> <?= $c ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1">Organization Sector / Type</label>
                            <div class="space-y-2">
                                <select id="admin-org-sector" name="org_sector[sector]" onchange="adminUpdateSubTypes()"
                                    class="w-full border border-slate-300 rounded-lg p-2.5 text-sm">
                                    <option value="">Select Sector...</option>
                                    <?php foreach (["Public Sector", "Private Sector", "Civil Society & NGOs", "Financial Institutions", "Research & Academic", "The Users", "Others"] as $sec): ?>
                                        <option value="<?= $sec ?>" <?= ($admin_org_sector['sector'] ?? '') === $sec ? 'selected' : '' ?>><?= $sec ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <select id="admin-org-subtype" name="org_sector[sub_type]" onchange="adminUpdateSpecs()"
                                    class="w-full border border-slate-300 rounded-lg p-2.5 text-sm <?= empty($admin_org_sector['sub_type']) ? 'hidden' : '' ?>">
                                    <option value="">Select Sub-Type...</option>
                                </select>
                                <select id="admin-org-spec" name="org_sector[specialisation]"
                                    class="w-full border border-slate-300 rounded-lg p-2.5 text-sm <?= empty($admin_org_sector['specialisation']) ? 'hidden' : '' ?>">
                                    <option value="">Select Specialisation...</option>
                                </select>
                                <input type="text" id="admin-org-other" name="org_sector[other]"
                                    placeholder="Please specify your sector/type"
                                    value="<?= htmlspecialchars($admin_org_sector['other'] ?? '', ENT_QUOTES) ?>"
                                    class="w-full border border-slate-300 rounded-lg p-2.5 text-sm <?= ($admin_org_sector['sector'] ?? '') === 'Others' ? '' : 'hidden' ?>">
                            </div>
                        </div>
                        <details class="group border border-slate-200 rounded-lg p-2">
                            <summary class="text-xs font-bold text-slate-700 cursor-pointer flex justify-between">
                                Service Chains & Enabling Pillars
                                <i class="fa-solid fa-chevron-down group-open:rotate-180 transition-transform"></i>
                            </summary>
                            <div class="mt-2 space-y-3">
                                <div>
                                    <p class="text-[10px] font-bold text-slate-400 uppercase">Service Chains</p>
                                    <div class="h-24 overflow-y-auto border rounded p-1 text-[11px] space-y-1">
                                        <?php foreach (["Capture & Containment", "Transport", "Emptying", "Disposal", "Treatment", "Reuse & Circular Economy"] as $sc): ?>
                                            <label class="flex items-center gap-2"><input type="checkbox" name="service_chains[]" value="<?= $sc ?>" <?= in_array($sc, $admin_decoded_service) ? 'checked' : '' ?>> <?= $sc ?></label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <div>
                                    <p class="text-[10px] font-bold text-slate-400 uppercase">Enabling Pillars</p>
                                    <div class="h-24 overflow-y-auto border rounded p-1 text-[11px] space-y-1">
                                        <?php foreach (["Financing", "Governance", "Research & Learning", "Collaboration", "Menstrual Health Management", "Capacity Building"] as $ep): ?>
                                            <label class="flex items-center gap-2"><input type="checkbox" name="enabling_pillars[]" value="<?= $ep ?>" <?= in_array($ep, $admin_decoded_pillars) ? 'checked' : '' ?>> <?= $ep ?></label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </details>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1">Bio</label>
                            <textarea name="bio" rows="3"
                                class="w-full border border-slate-300 rounded-lg p-2.5 text-sm resize-none"
                                placeholder="Short bio..."><?= htmlspecialchars($user['bio'] ?? '') ?></textarea>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm font-bold text-slate-700 mb-1">Role</label>
                                <select name="role" class="w-full border border-slate-300 rounded-lg p-2.5 text-sm">
                                    <option value="user" <?= ($user['role'] ?? '') === 'user' ? 'selected' : '' ?>>User</option>
                                    <option value="member" <?= ($user['role'] ?? '') === 'member' ? 'selected' : '' ?>>Member</option>
                                    <option value="admin" <?= ($user['role'] ?? '') === 'admin' ? 'selected' : '' ?>>Admin</option>
                                </select>
                            </div>
                            <div class="flex items-end">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="checkbox" name="is_enterprise" value="1" <?= ($user['is_enterprise'] ?? 0) ? 'checked' : '' ?>
                                        class="w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500">
                                    <span class="text-sm font-bold text-slate-700">Enterprise</span>
                                </label>
                            </div>
                        </div>
                        <button type="submit" class="w-full py-2.5 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 transition-colors text-sm">
                            <i class="fa-solid fa-save mr-1"></i> Save Changes
                        </button>
                    </form>
                </div>

                <!-- Password Reset -->
                <div class="bg-white rounded-xl shadow-sm p-6 border border-slate-200">
                    <h3 class="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-key text-yellow-500"></i> Password
                    </h3>
                    <form method="POST" onsubmit="return confirm('Generate a new random password for this user?');">
                        <input type="hidden" name="action" value="reset_password">
                        <button type="submit" class="w-full py-2.5 bg-yellow-500 text-white rounded-lg font-bold hover:bg-yellow-600 transition-colors text-sm">
                            <i class="fa-solid fa-rotate mr-1"></i> Reset Password
                        </button>
                    </form>
                </div>

                <!-- Categories -->
                <div class="bg-white rounded-xl shadow-sm p-6 border border-slate-200">
                    <h3 class="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-tags text-green-500"></i> Categories
                    </h3>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_categories">
                        <div class="space-y-2 max-h-48 overflow-y-auto">
                            <?php
                            if ($categories_result && $categories_result->num_rows > 0):
                                while ($cat = $categories_result->fetch_assoc()):
                            ?>
                                <label class="flex items-center gap-2 cursor-pointer p-1 hover:bg-slate-50 rounded">
                                    <input type="checkbox" name="categories[]" value="<?= $cat['id'] ?>"
                                        <?= in_array($cat['id'], $user_categories) ? 'checked' : '' ?>
                                        class="w-4 h-4 rounded border-slate-300 text-green-600 focus:ring-green-500">
                                    <span class="text-sm text-slate-700"><?= htmlspecialchars($cat['name']) ?></span>
                                </label>
                            <?php
                                endwhile;
                            else:
                            ?>
                                <p class="text-sm text-slate-400">No categories found.</p>
                            <?php endif; ?>
                        </div>
                        <button type="submit" class="w-full mt-3 py-2 bg-green-600 text-white rounded-lg font-bold hover:bg-green-700 transition-colors text-sm">
                            <i class="fa-solid fa-save mr-1"></i> Save Categories
                        </button>
                    </form>
                </div>

                <!-- Change Subscription -->
                <div class="bg-white rounded-xl shadow-sm p-6 border border-slate-200">
                    <h3 class="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-box-open text-purple-500"></i> Change Package
                    </h3>
                    <form method="POST" onsubmit="return confirm('Change this user\'s subscription package? Their current tokens will be replaced.');">
                        <input type="hidden" name="action" value="change_package">
                        <select name="package_id" class="w-full border border-slate-300 rounded-lg p-2.5 text-sm mb-3">
                            <?php while ($pkg = $packages->fetch_assoc()): ?>
                                <option value="<?= $pkg['id'] ?>" <?= ($sub['package_id'] ?? 0) == $pkg['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($pkg['name']) ?> — KES <?= number_format($pkg['price']) ?> (<?= number_format($pkg['token_amount']) ?> tokens)
                                </option>
                            <?php endwhile; ?>
                        </select>
                        <button type="submit" class="w-full py-2.5 bg-purple-600 text-white rounded-lg font-bold hover:bg-purple-700 transition-colors text-sm">
                            <i class="fa-solid fa-exchange-alt mr-1"></i> Change Package
                        </button>
                    </form>
                </div>
            </div>

            <!-- Right Column: History -->
            <div class="lg:col-span-2 space-y-6">
                <!-- Transaction History -->
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                    <div class="p-5 border-b border-slate-100">
                        <h3 class="text-lg font-bold text-slate-900 flex items-center gap-2">
                            <i class="fa-solid fa-receipt text-blue-500"></i> Token Transactions
                        </h3>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead class="bg-slate-50 text-slate-500 uppercase text-xs font-bold">
                                <tr>
                                    <th class="p-3">Date</th>
                                    <th class="p-3">Type</th>
                                    <th class="p-3">Amount</th>
                                    <th class="p-3">Description</th>
                                    <th class="p-3">Ref</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php if ($transactions && $transactions->num_rows > 0): ?>
                                    <?php while ($tx = $transactions->fetch_assoc()): ?>
                                        <tr class="hover:bg-slate-50 text-sm">
                                            <td class="p-3 text-slate-500 whitespace-nowrap"><?= date('M d, Y H:i', strtotime($tx['created_at'])) ?></td>
                                            <td class="p-3">
                                                <span class="px-2 py-1 rounded-full text-[10px] font-bold uppercase
                                                    <?= $tx['transaction_type'] === 'credit' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700' ?>">
                                                    <?= $tx['transaction_type'] ?>
                                                </span>
                                            </td>
                                            <td class="p-3 font-bold <?= $tx['amount'] >= 0 ? 'text-green-700' : 'text-red-600' ?>">
                                                <?= $tx['amount'] >= 0 ? '+' : '' ?><?= number_format($tx['amount']) ?>
                                            </td>
                                            <td class="p-3 text-slate-600"><?= htmlspecialchars($tx['description'] ?? '') ?></td>
                                            <td class="p-3 text-slate-400 font-mono text-xs"><?= htmlspecialchars($tx['reference_id'] ?? '') ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="p-6 text-center text-slate-400">No transactions yet.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Order History -->
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                    <div class="p-5 border-b border-slate-100">
                        <h3 class="text-lg font-bold text-slate-900 flex items-center gap-2">
                            <i class="fa-solid fa-shopping-cart text-green-500"></i> Orders
                        </h3>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead class="bg-slate-50 text-slate-500 uppercase text-xs font-bold">
                                <tr>
                                    <th class="p-3">ID</th>
                                    <th class="p-3">Date</th>
                                    <th class="p-3">Package</th>
                                    <th class="p-3">Amount</th>
                                    <th class="p-3">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php if ($orders && $orders->num_rows > 0): ?>
                                    <?php while ($ord = $orders->fetch_assoc()): ?>
                                        <tr class="hover:bg-slate-50 text-sm">
                                            <td class="p-3 text-slate-400">#<?= $ord['id'] ?></td>
                                            <td class="p-3 text-slate-500 whitespace-nowrap"><?= date('M d, Y', strtotime($ord['created_at'])) ?></td>
                                            <td class="p-3 font-semibold text-slate-700"><?= htmlspecialchars($ord['pkg_name'] ?? 'N/A') ?></td>
                                            <td class="p-3 font-bold text-slate-700">KES <?= number_format(floatval($ord['amount_paid'] ?? 0)) ?></td>
                                            <td class="p-3">
                                                <?php
                                                $sc = ['pending' => 'bg-yellow-100 text-yellow-700', 'approved' => 'bg-green-100 text-green-700', 'rejected' => 'bg-red-100 text-red-700'];
                                                $cls = $sc[$ord['status']] ?? 'bg-slate-100 text-slate-700';
                                                ?>
                                                <span class="px-2 py-1 rounded-full text-[10px] font-bold uppercase <?= $cls ?>">
                                                    <?= $ord['status'] ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="p-6 text-center text-slate-400">No orders yet.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Subscription History -->
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                    <div class="p-5 border-b border-slate-100">
                        <h3 class="text-lg font-bold text-slate-900 flex items-center gap-2">
                            <i class="fa-solid fa-history text-purple-500"></i> Subscription History
                        </h3>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead class="bg-slate-50 text-slate-500 uppercase text-xs font-bold">
                                <tr>
                                    <th class="p-3">Package</th>
                                    <th class="p-3">Status</th>
                                    <th class="p-3">Tokens Left</th>
                                    <th class="p-3">Start</th>
                                    <th class="p-3">End</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php if ($sub_history && $sub_history->num_rows > 0): ?>
                                    <?php while ($sh = $sub_history->fetch_assoc()): ?>
                                        <tr class="hover:bg-slate-50 text-sm">
                                            <td class="p-3 font-semibold text-slate-700"><?= htmlspecialchars($sh['pkg_name'] ?? 'N/A') ?></td>
                                            <td class="p-3">
                                                <?php
                                                $ss = ['active' => 'bg-green-100 text-green-700', 'expired' => 'bg-slate-100 text-slate-500', 'cancelled' => 'bg-red-100 text-red-700', 'pending' => 'bg-yellow-100 text-yellow-700'];
                                                $scls = $ss[$sh['status']] ?? 'bg-slate-100 text-slate-500';
                                                ?>
                                                <span class="px-2 py-1 rounded-full text-[10px] font-bold uppercase <?= $scls ?>">
                                                    <?= $sh['status'] ?>
                                                </span>
                                            </td>
                                            <td class="p-3 font-bold text-slate-700"><?= number_format(floatval($sh['tokens_remaining'] ?? 0)) ?></td>
                                            <td class="p-3 text-slate-500"><?= $sh['start_date'] ? date('M d, Y', strtotime($sh['start_date'])) : '—' ?></td>
                                            <td class="p-3 text-slate-500"><?= $sh['end_date'] ? date('M d, Y', strtotime($sh['end_date'])) : '—' ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="p-6 text-center text-slate-400">No subscription history.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Audit Trail -->
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                    <div class="p-5 border-b border-slate-100">
                        <h3 class="text-lg font-bold text-slate-900 flex items-center gap-2">
                            <i class="fa-solid fa-clipboard-list text-orange-500"></i> Audit Trail
                        </h3>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead class="bg-slate-50 text-slate-500 uppercase text-xs font-bold">
                                <tr>
                                    <th class="p-3">Date</th>
                                    <th class="p-3">Action</th>
                                    <th class="p-3">By</th>
                                    <th class="p-3">Note</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php if (!empty($audit_history)): ?>
                                    <?php foreach ($audit_history as $audit): ?>
                                        <tr class="hover:bg-slate-50 text-sm">
                                            <td class="p-3 text-slate-500 whitespace-nowrap"><?= date('M d, H:i', strtotime($audit['created_at'])) ?></td>
                                            <td class="p-3">
                                                <span class="px-2 py-1 bg-orange-100 text-orange-700 rounded-full text-[10px] font-bold uppercase">
                                                    <?= str_replace('_', ' ', $audit['action_type']) ?>
                                                </span>
                                            </td>
                                            <td class="p-3 text-slate-600"><?= htmlspecialchars($audit['admin_name'] ?? 'System') ?></td>
                                            <td class="p-3 text-slate-600 max-w-xs truncate"><?= htmlspecialchars($audit['note'] ?? '—') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="4" class="p-6 text-center text-slate-400">No audit events yet.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        // Org Taxonomy for admin form
        const adminOrgTaxonomy = {
            "Public Sector": {
                "National Government": ["Ministries", "Agencies", "Regulators"],
                "County Government": [],
                "Water & Sanitation Utilities": []
            },
            "Private Sector": {
                "Large-scale Contractors": [],
                "Micro-entrepreneurs": ["Manual Emptiers", "Small Mechanised", "Artisans"],
                "Social Enterprises": [],
                "Technology Providers": [],
                "Manufacturers": []
            },
            "Civil Society & NGOs": {
                "International NGOs": [],
                "Local NGOs": [],
                "Community-Based Organisations (CBOs)": [],
                "Advocacy Groups": []
            },
            "Financial Institutions": {
                "Multilateral Organisations": [],
                "Banks": [],
                "Microfinance Institutions (MFIs)": [],
                "Investors": []
            },
            "Research & Academic": {
                "Universities": [],
                "Labs": [],
                "Research Institutions": [],
                "Individual Researchers": [],
                "Tertiary Institutions": []
            },
            "The Users": {
                "Individuals": [],
                "Institutions": [],
                "Community": []
            },
            "Others": {}
        };

        function adminUpdateSubTypes() {
            const sectorEl = document.getElementById('admin-org-sector');
            if (!sectorEl) return;
            const sectorKey = sectorEl.value;
            const subTypeSelect = document.getElementById('admin-org-subtype');
            const specSelect = document.getElementById('admin-org-spec');
            const otherInput = document.getElementById('admin-org-other');

            subTypeSelect.classList.add('hidden');
            specSelect.classList.add('hidden');
            otherInput.classList.add('hidden');
            subTypeSelect.innerHTML = '<option value="">Select Sub-Type...</option>';
            specSelect.innerHTML = '<option value="">Select Specialisation...</option>';

            if (sectorKey === 'Others') {
                otherInput.classList.remove('hidden');
            }

            if (sectorKey && adminOrgTaxonomy[sectorKey] && Object.keys(adminOrgTaxonomy[sectorKey]).length > 0) {
                subTypeSelect.classList.remove('hidden');
                for (const subType in adminOrgTaxonomy[sectorKey]) {
                    const opt = document.createElement('option');
                    opt.value = subType;
                    opt.textContent = subType;
                    subTypeSelect.appendChild(opt);
                }
            }
        }

        function adminUpdateSpecs() {
            const sectorKey = document.getElementById('admin-org-sector').value;
            const subTypeKey = document.getElementById('admin-org-subtype').value;
            const specSelect = document.getElementById('admin-org-spec');

            specSelect.classList.add('hidden');
            specSelect.innerHTML = '<option value="">Select Specialisation...</option>';

            if (sectorKey && subTypeKey && adminOrgTaxonomy[sectorKey][subTypeKey] && adminOrgTaxonomy[sectorKey][subTypeKey].length > 0) {
                specSelect.classList.remove('hidden');
                adminOrgTaxonomy[sectorKey][subTypeKey].forEach(spec => {
                    const opt = document.createElement('option');
                    opt.value = spec;
                    opt.textContent = spec;
                    specSelect.appendChild(opt);
                });
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            const sectorEl = document.getElementById('admin-org-sector');
            if (sectorEl && sectorEl.value) {
                adminUpdateSubTypes();
                const preSubType = <?= json_encode($admin_org_sector['sub_type'] ?? '') ?>;
                if (preSubType) {
                    document.getElementById('admin-org-subtype').value = preSubType;
                    adminUpdateSpecs();
                    const preSpec = <?= json_encode($admin_org_sector['specialisation'] ?? '') ?>;
                    if (preSpec) {
                        document.getElementById('admin-org-spec').value = preSpec;
                    }
                }
            }
        });

        function toggleAdminUserType() {
            const ut = document.getElementById('admin-user-type').value;
            const orgSection = document.getElementById('admin-org-section');
            if (ut === 'individual') {
                orgSection.classList.add('hidden');
            } else {
                orgSection.classList.remove('hidden');
            }
        }
    </script>
</body>
</html>
