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

// Helper: generate URL-safe slug from org_name
function generate_slug($name, $conn, $exclude_id = 0)
{
    $slug = strtolower(trim($name));
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    $slug = trim($slug, '-');
    if (empty($slug))
        $slug = 'user';

    // Ensure uniqueness
    $base = $slug;
    $i = 1;
    while (true) {
        $stmt = $conn->prepare("SELECT id FROM users WHERE slug = ? AND id != ?");
        $stmt->bind_param("si", $slug, $exclude_id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows === 0)
            break;
        $slug = $base . '-' . $i++;
    }
    return $slug;
}

$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$slug = isset($_GET['slug']) ? trim($_GET['slug']) : '';

// Default to logged-in user if no specific profile requested
if ($user_id === 0 && empty($slug) && isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
}
$profile_message = '';
$profile_error = '';

// Fetch User Details — by slug or user_id
$user = null;
$query_cols = "id, org_name, role, county, email, phone, bio, slug, created_at, is_enterprise, 
               user_type, salutation, personal_email, personal_phone, company_email, company_phone, 
               designation, website, service_chains, enabling_pillars, challenges_sector, counties,
               is_public, privacy_settings, org_sector";

if ($conn) {
    if (!empty($slug)) {
        $stmt = $conn->prepare("SELECT $query_cols FROM users WHERE slug = ?");
        $stmt->bind_param("s", $slug);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($user)
            $user_id = $user['id'];
    } elseif ($user_id > 0) {
        $stmt = $conn->prepare("SELECT $query_cols FROM users WHERE id = ?");
        if (!$stmt) {
            // Keep error logging for debugging but make it less intrusive or remove if confident
             die("<strong>Database Error:</strong> " . $conn->error);
        }
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();
    }
}

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

// Auto-generate slug if missing
if ($conn && empty($user['slug'])) {
    $new_slug = generate_slug($user['org_name'], $conn, $user['id']);
    $stmt = $conn->prepare("UPDATE users SET slug = ? WHERE id = ?");
    $stmt->bind_param("si", $new_slug, $user['id']);
    $stmt->execute();
    $user['slug'] = $new_slug;
}

// Canonical redirect: ?user_id=X → /profile/slug
if ($user_id > 0 && empty($slug) && !empty($user['slug'])) {
    header("Location: /profile/" . urlencode($user['slug']), true, 301);
    exit;
}

