<?php
// complete-profile.php — Forced profile completion after first Google login
session_start();
require_once 'config.php';

// Must be logged in
if (empty($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = intval($_SESSION['user_id']);
$errors = [];
$success = false;

// ── Handle form submission ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_type = in_array($_POST['user_type'] ?? '', ['individual', 'organization']) ? $_POST['user_type'] : '';
    
    // Representative Details
    $salutation = trim(htmlspecialchars($_POST['salutation'] ?? '', ENT_QUOTES, 'UTF-8'));
    $personal_name = trim(htmlspecialchars($_POST['personal_name'] ?? '', ENT_QUOTES, 'UTF-8'));
    $personal_email = filter_var($_POST['personal_email'] ?? '', FILTER_SANITIZE_EMAIL);
    $personal_phone = trim(htmlspecialchars($_POST['personal_phone'] ?? '', ENT_QUOTES, 'UTF-8'));

    // Organization Details
    $org_name = trim(htmlspecialchars($_POST['org_name'] ?? '', ENT_QUOTES, 'UTF-8'));
    $company_email = filter_var($_POST['company_email'] ?? '', FILTER_SANITIZE_EMAIL);
    $company_phone = trim(htmlspecialchars($_POST['company_phone'] ?? '', ENT_QUOTES, 'UTF-8'));
    $designation = trim(htmlspecialchars($_POST['designation'] ?? '', ENT_QUOTES, 'UTF-8'));
    $website = trim(htmlspecialchars($_POST['website'] ?? '', ENT_QUOTES, 'UTF-8'));

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

    // Legacy fields mapping
    // If individual, use personal_name as org_name (display name)
    // If organization, use org_name
    $display_name = ($user_type === 'organization') ? $org_name : $personal_name;
    $phone = ($user_type === 'organization') ? $company_phone : $personal_phone;
    
    // Extract first county for legacy single-county support
    $county_arr = $_POST['counties'] ?? [];
    $primary_county = $county_arr[0] ?? '';

    // Validation
    if (empty($user_type))
        $errors[] = "Please select Individual or Organization.";
    
    if ($user_type === 'organization') {
        if (empty($org_name)) $errors[] = "Organization Name is required.";
    } else {
        if (empty($personal_name)) $errors[] = "Full Name is required.";
    }

    if (empty($errors)) {
        // Prepare UPDATE query with all new fields
        $sql = "UPDATE users SET 
                user_type = ?, 
                salutation = ?, 
                org_name = ?, 
                personal_email = ?, 
                personal_phone = ?, 
                company_email = ?, 
                company_phone = ?, 
                designation = ?, 
                website = ?, 
                counties = ?, 
                service_chains = ?, 
                enabling_pillars = ?, 
                challenges_sector = ?,
                phone = ?, 
                county = ?,
                profile_completed = 1 
                WHERE id = ?";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssssssssssssi", 
            $user_type, 
            $salutation, 
            $display_name, // Map to org_name col
            $personal_email, 
            $personal_phone, 
            $company_email, 
            $company_phone, 
            $designation, 
            $website, 
            $counties, 
            $service_chains, 
            $enabling_pillars, 
            $challenges_sector,
            $phone,
            $primary_county,
            $user_id
        );

        if ($stmt->execute()) {
            $_SESSION['user_name'] = $display_name;
            $stmt->close();

            // Redirect to saved origin or dashboard
            $redirect_to = 'user_dashboard.php';
            if (!empty($_SESSION['login_redirect'])) {
                $redirect_to = $_SESSION['login_redirect'];
                unset($_SESSION['login_redirect']);
            }
            header("Location: $redirect_to");
            exit;
        } else {
            $errors[] = "Something went wrong. Please try again. " . $conn->error;
        }
        $stmt->close();
    }
}

// ── Fetch current values for pre-fill ──
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$current = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Decode JSON fields
$current_counties = json_decode($current['counties'] ?? '[]', true) ?: [];
$current_service_chains = json_decode($current['service_chains'] ?? '[]', true) ?: [];
$current_enabling_pillars = json_decode($current['enabling_pillars'] ?? '[]', true) ?: [];
$current_challenges = json_decode($current['challenges_sector'] ?? '[]', true) ?: [];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Complete Your Profile | SaniBook</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brand: { dark: '#1B3A4B', red: '#C62828', gold: '#F9A825' }
                    },
                    fontFamily: { sans: ['Inter', 'sans-serif'] }
                }
            }
        }
    </script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>

