<?php
session_start();
require_once 'config.php';

$redirect_qs = '';
if (!empty($_GET['redirect'])) {
    $requested = basename($_GET['redirect']);
    if (preg_match('/^[a-zA-Z0-9_\-]+\.php$/', $requested)) {
        $redirect_qs = '?redirect=' . urlencode($requested);
    }
}

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    $redirect = 'user_dashboard.php';
    if (!empty($_GET['redirect'])) {
        $requested = basename($_GET['redirect']);
        if (preg_match('/^[a-zA-Z0-9_\-]+\.php$/', $requested)) {
            $redirect = $requested;
        }
    }
    header("Location: " . $redirect);
    exit;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // New fields
    $user_type = $_POST['user_type'] ?? 'organization';
    $salutation = $_POST['salutation'] ?? '';
    $personal_name = trim($_POST['personal_name'] ?? '');
    $personal_email = filter_var($_POST['personal_email'] ?? '', FILTER_SANITIZE_EMAIL);
    $personal_phone = trim($_POST['personal_phone'] ?? '');
    $org_name = trim($_POST['org_name'] ?? '');
    $company_email = filter_var($_POST['company_email'] ?? '', FILTER_SANITIZE_EMAIL);
    $company_phone = trim($_POST['company_phone'] ?? '');
    $designation = trim($_POST['designation'] ?? '');
    $website = trim($_POST['website'] ?? '');

    // Org Sector Parsing
    $sector = $_POST['sector'] ?? '';
    $sub_type = $_POST['sub_type'] ?? '';
    $specialisation = $_POST['specialisation'] ?? '';
    $org_sector_json = null;
    if ($user_type === 'organization' && !empty($sector)) {
        $org_sector_data = ['sector' => $sector];
        if (!empty($sub_type))
            $org_sector_data['type'] = $sub_type;
        if (!empty($specialisation))
            $org_sector_data['specialisation'] = $specialisation;
        if ($sector === 'Others' && !empty($_POST['sector_other'])) {
            $org_sector_data['sector'] = trim($_POST['sector_other']);
        }
        $org_sector_json = json_encode($org_sector_data);
    }

    // JSON arrays
    $service_chains = json_encode($_POST['service_chains'] ?? []);
    $enabling_pillars = json_encode($_POST['enabling_pillars'] ?? []);
    $challenges_sector = json_encode($_POST['challenges_sector'] ?? []);
    $counties = json_encode($_POST['counties'] ?? []);

    $email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL); // Main login email
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($email) || empty($password) || empty($confirm_password) || ($user_type === 'organization' && empty($org_name)) || ($user_type === 'individual' && empty($personal_name))) {
        $error = "Required fields are missing.";
    } else {
        // ... (reCAPTCHA check remains the same)
        $recaptcha_response = $_POST['g-recaptcha-response'] ?? '';
        $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret' => RECAPTCHA_SECRET_KEY, 'response' => $recaptcha_response];
        $options = ['http' => ['header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)]];
        $context = stream_context_create($options);
        $captcha_success = json_decode(file_get_contents($verify_url, false, $context));

        if (!$captcha_success->success) {
            $error = "Please verify you are not a robot.";
        } elseif ($password !== $confirm_password) {
            $error = "Passwords do not match.";
        } elseif (strlen($password) < 6) {
            $error = "Password must be at least 6 characters long.";
        } else {
            $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            if ($conn->connect_error)
                die("Connection failed: " . $conn->connect_error);

            $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                $error = "An account with this email already exists.";
            } else {
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                $display_name = ($user_type === 'organization') ? $org_name : $personal_name;
                // For individuals, store personal_name in org_name so the display name is set
                if ($user_type === 'individual') {
                    $org_name = $personal_name;
                }

                // Generate slug from display name
                $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $display_name), '-'));
                // Ensure unique slug
                $base_slug = $slug;
                $slug_counter = 1;
                $slug_check = $conn->prepare("SELECT id FROM users WHERE slug = ?");
                $slug_check->bind_param("s", $slug);
                $slug_check->execute();
                $slug_check->store_result();
                while ($slug_check->num_rows > 0) {
                    $slug = $base_slug . '-' . $slug_counter++;
                    $slug_check = $conn->prepare("SELECT id FROM users WHERE slug = ?");
                    $slug_check->bind_param("s", $slug);
                    $slug_check->execute();
                    $slug_check->store_result();
                }

                $role = 'user';
                $verification_code = substr(md5(uniqid()), 0, 10);
                $stmt = $conn->prepare("INSERT INTO users (user_type, salutation, org_name, org_sector, email, password, personal_email, personal_phone, company_email, company_phone, designation, website, service_chains, enabling_pillars, challenges_sector, counties, verification_code, is_verified, slug, role) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)");
                $stmt->bind_param("sssssssssssssssssss", $user_type, $salutation, $org_name, $org_sector_json, $email, $password_hash, $personal_email, $personal_phone, $company_email, $company_phone, $designation, $website, $service_chains, $enabling_pillars, $challenges_sector, $counties, $verification_code, $slug, $role);

                if ($stmt->execute()) {
                    $new_user_id = $conn->insert_id;

                    // Automatically create a submission for organizations so they appear in the admin panel
                    if ($user_type === 'organization') {
                        $sub_title = $org_name;
                        $sub_contact = $personal_name;
                        $sub_role = $designation;
                        // Use company phone if available, else personal phone
                        $sub_mobile = !empty($company_phone) ? $company_phone : $personal_phone;
                        $sub_status = 'pending';

                        $stmt_sub = $conn->prepare("INSERT INTO submissions (user_id, org_name, title, contact_person, contact_role, email, mobile, role, service_chains, enabling_pillars, thematic_categories, county, is_verified, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'user', ?, ?, ?, ?, 1, ?)");

                        if ($stmt_sub) {
                            $stmt_sub->bind_param("issssssssssss", $new_user_id, $org_name, $sub_title, $sub_contact, $sub_role, $email, $sub_mobile, $service_chains, $enabling_pillars, $challenges_sector, $counties, $sub_status);
                            $stmt_sub->execute();
                        }
                    }

                    // Assign Free Package
                    $pkg_res = $conn->query("SELECT id, token_amount, duration_days FROM subscription_packages WHERE price = 0 AND is_active = 1 LIMIT 1");
                    if ($pkg_res && $pkg = $pkg_res->fetch_assoc()) {
                        $end_date = date('Y-m-d H:i:s', strtotime("+" . ($pkg['duration_days'] ?? 3650) . " days"));
                        $conn->query("INSERT INTO user_subscriptions (user_id, package_id, tokens_remaining, start_date, end_date, status) VALUES ($new_user_id, {$pkg['id']}, {$pkg['token_amount']}, NOW(), '$end_date', 'active')");
                    }

                    $success = "Account created successfully! You can now log in.";
                } else {
                    $error = "Error: " . $conn->error;
                }
            }
            $stmt->close();
            $conn->close();
        }
    }
}