// Handle self-edit POST
$is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
$is_owner = isset($_SESSION['user_id']) && $_SESSION['user_id'] === $user_id;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($is_owner || $is_admin) && isset($_POST['edit_profile'])) {
    // New fields
    $user_type = $_POST['user_type'] ?? 'organization';
    $salutation = trim($_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_input = 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'] ?? '');
    $bio = trim($_POST['bio'] ?? '');

    // JSON Arrays
    $counties_json = json_encode($_POST['counties'] ?? []);
    $service_chains_json = json_encode($_POST['service_chains'] ?? []);
    $enabling_pillars_json = json_encode($_POST['enabling_pillars'] ?? []);
    $challenges_sector_json = json_encode($_POST['challenges_sector'] ?? []);
    $org_sector_json = isset($_POST['org_sector']) ? json_encode($_POST['org_sector']) : null;

    // Privacy Settings
    $is_public = isset($_POST['is_public']) ? 1 : 0;
    $privacy_settings = json_encode([
        'show_email' => isset($_POST['show_email']) ? true : false,
        'show_phone' => isset($_POST['show_phone']) ? true : false
    ]);

    // Logic for display name / phone / main county
    $org_name = ($user_type === 'organization') ? $org_name_input : $personal_name;
    $phone = ($user_type === 'organization') ? $company_phone : $personal_phone;
    $county_arr = $_POST['counties'] ?? [];
    $county = $county_arr[0] ?? '';

    if (!empty($org_name)) {
        $stmt = $conn->prepare("UPDATE users SET 
            user_type=?, salutation=?, org_name=?, personal_email=?, personal_phone=?, 
            company_email=?, company_phone=?, designation=?, website=?, bio=?, 
            counties=?, org_sector=?, service_chains=?, enabling_pillars=?, challenges_sector=?, 
            phone=?, county=?, is_public=?, privacy_settings=? 
            WHERE id=?");

        $stmt->bind_param(
            "sssssssssssssssssisi",
            $user_type,
            $salutation,
            $org_name,
            $personal_email,
            $personal_phone,
            $company_email,
            $company_phone,
            $designation,
            $website,
            $bio,
            $counties_json,
            $org_sector_json,
            $service_chains_json,
            $enabling_pillars_json,
            $challenges_sector_json,
            $phone,
            $county,
            $is_public,
            $privacy_settings,
            $user_id
        );

        if ($stmt->execute()) {
            // Audit
            if (file_exists(__DIR__ . '/util/audit_logger.php')) {
                include_once __DIR__ . '/util/audit_logger.php';
                audit_log(
                    $conn,
                    'user_edit',
                    'users',
                    $user_id,
                    $user_id,
                    $user_id,
                    null,
                    json_encode(['org_name' => $org_name, 'user_type' => $user_type]),
                    "User updated their own profile."
                );
            }
            $profile_message = "Profile updated successfully.";

            // Refresh user data
            $stmt = $conn->prepare("SELECT $query_cols FROM users WHERE id = ?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
        } else {
            $profile_error = "Error updating profile: " . $conn->error;
        }
    } else {
        $profile_error = "Name / Organization Name is required.";
    }
}

// Fetch User's Submissions
$submissions = [];
$query = "SELECT s.id, s.title, s.description, s.created_at, s.org_name, s.role, s.is_verified, 
                 IFNULL(s.view_count, 0) as view_count, 
                 IFNULL(AVG(r.rating), 0) as avg_rat,
                 s.service_chains, s.enabling_pillars, s.thematic_categories
          FROM submissions s 
          LEFT JOIN ratings r ON s.id = r.item_id AND r.item_type = 'submission'
          WHERE s.user_id = ?";

if (!$is_admin && !$is_owner) {
    $query .= " AND s.is_verified = 1";
}
$query .= " GROUP BY s.id ORDER BY s.created_at DESC";

if ($conn) {
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $submissions[] = $row;
    }
    $stmt->close();
}

$sub_ids_profile = array_column($submissions, 'id');
$batch_ratings_profile = get_batch_ratings($conn, 'submission', $sub_ids_profile);
$is_logged_in = isset($_SESSION['user_id']);
$current_user_id_profile = $_SESSION['user_id'] ?? 0;
$batch_user_ratings_profile = $is_logged_in ? get_batch_user_ratings($conn, (int) $current_user_id_profile, 'submission', $sub_ids_profile) : [];

// Helpers
$location_str = !empty($user['county']) ? $user['county'] : 'Kenya';
$contact_email = ($user['user_type'] === 'organization') ? ($user['company_email'] ?: $user['email']) : ($user['personal_email'] ?: $user['email']);
$decoded_counties = json_decode($user['counties'] ?? '[]', true) ?: [];
$decoded_service = json_decode($user['service_chains'] ?? '[]', true) ?: [];
$decoded_pillars = json_decode($user['enabling_pillars'] ?? '[]', true) ?: [];
$decoded_challenges = json_decode($user['challenges_sector'] ?? '[]', true) ?: [];

$privacy = json_decode($user['privacy_settings'] ?? '{}', true) ?: [];
$is_public = $user['is_public'] ?? 1; // Default to public
$show_email = $privacy['show_email'] ?? false;
$show_phone = $privacy['show_phone'] ?? false;

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($user['org_name']) ?> | SaniBook Profile</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" />
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;900&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brand: { dark: '#001F3F', blue: '#2563eb', gold: '#D4AF37' }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        heading: ['Montserrat', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <style>
        body { background: #f1f5f9; min-height: 100vh; }
        .glass-hero {
            background: rgba(255,255,255,0.07);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid rgba(255,255,255,0.15);
        }
        .glass-badge {
            background: rgba(255,255,255,0.12);
            backdrop-filter: blur(8px);
            border: 1px solid rgba(255,255,255,0.2);
        }
        .profile-card {
            background: #fff;
            border: 1px solid #e2e8f0;
            border-radius: 1rem;
            box-shadow: 0 4px 24px rgba(0,0,0,0.10);
        }
        .pill-tag {
            background: #eff6ff;
            color: #1d4ed8;
            border: 1px solid #bfdbfe;
            border-radius: 9999px;
            font-size: 10px;
            font-weight: 700;
            padding: 2px 10px;
        }
        .sub-card {
            transition: all 0.2s ease;
        }
        .sub-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
        }
        .label-sm { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.07em; color:#94a3b8; }
        
        /* Star Rating CSS from submitted.php */
        .star-rating-widget {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .star-rating-stars {
            display: flex;
            gap: 2px;
        }
        .star-rating-stars .star {
            color: rgba(0, 0, 0, 0.1);
            font-size: 14px;
            transition: all 0.2s;
        }
        .star-rating-stars .star.filled,
        .star-rating-stars .star.user-rated {
            color: #D4AF37;
        }
        .star-rating-info {
            font-size: 11px;
            color: #64748b;
            font-weight: 600;
        }
    </style>
</head>

<body class="bg-slate-100 font-sans text-slate-900 antialiased">

    <?php include 'navbar.php'; ?>

    <!-- ===== HERO HEADER ===== -->
    <header style="background:linear-gradient(135deg,#012a4a 0%,#013a5e 45%,#01497c 80%,#023e6e 100%);" class="pt-24 pb-10">
        <div class="max-w-6xl mx-auto px-4">
            <!-- Breadcrumb -->
            <p class="text-xs font-bold uppercase tracking-widest text-teal-300 mb-6">
                <i class="fa-solid fa-user-circle mr-1"></i> Profile
            </p>

            <!-- Glass hero card -->
            <div class="glass-hero rounded-2xl p-6 md:p-8">
                <!-- Dot grid overlay -->
                <div class="absolute inset-0 rounded-2xl pointer-events-none opacity-5" style="background-image:radial-gradient(circle at 2px 2px,white 1px,transparent 0);background-size:22px 22px;"></div>

                <div class="flex flex-col md:flex-row items-start md:items-center gap-6">
                    <!-- Avatar -->
                    <div class="w-20 h-20 md:w-24 md:h-24 rounded-2xl glass-badge flex items-center justify-center shrink-0">
                        <i class="<?= ($user['user_type'] === 'individual') ? 'fa-solid fa-user' : 'fa-solid fa-building' ?> text-4xl text-white/70"></i>
                    </div>

                    <!-- Name / meta -->
                    <div class="flex-1 min-w-0">
                        <div class="flex flex-wrap items-center gap-2 mb-1">
                            <h1 class="font-heading font-black text-2xl md:text-3xl text-white leading-tight">
                                <?= htmlspecialchars($user['org_name']) ?>
                            </h1>
                            <?php if ($user['is_enterprise']): ?>
                                <span class="text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider" style="background:#D4AF37;color:#fff;">Enterprise</span>
                            <?php endif; ?>
                            <?php if ($user['is_public']): ?>
                                <span class="glass-badge text-[10px] font-bold px-2 py-0.5 rounded-full text-teal-300"><i class="fa-solid fa-globe mr-1"></i>Public</span>
                            <?php endif; ?>
                        </div>
                        <p class="text-blue-200/80 font-medium text-sm mb-2">
                            <?= htmlspecialchars($user['designation'] ?: $user['role']) ?>
                            <?php if (!empty($location_str)): ?>
                                <span class="mx-1.5 text-white/30">•</span>
                                <i class="fa-solid fa-location-dot mr-1 text-teal-400"></i><?= htmlspecialchars($location_str) ?>
                            <?php endif; ?>
                        </p>
                        <?php if (!empty($user['website'])): ?>
                            <a href="<?= htmlspecialchars($user['website']) ?>" target="_blank"
                               class="inline-flex items-center gap-1.5 text-xs font-bold text-teal-300 hover:text-white transition-colors">
                                <i class="fa-solid fa-link"></i><?= htmlspecialchars($user['website']) ?>
                            </a>
                        <?php endif; ?>
                    </div>

                    <!-- Action buttons -->
                    <?php if ($is_admin || $is_owner): ?>
                    <div class="flex flex-wrap gap-2 shrink-0">
                        <a href="mailto:<?= htmlspecialchars($contact_email) ?>"
                           class="px-4 py-2 glass-badge text-white text-xs font-bold rounded-lg hover:bg-white/20 transition-all">
                            <i class="fa-regular fa-envelope mr-1"></i>Contact
                        </a>
                        <a href="#edit-profile-form"
                           class="px-4 py-2 text-xs font-bold rounded-lg transition-all text-white"
                           style="background:rgba(0,128,128,0.5);border:1px solid rgba(0,200,180,0.35);">
                            <i class="fa-solid fa-pen-to-square mr-1"></i>Edit Profile
                        </a>
                        <?php if ($is_admin && !$is_owner): ?>
                        <a href="/admin/user-detail.php?id=<?= $user_id ?>"
                           class="px-4 py-2 glass-badge text-amber-300 text-xs font-bold rounded-lg hover:bg-white/20 transition-all">
                            <i class="fa-solid fa-shield-halved mr-1"></i>Admin
                        </a>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Stats row -->
                <div class="flex flex-wrap gap-6 mt-6 pt-5" style="border-top:1px solid rgba(255,255,255,0.1);">
                    <div>
                        <p class="label-sm text-blue-200/50">Member since</p>
                        <p class="text-white font-bold text-sm"><?= date('F Y', strtotime($user['created_at'])) ?></p>
                    </div>
                    <div>
                        <p class="label-sm text-blue-200/50">Submissions</p>
                        <p class="text-white font-bold text-sm"><?= count($submissions) ?></p>
                    </div>
                    <?php if (!empty($decoded_service)): ?>
                    <div>
                        <p class="label-sm text-blue-200/50 mb-1">Service Chains</p>
                        <div class="flex flex-wrap gap-1">
                            <?php foreach (array_slice($decoded_service, 0, 3) as $s): ?>
                                <span class="glass-badge text-[10px] font-bold text-white/80 px-2 py-0.5 rounded-full"><?= htmlspecialchars($s) ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </header>

    <main class="max-w-6xl mx-auto px-4 py-10">

        <!-- Content Grid -->
        <div class="grid lg:grid-cols-4 gap-8">

            <!-- Sidebar -->
            <div class="lg:col-span-1 space-y-5">
                <!-- Flash messages -->
                <?php if ($profile_message): ?>
                    <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 p-3 rounded-xl text-sm flex items-start gap-2">
                        <i class="fa-solid fa-check-circle mt-0.5"></i><?= htmlspecialchars($profile_message) ?>
                    </div>
                <?php endif; ?>
                <?php if ($profile_error): ?>
                    <div class="bg-red-50 border border-red-200 text-red-800 p-3 rounded-xl text-sm flex items-start gap-2">
                        <i class="fa-solid fa-exclamation-circle mt-0.5"></i><?= htmlspecialchars($profile_error) ?>
                    </div>
                <?php endif; ?>

                <!-- About Card -->
                <div class="profile-card p-6">
                    <p class="label-sm text-slate-400 mb-4">About</p>
                    <div class="space-y-4 text-sm text-slate-600">
                        <div class="flex items-start gap-3">
                            <i class="fa-solid fa-location-dot mt-1 text-teal-500"></i>
                            <div>
                                <span class="block font-bold text-slate-800">Location</span>
                                <?= htmlspecialchars(implode(', ', $decoded_counties) ?: $location_str) ?>
                            </div>
                        </div>
                        <?php if (!empty($user['phone'])): ?>
                            <div class="flex items-start gap-3">
                                <i class="fa-solid fa-phone mt-1 text-teal-500"></i>
                                <div>
                                    <span class="block font-bold text-slate-800">Phone</span>
                                    <?= htmlspecialchars($user['phone']) ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($decoded_service)): ?>
                            <div class="pt-2 border-t border-slate-100">
                                <span class="block font-bold text-slate-800 mb-2">Service Chains</span>
                                <div class="flex flex-wrap gap-1">
                                    <?php foreach ($decoded_service as $item): ?>
                                        <span class="pill-tag"><?= htmlspecialchars($item) ?></span>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($user['bio'])): ?>
                            <div class="pt-2 border-t border-slate-100">
                                <i class="fa-solid fa-quote-left text-slate-300 mb-1"></i>
                                <p class="italic text-slate-500 text-sm"><?= nl2br(htmlspecialchars($user['bio'])) ?></p>
                            </div>
                        <?php endif; ?>
                        <div class="flex items-start gap-3 pt-2 border-t border-slate-100">
                            <i class="fa-solid fa-calendar mt-1 text-teal-500"></i>
                            <div>
                                <span class="block font-bold text-slate-800">Joined</span>
                                <?= date('F Y', strtotime($user['created_at'])) ?>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($is_owner || $is_admin): ?>
                        <!-- Edit Profile Form -->
                        <div id="edit-profile-form" class="profile-card p-6">
                            <p class="label-sm text-slate-400 mb-4"><i class="fa-solid fa-pen-to-square text-blue-500 mr-1"></i>Edit Profile</p>
                            <form method="POST" class="space-y-4">
                                <input type="hidden" name="edit_profile" value="1">
                            
                                <!-- User Type Toggle (Hidden input used to maintain state logic) -->
                                <div class="flex gap-2 mb-2 p-1 bg-slate-100 rounded-lg">
                                    <label class="flex-1 text-center cursor-pointer py-1.5 rounded-md text-xs font-bold transition-all <?= ($user['user_type'] === 'individual') ? 'bg-white shadow text-brand-dark' : 'text-slate-500' ?>">
                                        <input type="radio" name="user_type" value="individual" class="sr-only" onchange="this.form.submit()" <?= ($user['user_type'] === 'individual') ? 'checked' : '' ?>>
                                        Individual
                                    </label>
                                    <label class="flex-1 text-center cursor-pointer py-1.5 rounded-md text-xs font-bold transition-all <?= ($user['user_type'] !== 'individual') ? 'bg-white shadow text-brand-dark' : 'text-slate-500' ?>">
                                        <input type="radio" name="user_type" value="organization" class="sr-only" onchange="this.form.submit()" <?= ($user['user_type'] !== 'individual') ? 'checked' : '' ?>>
                                        Organization
                                    </label>
                                </div>

                                <?php if ($user['user_type'] === 'individual'): ?>
                                        <div>
                                            <label class="block text-xs font-bold text-slate-600 mb-1">Full Name</label>
                                            <div class="flex gap-2">
                                                <select name="salutation" class="w-20 border border-slate-300 rounded-lg p-2 text-xs">
                                                    <option value="">Title</option>
                                                    <?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="flex-1 border border-slate-300 rounded-lg p-2 text-xs">
                                            </div>
                                        </div>
                                        <div class="grid grid-cols-2 gap-2">
                                            <input type="email" name="personal_email" value="<?= htmlspecialchars($user['personal_email'] ?: $user['email']) ?>" placeholder="Email" class="border border-slate-300 rounded-lg p-2 text-xs">
                                            <input type="tel" name="personal_phone" value="<?= htmlspecialchars($user['personal_phone'] ?? '') ?>" placeholder="Phone" class="border border-slate-300 rounded-lg p-2 text-xs">
                                        </div>
                                <?php else: ?>
                                        <div>
                                            <label class="block text-xs font-bold text-slate-600 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 text-xs">
                                        </div>
                                        <div class="grid grid-cols-2 gap-2">
                                            <input type="email" name="company_email" value="<?= htmlspecialchars($user['company_email'] ?: $user['email']) ?>" placeholder="Email" class="border border-slate-300 rounded-lg p-2 text-xs">
                                            <input type="tel" name="company_phone" value="<?= htmlspecialchars($user['company_phone'] ?? '') ?>" placeholder="Phone" class="border border-slate-300 rounded-lg p-2 text-xs">
                                        </div>
                                        <div>
                                            <label class="block text-xs font-bold text-slate-600 mb-1">Designation & Website</label>
                                            <input type="text" name="designation" value="<?= htmlspecialchars($user['designation'] ?? '') ?>" placeholder="Designation" class="w-full border border-slate-300 rounded-lg p-2 text-xs mb-2">
                                            <input type="text" name="website" value="<?= htmlspecialchars($user['website'] ?? '') ?>" placeholder="https://..." class="w-full border border-slate-300 rounded-lg p-2 text-xs">
                                        </div>
                                        
                                        <!-- Organization Taxonomy -->
                                        <div>
                                            <label class="block text-xs font-bold text-slate-600 mb-1">Organization Sector / Type</label>
                                            <?php
                                            $selected_sector = '';
                                            $selected_sub = '';
                                            $selected_spec = '';
                                            $selected_other = '';
                                            if (!empty($user['org_sector'])) {
                                                $org_data = json_decode($user['org_sector'], true) ?? [];
                                                $selected_sector = $org_data['sector'] ?? '';
                                                $selected_sub = $org_data['sub_type'] ?? '';
                                                $selected_spec = $org_data['specialisation'] ?? '';
                                                $selected_other = $org_data['other'] ?? '';
                                            }
                                            ?>
                                            <div class="space-y-2">
                                                <select id="org-sector-select" name="org_sector[sector]" required
                                                    onchange="updateSubTypes()"
                                                    class="w-full border border-slate-300 rounded-lg p-2 text-xs">
                                                    <option value="">Select Sector...</option>
                                                    <option value="Public Sector" <?= $selected_sector === 'Public Sector' ? 'selected' : '' ?>>Public Sector</option>
                                                    <option value="Private Sector" <?= $selected_sector === 'Private Sector' ? 'selected' : '' ?>>Private Sector</option>
                                                    <option value="Civil Society & NGOs" <?= $selected_sector === 'Civil Society & NGOs' ? 'selected' : '' ?>>Civil Society & NGOs</option>
                                                    <option value="Financial Institutions" <?= $selected_sector === 'Financial Institutions' ? 'selected' : '' ?>>Financial Institutions</option>
                                                    <option value="Research & Academic" <?= $selected_sector === 'Research & Academic' ? 'selected' : '' ?>>Research & Academic</option>
                                                    <option value="The Users" <?= $selected_sector === 'The Users' ? 'selected' : '' ?>>The Users</option>
                                                    <option value="Others" <?= $selected_sector === 'Others' ? 'selected' : '' ?>>Others (Please Specify)</option>
                                                </select>

                                                <select id="org-type-select" name="org_sector[sub_type]"
                                                    onchange="updateSpecialisations()"
                                                    class="w-full border border-slate-300 rounded-lg p-2 text-xs <?= empty($selected_sub) ? 'hidden' : '' ?>">
                                                    <option value="">Select Sub-Type...</option>
                                                </select>

                                                <select id="org-specialisation-select" name="org_sector[specialisation]"
                                                    class="w-full border border-slate-300 rounded-lg p-2 text-xs <?= empty($selected_spec) ? 'hidden' : '' ?>">
                                                    <option value="">Select Specialisation...</option>
                                                </select>

                                                <input type="text" id="org-sector-other" name="org_sector[other]"
                                                    placeholder="Please specify your sector/type"
                                                    value="<?= htmlspecialchars($selected_other, ENT_QUOTES) ?>"
                                                    class="w-full border border-slate-300 rounded-lg p-2 text-xs <?= $selected_sector === 'Others' ? '' : 'hidden' ?>">
                                            </div>
                                            
                                            <?php if (!empty($user['org_sector'])): ?>
                                                <script>
                                                    var preselectedSubType = <?= json_encode($selected_sub) ?>;
                                                    var preselectedSpec = <?= json_encode($selected_spec) ?>;
                                                </script>
                                            <?php endif; ?>
                                        </div>
                                
                                        <!-- Counties Multi-Select Simplified -->
                                        <div>
                                            <label class="block text-xs font-bold text-slate-600 mb-1">Counties</label>
                                            <div class="p-2 border border-slate-300 rounded-lg bg-slate-50 max-h-32 overflow-y-auto text-xs space-y-1">
                                                <?php
                                                $all_counties = ["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"];
                                                foreach ($all_counties as $c):
                                                    ?>
                                                        <label class="flex items-center gap-2">
                                                            <input type="checkbox" name="counties[]" value="<?= $c ?>" <?= in_array($c, $decoded_counties) ? 'checked' : '' ?>> <?= $c ?>
                                                        </label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                <?php endif; ?>

                                <!-- Common Fields -->
                                <div>
                                    <label class="block text-xs font-bold text-slate-600 mb-1">Bio</label>
                                    <textarea name="bio" rows="3" class="w-full border border-slate-300 rounded-lg p-2 text-xs" placeholder="About you..."><?= htmlspecialchars($user['bio'] ?? '') ?></textarea>
                                </div>

                                <!-- Checkboxes Accordion -->
                                <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">
                                        Sector Details
                                        <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-20 overflow-y-auto border rounded p-1 text-[10px] space-y-1">
                                                <?php foreach (["Capture & Containment", "Transport", "Emptying", "Disposal", "Treatment", "Reuse & Circular Economy"] as $i): ?>
                                                        <label class="flex items-center gap-2"><input type="checkbox" name="service_chains[]" value="<?= $i ?>" <?= in_array($i, $decoded_service) ? 'checked' : '' ?>> <?= $i ?></label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <div>
                                            <p class="text-[10px] font-bold text-slate-400 uppercase">Enabling Pillars</p>
                                            <div class="h-20 overflow-y-auto border rounded p-1 text-[10px] space-y-1">
                                                <?php foreach (["Financing", "Governance", "Research & Learning", "Collaboration", "Menstrual Health Management", "Capacity Building"] as $i): ?>
                                                        <label class="flex items-center gap-2"><input type="checkbox" name="enabling_pillars[]" value="<?= $i ?>" <?= in_array($i, $decoded_pillars) ? 'checked' : '' ?>> <?= $i ?></label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                </details>

                                <!-- Privacy Settings -->
                                <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">
                                        Privacy & Visibility
                                        <i class="fa-solid fa-chevron-down group-open:rotate-180 transition-transform"></i>
                                    </summary>
                                    <div class="mt-3 space-y-3">
                                        <label class="flex items-start gap-2 cursor-pointer">
                                            <input type="checkbox" id="profile_is_public" name="is_public" value="1" <?= $is_public ? 'checked' : '' ?> class="mt-0.5">
                                            <div>
                                                <span class="block text-xs font-bold text-slate-700">List me in the Public Directory</span>
                                                <span class="block text-[10px] text-slate-500">If unchecked, your profile will be hidden from the Explore page.</span>
                                            </div>
                                        </label>
                                        <label class="flex items-start gap-2 cursor-pointer opacity-100 transition-opacity" id="profile_email_label">
                                            <input type="checkbox" id="profile_show_email" name="show_email" value="1" <?= $show_email ? 'checked' : '' ?> class="mt-0.5" <?= !$is_public ? 'disabled' : '' ?>>
                                            <div>
                                                <span class="block text-xs font-bold text-slate-700">Show Email to Logged-in Users</span>
                                                <span class="block text-[10px] text-slate-500">Allow other registered users to see your email address in the directory.</span>
                                            </div>
                                        </label>
                                        <label class="flex items-start gap-2 cursor-pointer opacity-100 transition-opacity" id="profile_phone_label">
                                            <input type="checkbox" id="profile_show_phone" name="show_phone" value="1" <?= $show_phone ? 'checked' : '' ?> class="mt-0.5" <?= !$is_public ? 'disabled' : '' ?>>
                                            <div>
                                                <span class="block text-xs font-bold text-slate-700">Show Phone to Logged-in Users</span>
                                                <span class="block text-[10px] text-slate-500">Allow other registered users to see your phone number in the directory.</span>
                                            </div>
                                        </label>
                                    </div>
                                    <script>
                                        document.addEventListener('DOMContentLoaded', () => {
                                            const isPublicCheckbox = document.getElementById('profile_is_public');
                                            const showEmailCheckbox = document.getElementById('profile_show_email');
                                            const showPhoneCheckbox = document.getElementById('profile_show_phone');
                                            const emailLabel = document.getElementById('profile_email_label');
                                            const phoneLabel = document.getElementById('profile_phone_label');
                                            
                                            if (isPublicCheckbox) {
                                                const toggleState = () => {
                                                    const disabled = !isPublicCheckbox.checked;
                                                    showEmailCheckbox.disabled = disabled;
                                                    showPhoneCheckbox.disabled = disabled;
                                                    emailLabel.style.opacity = disabled ? '0.5' : '1';
                                                    phoneLabel.style.opacity = disabled ? '0.5' : '1';
                                                };
                                                isPublicCheckbox.addEventListener('change', toggleState);
                                                toggleState(); // Init on load
                                            }
                                        });
                                    </script>
                                </details>

                                <button type="submit" class="w-full py-2.5 mt-4 text-white rounded-xl font-bold text-sm transition-all"
                                    style="background:linear-gradient(90deg,#008080,#0097a7);">
                                    <i class="fa-solid fa-save mr-1"></i> Save Changes
                                </button>
                            </form>
                        </div>

                        <!-- Account Actions -->
                        <div class="profile-card p-6">
                            <p class="label-sm text-slate-400 mb-4">Account</p>
                            <div class="space-y-1">
                                <a href="change-password.php" class="flex items-center gap-2 text-sm font-semibold text-blue-600 hover:text-blue-800 p-2 hover:bg-blue-50 rounded-lg transition-colors">
                                    <i class="fa-solid fa-key"></i> Change Password
                                </a>
                            </div>
                        </div>
                <?php endif; ?>
            </div>

            <!-- Submissions Feed -->
            <div class="lg:col-span-3">
                <div class="flex items-center justify-between mb-5">
                    <div>
                        <p class="label-sm text-slate-400">Submissions</p>
                        <h2 class="text-lg font-bold text-slate-800 mt-0.5">Data by <?= htmlspecialchars($user['org_name']) ?></h2>
                    </div>
                    <span class="text-xs font-bold text-slate-600 bg-slate-200 px-3 py-1.5 rounded-full"><?= count($submissions) ?> item<?= count($submissions) !== 1 ? 's' : '' ?></span>
                </div>

                <?php if (empty($submissions)): ?>
                    <div class="profile-card text-center py-12">
                        <i class="fa-solid fa-feather text-4xl text-slate-300 mb-3"></i>
                        <p class="text-slate-500">No data shared yet.</p>
                    </div>
                <?php else: ?>
                    <div class="grid md:grid-cols-2 gap-5">
                        <?php foreach ($submissions as $sub): 
                            $chains = json_decode($sub['service_chains'] ?? '[]', true) ?: [];
                            $pillars = json_decode($sub['enabling_pillars'] ?? '[]', true) ?: [];
                            $themes = json_decode($sub['thematic_categories'] ?? '[]', true) ?: [];
                            
                            $cats = array_merge($themes, $pillars, $chains);
                            $cat_pills = '';
                            if (!empty($cats)) {
                                foreach ($cats as $cat) {
                                    $cat_url = 'submitted.php?subcategory=' . urlencode($cat);
                                    $cat_pills .= '<a href="' . $cat_url . '" onclick="event.stopPropagation()" class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold bg-teal-50 text-teal-700 border border-teal-200 whitespace-nowrap hover:bg-teal-100 hover:text-teal-800 transition-colors">'
                                        . htmlspecialchars($cat) . '</a>';
                                }
                            } else {
                                $cat_pills = '<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold bg-slate-100 text-slate-500 border border-slate-200">General</span>';
                            }
                        ?>
                            <a href="/view_submission.php?id=<?= $sub['id'] ?>" class="group sub-card profile-card overflow-hidden flex flex-col h-full">
                                <div class="p-5 flex-1 flex flex-col">
                                    <div class="flex items-center justify-between mb-3">
                                        <div class="flex items-center gap-2">
                                            <span class="text-[10px] font-bold uppercase tracking-wider text-teal-700 bg-teal-50 border border-teal-100 px-2 py-1 rounded-full"><?= htmlspecialchars($sub['role']) ?></span>
                                            <?php if (!$sub['is_verified']): ?>
                                                <span class="text-[10px] font-bold uppercase tracking-wider text-amber-600 bg-amber-50 border border-amber-100 px-2 py-1 rounded-full">Pending</span>
                                            <?php endif; ?>
                                        </div>
                                        <span class="text-xs text-slate-400 font-semibold" title="<?= number_format((int) $sub['view_count']) ?> views">
                                            <i class="fa-regular fa-eye mr-1"></i><?= number_format((int) $sub['view_count']) ?>
                                        </span>
                                    </div>
                                    <h3 class="font-bold text-slate-900 group-hover:text-teal-700 transition-colors mb-2 leading-snug line-clamp-2"><?= htmlspecialchars(html_entity_decode($sub['title'])) ?></h3>
                                    <p class="text-slate-500 text-sm line-clamp-2 mb-3 flex-1"><?= htmlspecialchars(html_entity_decode($sub['description'])) ?></p>
                                    
                                    <!-- Star Rating -->
                                    <div class="mb-3 scale-90 origin-left">
                                        <?php
                                        $sr_avg = $batch_ratings_profile[$sub['id']]['avg'] ?? 0;
                                        $sr_cnt = $batch_ratings_profile[$sub['id']]['count'] ?? 0;
                                        $sr_user = $batch_user_ratings_profile[$sub['id']] ?? 0;
                                        echo render_stars($sr_avg, $sr_cnt, 'submission', $sub['id'], $sr_user, $is_logged_in);
                                        ?>
                                    </div>
                                    
                                    <!-- Categories -->
                                    <div class="flex flex-wrap gap-1.5 mt-auto pt-2 border-t border-slate-100">
                                        <?= $cat_pills ?>
                                    </div>
                                </div>
                                <div class="px-5 py-3 flex justify-between items-center" style="background:#f8fafc;border-top:1px solid #e2e8f0;">
                                    <span class="text-xs text-slate-400 font-medium"><i class="fa-solid fa-calendar-day mr-1"></i><?= date('M j, Y', strtotime($sub['created_at'])) ?></span>
                                    <span class="text-xs font-bold text-teal-600 group-hover:text-teal-800">View Data <i class="fa-solid fa-arrow-right ml-1"></i></span>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

        </div>

    </main>

    <?php include 'footer.php'; ?>

    <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 sectorElement = document.getElementById('org-sector-select');
            if (!sectorElement) return;
            const sectorKey = sectorElement.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 sectorElement = document.getElementById('org-sector-select');
            if (!sectorElement) return;
            const sectorKey = sectorElement.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);
                });
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            const sectorElement = document.getElementById('org-sector-select');
            if (sectorElement && sectorElement.value) {
                updateSubTypes();
                if (typeof preselectedSubType !== 'undefined' && preselectedSubType) {
                    document.getElementById('org-type-select').value = preselectedSubType;
                    updateSpecialisations();
                    if (typeof preselectedSpec !== 'undefined' && preselectedSpec) {
                        document.getElementById('org-specialisation-select').value = preselectedSpec;
                    }
                }
            }
        });
    </script>
</body>
</html>