<body class="bg-slate-50 font-sans text-slate-900 min-h-screen flex items-center justify-center p-4">

    <div class="w-full max-w-2xl">
        <!-- Card -->
        <div class="bg-white rounded-2xl shadow-lg border border-slate-200 overflow-hidden">

            <!-- Header -->
            <div class="bg-gradient-to-r from-brand-dark to-slate-800 px-8 py-6 text-white text-center">
                <div class="inline-flex items-center justify-center w-14 h-14 rounded-full bg-white/10 mb-3">
                    <i class="fa-solid fa-user-pen text-2xl"></i>
                </div>
                <h1 class="text-xl font-bold">Complete Your Profile</h1>
                <p class="text-slate-300 text-sm mt-1">Tell us a bit about yourself to get started.</p>
            </div>

            <!-- Form -->
            <form method="POST" class="px-8 py-6 space-y-6">

                <?php if (!empty($errors)): ?>
                    <div class="bg-red-50 border border-red-200 text-red-700 rounded-lg px-4 py-3 text-sm">
                        <?php foreach ($errors as $e): ?>
                            <p><i class="fa-solid fa-circle-exclamation mr-2"></i><?= htmlspecialchars($e) ?></p>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <!-- Account type -->
                <fieldset>
                    <legend class="text-sm font-semibold text-slate-700 mb-2">I am registering as <span class="text-red-500">*</span></legend>
                    <div class="grid grid-cols-2 gap-3">
                        <label id="type-individual"
                            class="cursor-pointer flex flex-col items-center gap-2 border-2 rounded-xl p-4 transition-all
                                      <?= ($current['user_type'] ?? '') === 'individual' ? 'border-brand-dark bg-brand-dark/5' : 'border-slate-200 hover:border-slate-400' ?>">
                            <input type="radio" name="user_type" value="individual" class="sr-only" onclick="toggleUserType('individual')"
                                <?= ($current['user_type'] ?? '') === 'individual' ? 'checked' : '' ?>>
                            <i class="fa-solid fa-user text-xl text-brand-dark"></i>
                            <span class="text-sm font-medium">Individual</span>
                        </label>
                        <label id="type-organization"
                            class="cursor-pointer flex flex-col items-center gap-2 border-2 rounded-xl p-4 transition-all
                                      <?= ($current['user_type'] ?? '') !== 'individual' ? 'border-brand-dark bg-brand-dark/5' : 'border-slate-200 hover:border-slate-400' ?>">
                            <input type="radio" name="user_type" value="organization" class="sr-only" onclick="toggleUserType('organization')"
                                <?= ($current['user_type'] ?? '') !== 'individual' ? 'checked' : '' ?>>
                            <i class="fa-solid fa-building text-xl text-brand-dark"></i>
                            <span class="text-sm font-medium">Organization</span>
                        </label>
                    </div>
                </fieldset>

                <!-- Representative Details -->
                <div class="space-y-3 bg-slate-50 p-4 rounded-xl border border-slate-100">
                    <h3 class="text-xs 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="">Title</option>
                            <?php foreach(['Mr.', 'Ms.', 'Dr.', 'Prof.'] as $sal): ?>
                                <option value="<?= $sal ?>" <?= ($current['salutation'] ?? '') === $sal ? 'selected' : '' ?>><?= $sal ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input type="text" name="personal_name" placeholder="Full Name"
                            value="<?= htmlspecialchars($current['user_type'] === 'individual' ? ($current['org_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="<?= htmlspecialchars($current['personal_email'] ?: $current['email']) ?>"
                            class="px-3 py-2 border rounded-lg text-sm bg-white">
                        <input type="tel" name="personal_phone" placeholder="Personal Phone"
                            value="<?= htmlspecialchars($current['personal_phone'] ?? '') ?>"
                            class="px-3 py-2 border rounded-lg text-sm bg-white">
                    </div>
                </div>

                <!-- Organization Details -->
                <div id="company-section" class="space-y-3 bg-slate-50 p-4 rounded-xl border border-slate-100 <?= ($current['user_type'] ?? '') === 'individual' ? 'hidden' : '' ?>">
                    <h3 class="text-xs font-bold text-slate-400 uppercase tracking-widest">Organization Details</h3>
                    <input type="text" id="org_name" name="org_name" placeholder="Organization Name"
                        value="<?= htmlspecialchars($current['user_type'] !== 'individual' ? ($current['org_name'] ?? '') : '') ?>"
                        class="w-full px-3 py-2 border rounded-lg text-sm bg-white">
                    <div class="grid grid-cols-2 gap-2">
                        <input type="email" name="company_email" placeholder="Company Email"
                            value="<?= htmlspecialchars($current['company_email'] ?: $current['email']) ?>"
                            class="px-3 py-2 border rounded-lg text-sm bg-white">
                        <input type="tel" name="company_phone" placeholder="Company Phone"
                            value="<?= htmlspecialchars($current['company_phone'] ?? '') ?>"
                            class="px-3 py-2 border rounded-lg text-sm bg-white">
                    </div>
                    <input type="text" name="designation" placeholder="Designation / Role"
                        value="<?= htmlspecialchars($current['designation'] ?? '') ?>"
                        class="w-full px-3 py-2 border rounded-lg text-sm bg-white">
                    <input type="url" name="website" placeholder="Website (https://...)"
                        value="<?= htmlspecialchars($current['website'] ?? '') ?>"
                        class="w-full px-3 py-2 border rounded-lg text-sm bg-white">

                    <!-- Counties Multi-Select -->
                    <div class="space-y-2">
                        <label class="block text-xs 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"></div>
                        </div>
                    </div>
                </div>

                <!-- Sector Involvement -->
                <div class="space-y-4 pt-2">
                    <h3 class="text-xs font-bold text-slate-400 uppercase tracking-widest">Sector Involvement</h3>
                    
                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1">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", "Emptying & Transport", "Treatment & Disposal", "Reuse & Circular Economy"] as $c): ?>
                                <label class="flex items-center gap-2">
                                    <input type="checkbox" name="service_chains[]" value="<?= $c ?>" <?= in_array($c, $current_service_chains) ? 'checked' : '' ?>> 
                                    <?= $c ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1">Enabling Pillars</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", "Collaboration", "Menstrual Health Management", "Capacity Building"] as $c): ?>
                                <label class="flex items-center gap-2">
                                    <input type="checkbox" name="enabling_pillars[]" value="<?= $c ?>" <?= in_array($c, $current_enabling_pillars) ? 'checked' : '' ?>> 
                                    <?= $c ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1">Barriers</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 (["Access", "Funding", "Technology", "Governance", "Behavioral", "Environmental"] as $s): ?>
                                <label class="flex items-center gap-2">
                                    <input type="checkbox" name="challenges_sector[]" value="<?= $s ?>" <?= in_array($s, $current_challenges) ? 'checked' : '' ?>> 
                                    <?= $s ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Submit -->
                <button type="submit"
                    class="w-full py-3 bg-brand-dark text-white rounded-lg font-semibold text-sm hover:bg-slate-800 transition-colors shadow-md">
                    <i class="fa-solid fa-check mr-2"></i>Save &amp; Continue
                </button>

            </form>
        </div>

        <p class="text-center text-xs text-slate-400 mt-4">
            You can update these details later from your dashboard.
        </p>
    </div>

    <script>
        // County Logic
        const kenyaCounties = ["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 = <?= json_encode($current_counties) ?>;

        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 onclick="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');
            }
        });

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

        // Initialize UI
        updateCountiesUI();

        // User Type Toggle
        function toggleUserType(type) {
            const btnInd = document.getElementById('type-individual');
            const btnOrg = document.getElementById('type-organization');
            const companySection = document.getElementById('company-section');
            const personalNameInput = document.querySelector('input[name="personal_name"]');
            const orgNameInput = document.querySelector('input[name="org_name"]');

            if (type === 'individual') {
                btnInd.classList.add('border-brand-dark', 'bg-brand-dark/5');
                btnInd.classList.remove('border-slate-200');
                btnOrg.classList.remove('border-brand-dark', 'bg-brand-dark/5');
                btnOrg.classList.add('border-slate-200');
                
                companySection.classList.add('hidden');
                personalNameInput.required = true;
                orgNameInput.required = false;
            } else {
                btnOrg.classList.add('border-brand-dark', 'bg-brand-dark/5');
                btnOrg.classList.remove('border-slate-200');
                btnInd.classList.remove('border-brand-dark', 'bg-brand-dark/5');
                btnInd.classList.add('border-slate-200');
                
                companySection.classList.remove('hidden');
                personalNameInput.required = false;
                orgNameInput.required = true;
            }
        }
        
        // Init state
        toggleUserType('<?= $current['user_type'] ?? 'organization' ?>');

    </script>

</body>
</html>