$bg_images = ['images/services/containment.jpeg', 'images/services/Transport.jpg', 'images/services/emptying.jpg', 'images/services/Treatment.jpg', 'images/services/reuse.jpg'];
$random_bg = $bg_images[array_rand($bg_images)];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign Up - SaniBook</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <!-- FontAwesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
        body {
            font-family: 'Outfit', sans-serif;
            background-color: #0f172a;
        }

        .login-card {
            background: white;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            transition: all 0.3s ease;
        }

        .login-card:hover {
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }
    </style>
</head>

<body class="min-h-screen flex items-center justify-center p-4 relative">
    <!-- Background Image -->
    <img src="<?php echo htmlspecialchars($random_bg); ?>" alt="" class="absolute inset-0 w-full h-full object-cover">
    <div class="absolute inset-0 bg-slate-900/75"></div>

    <!-- Back Button -->
    <a href="index.php"
        class="absolute top-6 left-6 z-10 text-white/80 hover:text-white font-medium flex items-center gap-2 transition-colors">
        <i class="fa-solid fa-arrow-left"></i> Home
    </a>

    <div class="login-card relative z-10 w-full max-w-4xl bg-white rounded-2xl overflow-hidden border border-slate-100">

        <!-- Header -->
        <div class="bg-blue-900 p-8 text-center relative overflow-hidden">
            <div class="absolute inset-0 bg-gradient-to-br from-blue-800 to-blue-950 opacity-90"></div>
            <div class="absolute -bottom-10 -left-10 w-40 h-40 bg-blue-500 rounded-full blur-3xl opacity-20"></div>

            <div class="relative z-10">
                <a href="index.php" class="inline-block mb-2">
                    <img src="images/saniBook logo.png" alt="SaniBook"
                        class="h-12 w-auto bg-white/10 p-1 rounded-lg backdrop-blur-sm">
                </a>
                <h2 class="text-2xl font-bold text-white tracking-tight">Create Account</h2>
                <p class="text-blue-200 text-sm mt-1">Join the national sanitation movement</p>
            </div>
        </div>

        <!-- Form -->
        <div class="p-8">
            <div class="text-center mb-4">
                <p class="text-sm text-slate-500">
                    Already have an account?
                    <a href="login.php<?php echo $redirect_qs; ?>"
                        class="text-blue-600 font-semibold hover:text-blue-800">Sign in</a>
                </p>
            </div>
            <?php if (!empty($_GET['redirect']) && basename($_GET['redirect']) === 'submit-data.php'): ?>
                <div class="bg-blue-50 border-l-4 border-blue-500 text-blue-700 p-4 mb-6 rounded text-sm flex items-start">
                    <i class="fa-solid fa-circle-info mt-0.5 mr-2"></i>
                    <div>
                        Or create an account below to submit data
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded text-sm flex items-start">
                    <i class="fa-solid fa-circle-exclamation mt-0.5 mr-2"></i>
                    <div>
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div
                    class="bg-green-50 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded text-sm flex items-start">
                    <i class="fa-solid fa-check-circle mt-0.5 mr-2"></i>
                    <div>
                        <?php echo htmlspecialchars($success); ?>
                        <div class="mt-2 text-green-800 font-semibold">
                            <a href="login.php<?php echo $redirect_qs; ?>" class="underline hover:text-green-900">Sign in
                                now</a>
                        </div>
                    </div>
                </div>
            <?php else: ?>

                <form method="POST" action="" class="space-y-6">
                    <!-- User Type Toggle -->
                    <div class="flex justify-center mb-6">
                        <div class="inline-flex bg-slate-100 p-1 rounded-lg border border-slate-200">
                            <button type="button" onclick="setSignupType('organization')" id="type-org"
                                class="px-4 py-2 rounded-md text-sm font-bold transition-all <?php echo (!isset($user_type) || $user_type === 'organization') ? 'bg-blue-900 text-white shadow-sm' : 'text-slate-500 hover:text-blue-900'; ?>">Organization</button>
                            <button type="button" onclick="setSignupType('individual')" id="type-ind"
                                class="px-4 py-2 rounded-md text-sm font-bold transition-all <?php echo (isset($user_type) && $user_type === 'individual') ? 'bg-blue-900 text-white shadow-sm' : 'text-slate-500 hover:text-blue-900'; ?>">Individual</button>
                        </div>
                        <input type="hidden" name="user_type" id="signup_user_type"
                            value="<?php echo htmlspecialchars($user_type ?? 'organization'); ?>">
                    </div>

                    <!-- Two-column grid on desktop -->
                    <div class="grid md:grid-cols-2 md:gap-8">
                        <!-- LEFT: Personal + Credentials -->
                        <div class="space-y-4">
                            <!-- Personal Representative Section -->
                            <div class="space-y-3 bg-slate-50 p-4 rounded-xl border border-slate-100">
                                <h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Representative
                                    Details
                                </h3>
                                <div class="grid grid-cols-3 gap-2">
                                    <select name="salutation"
                                        class="col-span-1 px-3 py-2 border rounded-lg text-sm bg-white">
                                        <option value="Mr." <?php echo (isset($salutation) && $salutation === 'Mr.') ? 'selected' : ''; ?>>Mr.</option>
                                        <option value="Ms." <?php echo (isset($salutation) && $salutation === 'Ms.') ? 'selected' : ''; ?>>Ms.</option>
                                        <option value="Dr." <?php echo (isset($salutation) && $salutation === 'Dr.') ? 'selected' : ''; ?>>Dr.</option>
                                        <option value="Prof." <?php echo (isset($salutation) && $salutation === 'Prof.') ? 'selected' : ''; ?>>Prof.</option>
                                    </select>
                                    <input type="text" name="personal_name" required placeholder="Full Name"
                                        value="<?php echo htmlspecialchars($personal_name ?? ''); ?>"
                                        class="col-span-2 px-3 py-2 border rounded-lg text-sm bg-white">
                                </div>
                                <div class="grid grid-cols-2 gap-2">
                                    <input type="email" name="personal_email" placeholder="Personal Email"
                                        value="<?php echo htmlspecialchars($personal_email ?? ''); ?>"
                                        class="px-3 py-2 border rounded-lg text-sm bg-white">
                                    <input type="tel" name="personal_phone" placeholder="Personal Phone"
                                        value="<?php echo htmlspecialchars($personal_phone ?? ''); ?>"
                                        class="px-3 py-2 border rounded-lg text-sm bg-white">
                                </div>
                            </div>

                            <!-- Account Info -->
                            <div class="space-y-3">
                                <h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Account
                                    Credentials</h3>
                                <input type="email" name="email" required placeholder="Login Email"
                                    value="<?php echo htmlspecialchars($email ?? ''); ?>"
                                    class="w-full px-3 py-2 border rounded-lg text-sm">
                                <div class="grid grid-cols-2 gap-2">
                                    <input type="password" name="password" required minlength="6" placeholder="Password"
                                        class="px-3 py-2 border rounded-lg text-sm">
                                    <input type="password" name="confirm_password" required minlength="6"
                                        placeholder="Confirm" class="px-3 py-2 border rounded-lg text-sm">
                                </div>
                            </div>

                        </div><!-- END LEFT COLUMN -->

                        <!-- RIGHT: Company + Sectors -->
                        <div class="space-y-4">
                            <!-- Company Section -->
                            <div id="company-section"
                                class="space-y-3 bg-slate-50 p-4 rounded-xl border border-slate-100 <?php echo (!empty($user_type) && $user_type === 'individual') ? 'hidden' : ''; ?>">
                                <h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Organization
                                    Details</h3>
                                <input type="text" id="signup_org_name" name="org_name" placeholder="Organization Name"
                                    value="<?php echo htmlspecialchars($org_name ?? ''); ?>"
                                    class="w-full px-3 py-2 border rounded-lg text-sm bg-white">

                                <!-- Organization Sector Hierarchy -->
                                <div class="space-y-2 pt-2 border-t border-slate-200 mt-2">
                                    <label
                                        class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest">Organization
                                        Sector &amp; Type</label>
                                    <select id="org-sector-select" name="sector"
                                        class="w-full px-3 py-2 border rounded-lg text-sm bg-white"
                                        onchange="updateSubTypes()">
                                        <option value="">Select Top-level Sector...</option>
                                        <option value="Public Sector" <?php echo (isset($sector) && $sector === 'Public Sector') ? 'selected' : ''; ?>>Public Sector</option>
                                        <option value="Private Sector" <?php echo (isset($sector) && $sector === 'Private Sector') ? 'selected' : ''; ?>>Private Sector</option>
                                        <option value="Civil Society & NGOs" <?php echo (isset($sector) && $sector === 'Civil Society & NGOs') ? 'selected' : ''; ?>>Civil Society &amp; NGOs</option>
                                        <option value="Financial Institutions" <?php echo (isset($sector) && $sector === 'Financial Institutions') ? 'selected' : ''; ?>>Financial Institutions
                                        </option>
                                        <option value="Research & Academic" <?php echo (isset($sector) && $sector === 'Research & Academic') ? 'selected' : ''; ?>>Research &amp; Academic
                                        </option>
                                        <option value="The Users" <?php echo (isset($sector) && $sector === 'The Users') ? 'selected' : ''; ?>>The Users</option>
                                        <option value="Others" <?php echo (isset($sector) && $sector === 'Others') ? 'selected' : ''; ?>>Others</option>
                                    </select>

                                    <input type="text" id="org-sector-other" name="sector_other"
                                        placeholder="Please specify sector"
                                        value="<?php echo htmlspecialchars($_POST['sector_other'] ?? ''); ?>"
                                        class="w-full px-3 py-2 border rounded-lg text-sm bg-white hidden">

                                    <select id="org-type-select" name="sub_type"
                                        class="w-full px-3 py-2 border rounded-lg text-sm bg-white hidden"
                                        onchange="updateSpecialisations()">
                                        <option value="">Select Sub-Type...</option>
                                    </select>

                                    <select id="org-specialisation-select" name="specialisation"
                                        class="w-full px-3 py-2 border rounded-lg text-sm bg-white hidden">
                                        <option value="">Select Specialisation...</option>
                                    </select>

                                    <script>
                                        var preselectedSubType = <?php echo json_encode($sub_type ?? ''); ?>;
                                        var preselectedSpec = <?php echo json_encode($specialisation ?? ''); ?>;
                                        document.addEventListener('DOMContentLoaded', () => {
                                            if (document.getElementById('org-sector-select').value) {
                                                updateSubTypes();
                                            }
                                        });
                                    </script>
                                </div>

                                <div class="grid grid-cols-2 gap-2 mt-2">
                                    <input type="email" name="company_email" placeholder="Company Email"
                                        value="<?php echo htmlspecialchars($company_email ?? ''); ?>"
                                        class="px-3 py-2 border rounded-lg text-sm bg-white">
                                    <input type="tel" name="company_phone" placeholder="Company Phone"
                                        value="<?php echo htmlspecialchars($company_phone ?? ''); ?>"
                                        class="px-3 py-2 border rounded-lg text-sm bg-white">
                                </div>
                                <input type="text" name="designation" placeholder="Designation / Role"
                                    value="<?php echo htmlspecialchars($designation ?? ''); ?>"
                                    class="w-full px-3 py-2 border rounded-lg text-sm bg-white">
                                <input type="text" name="website" placeholder="Website (e.g. www.organization.org)"
                                    value="<?php echo htmlspecialchars($website ?? ''); ?>"
                                    class="w-full px-3 py-2 border rounded-lg text-sm bg-white">

                                <!-- Counties of Operation (Multi-Select) -->
                                <div class="space-y-2">
                                    <label
                                        class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest">Counties
                                        of
                                        Operation</label>
                                    <div class="relative" id="county-multi-select">
                                        <div
                                            class="flex flex-wrap gap-1 p-1.5 border border-slate-200 rounded-lg bg-white min-h-[38px] transition-all focus-within:ring-2 focus-within:ring-blue-500">
                                            <div id="selected-counties-container" class="flex flex-wrap gap-1"></div>
                                            <input type="text" id="county-search"
                                                class="flex-1 min-w-[100px] outline-none text-xs bg-transparent border-none focus:ring-0 p-0"
                                                placeholder="Search counties...">
                                        </div>
                                        <div id="county-dropdown"
                                            class="hidden absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-xl max-h-40 overflow-y-auto">
                                            <!-- Options will be injected here -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Sector Involvement -->
                            <div class="space-y-4 pt-2">
                                <label class="block text-[10px] font-bold text-slate-500 uppercase">Service Chain(s)</label>
                                <div
                                    class="grid grid-cols-2 gap-1 max-h-24 overflow-y-auto p-2 bg-slate-50 rounded border text-[10px]">
                                    <?php foreach (["Capture & Containment", "Transport", "Emptying", "Disposal", "Treatment", "Reuse & Circular Economy"] as $c): ?>
                                        <label class="flex items-center gap-2"><input type="checkbox" name="service_chains[]"
                                                value="<?php echo $c; ?>" <?php echo (isset($_POST['service_chains']) && in_array($c, $_POST['service_chains'])) ? 'checked' : ''; ?>>
                                            <?php echo $c; ?></label>
                                    <?php endforeach; ?>
                                </div>

                                <label class="block text-[10px] font-bold text-slate-500 uppercase">Enabling
                                    Pillar(s)</label>
                                <div
                                    class="grid grid-cols-2 gap-1 max-h-24 overflow-y-auto p-2 bg-slate-50 rounded border text-[10px]">
                                    <?php foreach (["Financing", "Governance", "Research & Learning", "Coordination and Collaboration", "Menstrual Health Management", "Capacity Building"] as $s): ?>
                                        <label class="flex items-center gap-2"><input type="checkbox" name="enabling_pillars[]"
                                                value="<?php echo $s; ?>" <?php echo (isset($_POST['enabling_pillars']) && in_array($s, $_POST['enabling_pillars'])) ? 'checked' : ''; ?>>
                                            <?php echo $s; ?></label>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                        </div><!-- END RIGHT COLUMN -->
                    </div><!-- END two-column grid -->

                    <div class="flex justify-center">
                        <div class="g-recaptcha"
                            data-sitekey="<?php echo defined('RECAPTCHA_SITE_KEY') ? RECAPTCHA_SITE_KEY : ''; ?>"></div>
                    </div>

                    <button type="submit"
                        class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded-lg shadow-md transition-all">
                        Create Account
                    </button>
                </form>

                <script>
                    // Org Taxonomy Logic
                    const orgTaxonomy = {
                        "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 updateSubTypes() {
                        const sectorKey = document.getElementById('org-sector-select').value;
                        const subTypeSelect = document.getElementById('org-type-select');
                        const specSelect = document.getElementById('org-specialisation-select');
                        const otherInput = document.getElementById('org-sector-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');
                            otherInput.required = true;
                        } else {
                            otherInput.required = false;
                        }

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

                    function updateSpecialisations() {
                        const sectorKey = document.getElementById('org-sector-select').value;
                        const subTypeKey = document.getElementById('org-type-select').value;
                        const specSelect = document.getElementById('org-specialisation-select');

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

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

                    // County Multi-Select Logic
                    const kenyaCounties = ["National", "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"];
                    let selectedCounties = <?php echo json_encode($_POST['counties'] ?? []); ?>;

                    document.addEventListener('DOMContentLoaded', () => {
                        updateCountiesUI();
                    });

                    const countySearch = document.getElementById('county-search');
                    const countyDropdown = document.getElementById('county-dropdown');
                    const selectedContainer = document.getElementById('selected-counties-container');

                    function updateCountiesUI() {
                        selectedContainer.innerHTML = '';
                        selectedCounties.forEach(county => {
                            const pill = document.createElement('div');
                            pill.className = 'flex items-center gap-1 bg-blue-50 text-blue-700 border border-blue-100 px-2 py-0.5 rounded text-[10px] font-bold';
                            pill.innerHTML = `
                                <span>${county}</span>
                                <button type="button" onclick="removeCounty('${county}')" class="hover:text-red-500 transition-colors">
                                    <i class="fa-solid fa-xmark"></i>
                                </button>
                                <input type="hidden" name="counties[]" value="${county}">
                            `;
                            selectedContainer.appendChild(pill);
                        });
                    }

                    function removeCounty(county) {
                        selectedCounties = selectedCounties.filter(c => c !== county);
                        updateCountiesUI();
                    }

                    function addCounty(county) {
                        if (!selectedCounties.includes(county)) {
                            selectedCounties.push(county);
                            updateCountiesUI();
                        }
                        countySearch.value = '';
                        countyDropdown.classList.add('hidden');
                    }

                    countySearch?.addEventListener('input', (e) => {
                        const val = e.target.value.toLowerCase();
                        if (!val) {
                            countyDropdown.classList.add('hidden');
                            return;
                        }

                        const filtered = kenyaCounties.filter(c =>
                            c.toLowerCase().includes(val) && !selectedCounties.includes(c)
                        );

                        if (filtered.length > 0) {
                            countyDropdown.innerHTML = filtered.map(c => `
                                <div onmousedown="event.preventDefault(); addCounty('${c}')" class="px-3 py-1.5 hover:bg-slate-50 cursor-pointer text-[11px] font-medium border-b border-slate-50 last:border-0">
                                    ${c}
                                </div>
                            `).join('');
                            countyDropdown.classList.remove('hidden');
                        } else {
                            countyDropdown.classList.add('hidden');
                        }
                    });

                    // Close dropdown when clicking outside
                    document.addEventListener('click', (e) => {
                        const select = document.getElementById('county-multi-select');
                        if (select && !select.contains(e.target)) {
                            countyDropdown.classList.add('hidden');
                        }
                    });

                    function setSignupType(type) {
                        document.getElementById('signup_user_type').value = type;
                        const btnOrg = document.getElementById('type-org');
                        const btnInd = document.getElementById('type-ind');
                        const companySection = document.getElementById('company-section');
                        if (type === 'organization') {
                            btnOrg.className = "px-4 py-2 rounded-md text-sm font-bold transition-all bg-blue-900 text-white shadow-sm";
                            btnInd.className = "px-4 py-2 rounded-md text-sm font-bold transition-all text-slate-500 hover:text-blue-900";
                            companySection.classList.remove('hidden');
                            document.getElementById('signup_org_name').required = true;
                        } else {
                            btnInd.className = "px-4 py-2 rounded-md text-sm font-bold transition-all bg-blue-900 text-white shadow-sm";
                            btnOrg.className = "px-4 py-2 rounded-md text-sm font-bold transition-all text-slate-500 hover:text-blue-900";
                            companySection.classList.add('hidden');
                            document.getElementById('signup_org_name').required = false;
                        }
                    }
                </script>
            <?php endif; ?>

            <?php if (defined('GOOGLE_OAUTH_ENABLED') && GOOGLE_OAUTH_ENABLED): ?>
                <div class="relative my-6">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t border-slate-200"></div>
                    </div>
                    <div class="relative flex justify-center text-xs"><span
                            class="bg-white px-3 text-slate-400 uppercase tracking-wider">or</span></div>
                </div>
                <a href="auth/google-login.php"
                    class="w-full flex items-center justify-center gap-3 py-2.5 px-4 border border-slate-300 rounded-lg hover:bg-slate-50 transition-all text-slate-700 font-medium text-sm">
                    <svg width="20" height="20" viewBox="0 0 48 48">
                        <path fill="#EA4335"
                            d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
                        <path fill="#4285F4"
                            d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
                        <path fill="#FBBC05"
                            d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
                        <path fill="#34A853"
                            d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
                    </svg>
                    Sign up with Google
                </a>
            <?php endif; ?>

        </div>
    </div>

</body>

</html>