<?php
session_start();
require_once 'config.php'; // Ensure db connection
$is_logged_in = isset($_SESSION['user_id']);

// Gate: must be logged in
if (!$is_logged_in) {
    header("Location: signup.php?redirect=submit-data.php");
    exit;
}

$user_name = $_SESSION['user_name'] ?? '';
$user_balance = 0;
$has_subscription = false;

$stmt = $conn->prepare("
    SELECT us.tokens_remaining, sp.name AS package_name
    FROM user_subscriptions us
    JOIN subscription_packages sp ON us.package_id = sp.id
    WHERE us.user_id = ? AND us.status = 'active'
    LIMIT 1
");
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
$stmt->bind_result($user_balance, $sub_title);
if ($stmt->fetch()) {
    // Exclude free Community subscription from accessing submit data
    if (strtolower(trim($sub_title)) !== 'community') {
        $has_subscription = true;
    }
}
$stmt->close();

// Handle Edit Mode
$edit_mode = false;
$submission = [];
$is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
if ($is_logged_in && isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    if ($is_admin) {
        $stmt = $conn->prepare("SELECT * FROM submissions WHERE id = ?");
        $stmt->bind_param("i", $edit_id);
    } else {
        $stmt = $conn->prepare("SELECT * FROM submissions WHERE id = ? AND user_id = ?");
        $stmt->bind_param("ii", $edit_id, $_SESSION['user_id']);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows > 0) {
        $submission = $res->fetch_assoc();
        $edit_mode = true;
    }
    $stmt->close();
}

// Fetch existing media for edit mode
$existing_media = [];
if ($edit_mode && !empty($submission['id'])) {
    $m_stmt = $conn->prepare("SELECT id, title, file_path, media_type, file_size, mime_type, caption, original_filename FROM media_uploads WHERE submission_id = ? ORDER BY id ASC");
    $m_stmt->bind_param("i", $submission['id']);
    $m_stmt->execute();
    $m_result = $m_stmt->get_result();
    while ($row = $m_result->fetch_assoc()) {
        $existing_media[] = $row;
    }
    $m_stmt->close();
}

// Fetch user's drafts if NOT edit mode
$user_drafts = [];
if ($is_logged_in && !$edit_mode) {
    $d_stmt = $conn->prepare("SELECT id, title, created_at FROM submissions WHERE user_id = ? AND status = 'draft' ORDER BY created_at DESC");
    if ($d_stmt) {
        $d_stmt->bind_param("i", $_SESSION['user_id']);
        $d_stmt->execute();
        $d_result = $d_stmt->get_result();
        while ($row = $d_result->fetch_assoc()) {
            $user_drafts[] = $row;
        }
        $d_stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Submit Your Data | SaniBook Kenya | Contribute to National Sanitation Data</title>
    <meta name="description"
        content="Join Kenya's unified sanitation revolution. Submit your organizational projects or individual expertise to SaniBook. Scale your impact, influence policy, and help track SDG 6.2.">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
    <script>
        if (typeof pdfjsLib !== 'undefined') {
            pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';
        }
    </script>

    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brand: {
                            dark: '#0f172a',
                            blue: '#2563eb',
                            cyan: '#0891b2',
                            red: '#dc2626',
                            lime: '#65a30d',
                            gold: '#ca8a04',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        display: ['Space Grotesk', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style>
        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #ffffff;
        }

        .nav-scrolled {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid #e5e7eb;
        }

        .fade-up {
            opacity: 0;
            transform: translateY(24px);
            transition: opacity 0.6s ease, transform 0.6s ease;
        }

        .fade-up.visible {
            opacity: 1;
            transform: translateY(0);
        }

        .menu-open {
            transform: translateX(0);
        }

        .menu-closed {
            transform: translateX(100%);
        }

        .card-hover:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>

<body class="antialiased text-slate-900">

    <!-- Navigation -->
    <?php include 'navbar.php'; ?>

    <!-- Main Content -->
    <main class="pt-20">

        <!-- Header -->
        <header class="bg-slate-50 pt-16 pb-10 text-center">
            <div class="max-w-4xl mx-auto px-4">
                <h1 id="page-title" class="text-3xl md:text-4xl font-display font-bold text-slate-900 mb-4">
                    <?php echo $edit_mode ? 'Update Your Data' : 'Submit Your Data'; ?>
                </h1>
                <p class="text-lg text-slate-600 leading-relaxed mb-6">
                    <?php echo $edit_mode ? 'Refine your submission. Changes will incur a small token fee.' : 'Use your tokens to contribute to the national sanitation database.'; ?>
                </p>
                <div class="inline-block bg-blue-100 text-brand-blue px-6 py-2 rounded-full font-bold">
                    Logged in as: <?php echo htmlspecialchars($user_name); ?>
                </div>
            </div>
        </header>

        <?php if (!$has_subscription): ?>
            <!-- No Subscription Gate -->
            <section class="py-16 bg-white">
                <div class="max-w-2xl mx-auto px-4 text-center">
                    <div class="bg-amber-50 border border-amber-200 rounded-2xl p-10">
                        <div class="text-amber-500 text-5xl mb-6"><i class="fa-solid fa-lock"></i></div>
                        <h2 class="text-2xl font-display font-bold text-slate-900 mb-4">Subscription Required</h2>
                        <p class="text-slate-600 mb-8 leading-relaxed">
                            You need an active subscription with tokens to submit data. Purchase a subscription package to
                            get started.
                        </p>
                        <div class="flex flex-col sm:flex-row gap-4 justify-center">
                            <a href="pricing.php"
                                class="inline-flex items-center justify-center gap-2 px-8 py-4 bg-brand-blue text-white rounded-xl hover:bg-blue-700 transition-all font-bold text-lg">
                                <i class="fa-solid fa-gem"></i> View Subscription Packages
                            </a>
                            <a href="user_dashboard.php"
                                class="inline-flex items-center justify-center gap-2 px-8 py-4 bg-slate-100 text-slate-700 rounded-xl hover:bg-slate-200 transition-all font-bold">
                                <i class="fa-solid fa-arrow-left"></i> Back to Dashboard
                            </a>
                        </div>
                    </div>
                </div>
            </section>
        <?php else: ?>
            <!-- Token Cost Breakdown Banner -->
            <section class="py-6 bg-gradient-to-br from-slate-50 to-blue-50">
                <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
                    <details
                        class="bg-white rounded-2xl shadow-md border border-slate-200 [&_summary::-webkit-details-marker]:hidden group">
                        <summary
                            class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 p-6 md:p-8 cursor-pointer list-none select-none">
                            <div class="flex-1">
                                <h3
                                    class="text-lg font-bold text-slate-900 flex items-center justify-between md:justify-start gap-2">
                                    <span class="flex items-center gap-2"><i class="fa-solid fa-coins text-amber-500"></i>
                                        Understand submission costs</span>
                                    <span
                                        class="md:hidden transition duration-300 group-open:-rotate-180 bg-slate-50 border border-slate-200 rounded-full flex items-center justify-center w-8 h-8">
                                        <i class="fa-solid fa-chevron-down text-slate-500 text-sm"></i>
                                    </span>
                                </h3>
                                <p class="text-sm text-slate-500 mt-1">Tokens are consumed based on what you submit. Your
                                    current balance:
                                    <strong class="text-brand-blue"><?php echo number_format($user_balance); ?>
                                        tokens</strong>
                                </p>
                            </div>
                            <div class="flex items-center gap-4">
                                <a href="pricing.php"
                                    class="inline-flex items-center gap-2 px-6 py-3 bg-brand-blue text-white rounded-xl hover:bg-blue-700 transition-all font-bold text-sm whitespace-nowrap shadow-sm">
                                    <i class="fa-solid fa-gem"></i> Buy Tokens
                                </a>
                                <span
                                    class="hidden md:flex transition duration-300 group-open:-rotate-180 bg-slate-50 border border-slate-200 rounded-full items-center justify-center w-8 h-8">
                                    <i class="fa-solid fa-chevron-down text-slate-500 text-sm"></i>
                                </span>
                            </div>
                        </summary>
                        <div class="px-6 pb-6 md:px-8 md:pb-8 pt-0 border-t border-slate-100 mt-2">
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
                                <div class="bg-blue-50 rounded-xl p-4 text-center border border-blue-100">
                                    <i class="fa-solid fa-font text-blue-500 text-xl mb-2"></i>
                                    <p class="text-2xl font-bold text-slate-900"><?php echo number_format(COST_PER_CHAR); ?>
                                    </p>
                                    <p class="text-xs text-slate-500 mt-1">token / character</p>
                                </div>
                                <div class="bg-purple-50 rounded-xl p-4 text-center border border-purple-100">
                                    <i class="fa-solid fa-image text-purple-500 text-xl mb-2"></i>
                                    <p class="text-2xl font-bold text-slate-900">
                                        <?php echo number_format(COST_PER_IMAGE); ?>
                                    </p>
                                    <p class="text-xs text-slate-500 mt-1">tokens / image</p>
                                </div>
                                <div class="bg-rose-50 rounded-xl p-4 text-center border border-rose-100">
                                    <i class="fa-solid fa-video text-rose-500 text-xl mb-2"></i>
                                    <p class="text-2xl font-bold text-slate-900">
                                        <?php echo number_format(COST_PER_VIDEO_SEC); ?>
                                    </p>
                                    <p class="text-xs text-slate-500 mt-1">tokens / sec video</p>
                                </div>
                                <div class="bg-teal-50 rounded-xl p-4 text-center border border-teal-100">
                                    <i class="fa-solid fa-microphone text-teal-500 text-xl mb-2"></i>
                                    <p class="text-2xl font-bold text-slate-900">
                                        <?php echo number_format(COST_PER_AUDIO_SEC); ?>
                                    </p>
                                    <p class="text-xs text-slate-500 mt-1">tokens / sec audio</p>
                                </div>
                            </div>
                            <div
                                class="mt-4 bg-amber-50 border border-amber-200 rounded-lg px-4 py-3 flex items-start gap-3">
                                <i class="fa-solid fa-circle-info text-amber-600 mt-0.5"></i>
                                <p class="text-sm text-amber-800">
                                    <strong>Multi-category pricing:</strong> Your first category is included in the base
                                    cost.
                                    Each additional Service Chain or Enabling Pillar adds
                                    <strong><?php echo number_format(COST_PER_EXTRA_CATEGORY); ?> tokens</strong>.
                                </p>
                            </div>
                        </div>
                    </details>
                </div>
            </section>

            <!-- Drafts Section -->
            <?php if (!empty($user_drafts) && !$edit_mode): ?>
                <section class="py-6 bg-slate-50">
                    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
                        <div class="bg-blue-50 border border-blue-200 rounded-xl p-6 shadow-sm">
                            <div class="flex items-center gap-3 mb-4">
                                <i class="fa-solid fa-file-pen text-blue-600 text-2xl"></i>
                                <div>
                                    <h3 class="text-lg font-bold text-slate-900">Your Saved Drafts</h3>
                                    <p class="text-sm text-slate-600">You have <?php echo count($user_drafts); ?> draft(s) in
                                        progress. Drafts that are older than 7 days will expire and may be deleted.</p>
                                </div>
                            </div>
                            <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                                <?php foreach ($user_drafts as $draft): ?>
                                    <div
                                        class="bg-white border border-slate-200 rounded-lg p-4 flex flex-col justify-between hover:border-brand-blue hover:shadow-md transition-all">
                                        <div>
                                            <h4 class="font-bold text-slate-800 text-sm mb-1 truncate"
                                                title="<?php echo htmlspecialchars($draft['title']); ?>">
                                                <?php echo htmlspecialchars($draft['title']) ?: 'Untitled Draft'; ?>
                                            </h4>
                                            <p class="text-xs text-slate-500 mb-3">Saved:
                                                <?php echo date('M j, Y g:i A', strtotime($draft['created_at'])); ?>
                                            </p>
                                        </div>
                                        <a href="submit-data.php?edit=<?php echo $draft['id']; ?>"
                                            class="inline-flex items-center justify-center gap-2 w-full py-2 bg-blue-100 hover:bg-blue-200 text-brand-blue rounded text-sm font-bold transition-colors">
                                            <i class="fa-solid fa-pen-to-square"></i> Continue Editing
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </section>
            <?php endif; ?>

            <!-- Submission Form -->
            <section class="py-8 bg-white">
                <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">

                    <div id="form-org" class="p-4 md:p-8">
                        <div class="text-center mb-8 pb-6 border-b border-slate-100">
                            <h2 class="text-2xl md:text-3xl font-bold text-slate-900">
                                <?php echo $edit_mode ? 'Edit Submission' : 'New Submission'; ?>
                            </h2>
                            <p class="text-slate-500 text-sm mt-1">Transform your project data into a national blueprint.
                            </p>
                        </div>
                        <form id="submission-form" class="grid md:grid-cols-2 gap-6">
                            <?php if ($edit_mode && isset($submission['status']) && $submission['status'] === 'draft'): ?>
                                <input type="hidden" name="draft_id" id="draft-id" value="<?php echo $submission['id']; ?>">
                            <?php else: ?>
                                <input type="hidden" name="draft_id" id="draft-id" value="">
                            <?php endif; ?>



                            <!-- Chains & Interventions (Always Visible) -->
                            <div class="md:col-span-2">
                                <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Service
                                    Chain(s)</label>
                                <?php
                                $selected_chains = [];
                                if ($edit_mode && !empty($submission['service_chains'])) {
                                    $selected_chains = json_decode($submission['service_chains'], true) ?? [];
                                }
                                ?>
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                    <?php foreach (["Capture & Containment", "Transport", "Emptying", "Disposal", "Treatment", "Reuse & Circular Economy"] as $chain_val): ?>
                                        <label
                                            class="flex items-center gap-3 p-3 bg-slate-50 rounded-lg cursor-pointer hover:bg-slate-100"><input
                                                type="checkbox" name="service_chains[]" value="<?php echo $chain_val; ?>"
                                                class="rounded text-brand-blue" <?php echo in_array($chain_val, $selected_chains) ? 'checked' : ''; ?>><span
                                                class="text-sm text-slate-700"><?php echo $chain_val; ?></span></label>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- Enabling Pillars -->
                            <div class="md:col-span-2">
                                <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Enabling
                                    Pillar(s) <span class="text-slate-400 font-normal normal-case">(optional)</span></label>
                                <?php
                                $selected_pillars = [];
                                if ($edit_mode && !empty($submission['enabling_pillars'])) {
                                    $selected_pillars = json_decode($submission['enabling_pillars'], true) ?? [];
                                }
                                ?>
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                    <?php
                                    $pillars = [
                                        'Financing' => 'fa-money-bill-wave',
                                        'Governance' => 'fa-scale-balanced',
                                        'Research & Learning' => 'fa-flask',
                                        'Coordination and Collaboration' => 'fa-handshake',
                                        'Menstrual Health Management' => 'fa-venus',
                                        'Capacity Building' => 'fa-graduation-cap',
                                    ];
                                    foreach ($pillars as $pillar => $icon):
                                        $p_checked = in_array($pillar, $selected_pillars) ? 'checked' : '';
                                        ?>
                                        <label
                                            class="flex items-center gap-3 p-3 bg-orange-50 rounded-lg cursor-pointer hover:bg-orange-100 border border-orange-100"><input
                                                type="checkbox" name="enabling_pillars[]" value="<?php echo $pillar; ?>"
                                                class="rounded text-orange-500" <?php echo $p_checked; ?>><i
                                                class="fa-solid <?php echo $icon; ?> text-orange-400"></i><span
                                                class="text-sm text-slate-700"><?php echo $pillar; ?></span></label>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- County (Multi-Select) -->
                            <div class="md:col-span-2">
                                <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Counties
                                    where you work
                                    <span class="text-red-500">*</span>
                                    <div class="relative" id="submit-county-multi-select">
                                        <div
                                            class="flex flex-wrap gap-1.5 p-2.5 border border-slate-200 rounded-lg bg-slate-50 min-h-[48px] transition-all focus-within:ring-2 focus-within:ring-blue-500 focus-within:bg-white">
                                            <div id="submit-selected-counties" class="flex flex-wrap gap-1.5"></div>
                                            <input type="text" id="submit-county-search"
                                                class="flex-1 min-w-[120px] outline-none text-sm bg-transparent border-none focus:ring-0 p-0"
                                                placeholder="Search counties...">
                                        </div>
                                        <div id="submit-county-dropdown"
                                            class="hidden absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-xl max-h-48 overflow-y-auto">
                                        </div>
                                    </div>
                                    <?php if ($edit_mode && !empty($submission['county'])): ?>
                                        <script>var preselectedCounties = <?php echo json_encode(array_map('trim', explode(',', $submission['county']))); ?>;</script>
                                    <?php endif; ?>
                            </div>

                            <!-- Organization Taxonomy -->
                            <div class="md:col-span-2">
                                <label
                                    class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Organization
                                    Sector / Type <span class="text-red-500">*</span></label>

                                <?php
                                $selected_sector = '';
                                $selected_sub = '';
                                $selected_spec = '';
                                $selected_other = '';
                                if ($edit_mode && !empty($submission['org_sector'])) {
                                    $org_data = json_decode($submission['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="grid grid-cols-1 md:grid-cols-3 gap-4 mb-3">
                                    <select id="org-sector-select" name="org_sector[sector]" required
                                        onchange="updateSubTypes()"
                                        class="w-full bg-slate-50 border border-slate-200 rounded-lg px-4 py-3 focus:bg-white focus:border-brand-blue outline-none text-sm transition-colors">
                                        <option value="">Select Sector...</option>
                                        <option value="Public Sector" <?php echo $selected_sector === 'Public Sector' ? 'selected' : ''; ?>>Public Sector</option>
                                        <option value="Private Sector" <?php echo $selected_sector === 'Private Sector' ? 'selected' : ''; ?>>Private Sector</option>
                                        <option value="Civil Society & NGOs" <?php echo $selected_sector === 'Civil Society & NGOs' ? 'selected' : ''; ?>>Civil Society & NGOs</option>
                                        <option value="Financial Institutions" <?php echo $selected_sector === 'Financial Institutions' ? 'selected' : ''; ?>>Financial Institutions</option>
                                        <option value="Research & Academic" <?php echo $selected_sector === 'Research & Academic' ? 'selected' : ''; ?>>Research & Academic</option>
                                        <option value="The Users" <?php echo $selected_sector === 'The Users' ? 'selected' : ''; ?>>The Users</option>
                                        <option value="Others" <?php echo $selected_sector === 'Others' ? 'selected' : ''; ?>>
                                            Others (Please Specify)</option>
                                    </select>

                                    <select id="org-type-select" name="org_sector[sub_type]"
                                        onchange="updateSpecialisations()"
                                        class="w-full bg-slate-50 border border-slate-200 rounded-lg px-4 py-3 focus:bg-white focus:border-brand-blue outline-none text-sm transition-colors <?php echo empty($selected_sub) ? 'hidden' : ''; ?>">
                                        <option value="">Select Sub-Type...</option>
                                    </select>

                                    <select id="org-specialisation-select" name="org_sector[specialisation]"
                                        class="w-full bg-slate-50 border border-slate-200 rounded-lg px-4 py-3 focus:bg-white focus:border-brand-blue outline-none text-sm transition-colors <?php echo empty($selected_spec) ? 'hidden' : ''; ?>">
                                        <option value="">Select Specialisation...</option>
                                    </select>
                                </div>

                                <input type="text" id="org-sector-other" name="org_sector[other]"
                                    placeholder="Please specify your sector/type"
                                    value="<?php echo htmlspecialchars($selected_other, ENT_QUOTES); ?>"
                                    class="w-full bg-slate-50 border border-slate-200 rounded-lg px-4 py-3 focus:bg-white focus:border-brand-blue outline-none text-sm transition-colors <?php echo $selected_sector === 'Others' ? '' : 'hidden'; ?>">

                                <?php if ($edit_mode && !empty($submission['org_sector'])): ?>
                                    <script>
                                        var preselectedSubType = <?php echo json_encode($selected_sub); ?>;
                                        var preselectedSpec = <?php echo json_encode($selected_spec); ?>;
                                    </script>
                                <?php endif; ?>
                            </div>

                            <div class="md:col-span-2">
                                <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Project
                                    Title <span class="text-red-500">*</span></label>
                                <input type="text" name="title"
                                    value="<?php echo $edit_mode ? htmlspecialchars(html_entity_decode($submission['title'], ENT_QUOTES | ENT_HTML5)) : ''; ?>"
                                    class="w-full bg-slate-50 border border-slate-200 rounded-lg px-4 py-3 focus:bg-white focus:border-brand-blue outline-none transition-colors"
                                    required>
                            </div>



                            <!-- Description (Brief) -->
                            <div class="md:col-span-2">
                                <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Brief
                                    Description</label>
                                <textarea name="description" rows="2"
                                    class="w-full bg-slate-50 border border-slate-200 rounded-lg px-4 py-3"
                                    placeholder="Max 50 words summary..."><?php echo $edit_mode ? htmlspecialchars(html_entity_decode($submission['description'] ?? '', ENT_QUOTES | ENT_HTML5)) : ''; ?></textarea>
                            </div>

                            <!-- Rich Text data -->
                            <div class="md:col-span-2 mt-6">
                                <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Full
                                    Data Description (Rich Text)</label>
                                <div class="bg-white border border-slate-200 rounded-lg overflow-hidden">
                                    <div id="quill-editor" class="h-64 bg-slate-50"></div>
                                </div>
                                <input type="hidden" name="data" id="hidden-data">
                                <?php if ($edit_mode && !empty($submission['data'])): ?>
                                    <div id="existing-data" style="display:none;">
                                        <?php echo html_entity_decode($submission['data']); ?>
                                    </div>
                                <?php endif; ?>
                                <p class="text-xs text-slate-500 mt-1 text-right">Character Count: <span
                                        id="char-count">0</span> | Cost: <span id="text-cost">0</span> Tokens</p>
                            </div>

                            <!-- Capacity Grid (Hidden by default, shown by JS) -->
                            <div id="capacity-grid" class="md:col-span-2 mt-4 hidden">
                                <p id="remaining-feedback" class="text-sm text-slate-600 mb-2 font-medium"></p>
                                <div class="grid grid-cols-4 gap-2 text-center text-xs">
                                    <div class="bg-blue-50 p-2 rounded border border-blue-100">
                                        <span class="block font-bold text-brand-blue text-lg" id="cap-text">0</span>
                                        <span class="text-slate-500">Chars</span>
                                    </div>
                                    <div class="bg-lime-50 p-2 rounded border border-lime-100">
                                        <span class="block font-bold text-brand-lime text-lg" id="cap-img">0</span>
                                        <span class="text-slate-500">Images</span>
                                    </div>
                                    <div class="bg-red-50 p-2 rounded border border-red-100">
                                        <span class="block font-bold text-brand-red text-lg" id="cap-vid">0</span>
                                        <span class="text-slate-500">Video Mins</span>
                                    </div>
                                    <div class="bg-yellow-50 p-2 rounded border border-yellow-100">
                                        <span class="block font-bold text-brand-gold text-lg" id="cap-aud">0</span>
                                        <span class="text-slate-500">Audio Mins</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Costs will be moved below media -->

                            <!-- Media Uploads & PDF -->
                            <div class="md:col-span-2 mt-6">
                                <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-2">Media
                                    & Documents</label>
                                <div id="drop-zone"
                                    class="border-2 border-dashed border-slate-300 rounded-lg p-6 text-center hover:bg-slate-50 transition-colors cursor-pointer relative"
                                    onclick="document.getElementById('media-upload').click()">
                                    <i
                                        class="fa-solid fa-cloud-arrow-up text-3xl text-slate-400 mb-2 transition-colors"></i>
                                    <p class="text-slate-600 font-medium">Click or Drag & Drop to upload images, videos,
                                        audio, or PDFs</p>
                                    <p class="text-xs text-slate-400">PDF text is counted towards character cost.</p>
                                    <input type="file" id="media-upload" name="media_files[]" multiple class="hidden"
                                        accept="image/*,video/*,audio/*,.pdf">
                                </div>
                                <div id="file-list" class="mt-4 space-y-2 text-sm text-slate-600"></div>

                                <!-- Drag & Drop Logic Handled by Main Script -->
                                <div class="mt-4 text-center">
                                    <p class="text-xs text-slate-500">Supported formats: Images, Video, Audio, PDF</p>
                                </div>
                            </div>

                            <?php if ($edit_mode): ?>
                                <input type="hidden" name="edit_id" value="<?php echo $submission['id']; ?>">
                                <input type="hidden" name="original_cost" id="original-cost"
                                    value="<?php echo (int) ($submission['last_token_cost'] ?? 0); ?>">

                                <?php if (!empty($existing_media)): ?>
                                    <!-- Current Media Section -->
                                    <div class="md:col-span-2 mt-4">
                                        <label class="block text-slate-700 text-sm font-bold uppercase tracking-wide mb-3">
                                            <i class="fa-solid fa-photo-film mr-1"></i> Current Media
                                            (<?php echo count($existing_media); ?> files)
                                        </label>
                                        <div class="grid gap-4 sm:grid-cols-2">
                                            <?php foreach ($existing_media as $media): ?>
                                                <div class="bg-slate-50 border border-slate-200 rounded-xl overflow-hidden">
                                                    <?php if ($media['media_type'] === 'image'): ?>
                                                        <img src="serve_file.php?id=<?php echo $media['id']; ?>"
                                                            alt="<?php echo htmlspecialchars($media['caption'] ?? $media['original_filename'] ?? 'Image'); ?>"
                                                            class="w-full h-40 object-cover" loading="lazy">
                                                    <?php elseif ($media['media_type'] === 'video'): ?>
                                                        <video controls class="w-full h-40 bg-black object-contain" preload="metadata">
                                                            <source src="serve_file.php?id=<?php echo $media['id']; ?>"
                                                                type="<?php echo htmlspecialchars($media['mime_type'] ?? 'video/mp4'); ?>">
                                                        </video>
                                                    <?php elseif ($media['media_type'] === 'audio'): ?>
                                                        <div class="p-4 flex flex-col items-center justify-center h-40 bg-yellow-50">
                                                            <i class="fa-solid fa-microphone text-3xl text-yellow-600 mb-2"></i>
                                                            <audio controls class="w-full" preload="metadata">
                                                                <source src="serve_file.php?id=<?php echo $media['id']; ?>"
                                                                    type="<?php echo htmlspecialchars($media['mime_type'] ?? 'audio/mpeg'); ?>">
                                                            </audio>
                                                        </div>
                                                    <?php elseif ($media['media_type'] === 'pdf'): ?>
                                                        <div class="p-4 flex flex-col items-center justify-center h-40 bg-red-50">
                                                            <i class="fa-solid fa-file-pdf text-4xl text-red-500 mb-2"></i>
                                                            <a href="serve_file.php?id=<?php echo $media['id']; ?>&download=1"
                                                                class="text-xs text-blue-600 font-bold hover:underline" target="_blank">
                                                                <i class="fa-solid fa-download mr-1"></i> Download PDF
                                                            </a>
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="p-4 flex flex-col items-center justify-center h-40 bg-slate-100">
                                                            <i class="fa-solid fa-file text-3xl text-slate-400 mb-2"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    <div class="p-3 border-t border-slate-200">
                                                        <p class="text-xs font-bold text-slate-700 truncate">
                                                            <?php echo htmlspecialchars($media['original_filename'] ?? $media['title'] ?? 'File'); ?>
                                                        </p>
                                                        <?php if (!empty($media['caption'])): ?>
                                                            <p class="text-[10px] text-slate-500 truncate mt-0.5">
                                                                <?php echo htmlspecialchars($media['caption']); ?>
                                                            </p>
                                                        <?php endif; ?>
                                                        <p class="text-[10px] text-slate-400 mt-1">
                                                            <?php echo strtoupper($media['media_type']); ?>
                                                            <?php if ($media['file_size']): ?>
                                                                &bull; <?php echo round($media['file_size'] / 1024 / 1024, 2); ?> MB
                                                            <?php endif; ?>
                                                        </p>
                                                        <label class="flex items-center gap-2 mt-2 cursor-pointer">
                                                            <input type="checkbox" name="delete_media[]"
                                                                value="<?php echo $media['id']; ?>"
                                                                class="w-3.5 h-3.5 text-red-600 rounded border-slate-300">
                                                            <span class="text-[10px] font-bold text-red-500 uppercase">Remove</span>
                                                        </label>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                        <p class="text-[10px] text-slate-400 mt-2">
                                            <i class="fa-solid fa-circle-info mr-1"></i>
                                            Check "Remove" to delete media on save. Upload new files above to add more.
                                        </p>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>

                            <!-- Overdraft Warning & Upsell UI -->
                            <div id="overdraft-warning"
                                class="hidden md:col-span-2 pt-6 border-t border-slate-200 bg-red-50 rounded-lg p-6 mt-6">
                                <div class="flex items-start gap-4 mb-4">
                                    <div class="text-red-500 text-3xl"><i class="fa-solid fa-triangle-exclamation"></i>
                                    </div>
                                    <div>
                                        <p class="text-red-800 font-bold text-lg">Insufficient Tokens</p>
                                        <p class="text-red-700 text-sm">Your submission requires <span id="needed-tokens"
                                                class="font-bold border-b border-red-300">0</span>
                                            more tokens than your current balance.</p>
                                        <p class="text-slate-600 text-xs mt-1">Don't worry, your data is preserved. Choose
                                            an option to proceed:</p>
                                    </div>
                                </div>
                                <div class="grid md:grid-cols-2 gap-4">
                                    <!-- Option 1: Buy Tokens -->
                                    <div class="bg-white p-4 rounded-lg border border-slate-200 text-center">
                                        <h4 class="font-bold text-slate-800 mb-2">Option 1: Buy Top-up Tokens</h4>
                                        <p class="text-xs text-slate-500 mb-4">Buy additional tokens instantly. (Min
                                            1000, batches of 500 @ KES 1.5/token).</p>
                                        <a href="buy-tokens.php" id="buy-tokens-link"
                                            class="inline-block w-full py-2 bg-brand-blue text-white rounded font-bold text-sm tracking-wide hover:bg-blue-700 transition"
                                            target="_blank">Buy
                                            Tokens</a>
                                    </div>

                                    <!-- Option 2: Upgrade Subscription -->
                                    <div class="bg-white p-4 rounded-lg border border-slate-200 text-center">
                                        <h4 class="font-bold text-slate-800 mb-2">Option 2: Upgrade Subscription</h4>
                                        <p class="text-xs text-slate-500 mb-4">Switch to a higher tier package for more
                                            monthly tokens & features.</p>
                                        <a href="pricing.php"
                                            class="inline-block w-full py-2 bg-brand-lime text-slate-900 rounded font-bold text-sm tracking-wide hover:bg-lime-400 transition"
                                            target="_blank">View
                                            Packages</a>
                                    </div>
                                </div>
                            </div>

                            <!-- Affordability Panel (Wrapper for cost summary to fade it out if unaffordable) -->
                            <div id="affordability-panel"
                                class="md:col-span-2 grid grid-cols-2 md:grid-cols-5 gap-2 text-center text-xs bg-slate-50 p-3 rounded-lg border border-slate-200 mt-6 md:mt-8">
                                <div><span class="block font-bold">Text</span><span id="summary-text">0</span></div>
                                <div><span class="block font-bold">Images</span><span id="summary-images">0</span></div>
                                <div><span class="block font-bold">Video</span><span id="summary-video">0</span></div>
                                <div><span class="block font-bold">Audio</span><span id="summary-audio">0</span></div>
                                <div><span class="block font-bold">PDF</span><span id="summary-pdf">0</span></div>
                                <div class="col-span-2 md:col-span-5 border-t border-slate-200 pt-2 mt-1"><span
                                        class="inline-block font-bold mr-2">Categories:</span><span
                                        id="summary-categories">0</span></div>
                            </div>
                            <div class="md:col-span-2 text-right">
                                <p class="text-lg font-bold text-slate-800">
                                    <?php if ($edit_mode): ?>
                                        Edit Fee (Base 20 + Diff): <span id="total-cost"
                                            class="text-brand-blue text-2xl">0</span>
                                        Tokens
                                    <?php else: ?>
                                        Total Cost: <span id="total-cost" class="text-brand-blue text-2xl">0</span> Tokens
                                        <span class="mx-2 text-slate-300">|</span>
                                        Available: <span
                                            class="text-green-600 font-bold"><?php echo number_format($user_balance); ?></span>
                                        Tokens
                                    <?php endif; ?>
                                </p>
                            </div>

                            <div class="md:col-span-2 pt-6 space-y-3">
                                <div class="flex flex-col sm:flex-row gap-3">
                                    <button type="button" id="save-draft-btn"
                                        class="flex-1 py-4 bg-slate-100 text-slate-700 border border-slate-200 rounded-lg font-bold uppercase tracking-widest hover:bg-slate-200 transition-colors flex justify-center items-center gap-3">
                                        <i class="fa-solid fa-floppy-disk"></i> Save Draft
                                    </button>
                                    <button type="submit"
                                        class="flex-1 py-4 bg-brand-blue text-white rounded-lg font-bold uppercase tracking-widest hover:bg-blue-700 transition-colors shadow-lg flex justify-center items-center gap-3">
                                        <?php
                                        if ($edit_mode) {
                                            echo 'Update Data & Pay Difference';
                                        } else {
                                            echo 'Submit Data & Pay Tokens';
                                        }
                                        ?>
                                        <i class="fa-solid fa-paper-plane"></i>
                                    </button>
                                </div>
                                <p class="text-xs text-center text-slate-400">
                                    <i class="fa-solid fa-circle-info mr-1"></i>
                                    Saving as draft is free. Tokens are only deducted when you submit.
                                </p>
                            </div>
                        </form>
                    </div>

                </div>
            </section>
        <?php endif; ?>

    </main>

    <!-- Footer -->
    <footer class="bg-brand-dark text-white py-16">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-10 mb-12">
                <div class="md:col-span-2">
                    <a href="index.php" class="inline-block font-display font-bold text-2xl mb-4">SaniBook<span
                            class="text-brand-red">.ke</span></a>
                    <p class="text-slate-400 max-w-sm leading-relaxed">The definitive platform unlocking synergy and
                        maximizing impact for Kenya's sanitation sector.</p>
                </div>
            </div>
            <div class="pt-8 border-t border-white/10 flex flex-col sm:flex-row justify-between items-center gap-4">
                <p class="text-slate-500 text-sm">&copy; 2026 SaniBook Kenya. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <script>
        const IS_LOGGED_IN = true;
        const USER_BALANCE = <?php echo json_encode((int) $user_balance); ?>;
        const EDIT_MODE = <?php echo json_encode($edit_mode); ?>;

        let ORG_API_URL = "submit.php?action=submit_data";

        // Use logic for edit url
        if (IS_LOGGED_IN) {
            ORG_API_URL = "submit.php?action=" + (EDIT_MODE ? "update_data" : "submit_data");
            calculateCapacity(USER_BALANCE);
        }

        // --- Quill Init ---
        var quill = new Quill('#quill-editor', {
            theme: 'snow',
            placeholder: 'Write your full data description here...',
            modules: {
                toolbar: {
                    container: [[{ 'header': [1, 2, 3, false] }], ['bold', 'italic', 'underline'], [{ 'list': 'ordered' }, { 'list': 'bullet' }], ['image'], ['clean']],
                    handlers: {
                        'video': function () {
                            alert("Video embedding is disabled in the text editor. Please use the 'Media & Documents' upload section below for video files.");
                        }
                    }
                }
            }
        });

        // Load existing data HTML into Quill as rich text (edit mode)
        var existingStory = document.getElementById('existing-data');
        if (existingStory && existingStory.innerHTML.trim()) {
            quill.clipboard.dangerouslyPasteHTML(existingStory.innerHTML);
        }

        quill.on('text-change', function () {
            calculateTotal();
        });

        // Recalculate when categories change (multi-category surcharge)
        document.querySelectorAll('input[name="service_chains[]"], input[name="enabling_pillars[]"]').forEach(cb => {
            cb.addEventListener('change', calculateTotal);
        });

        // --- File & Calculator Logic ---
        const fileInput = document.getElementById('media-upload');
        const fileList = document.getElementById('file-list');
        let selectedFiles = [];

        if (fileInput) {
            fileInput.addEventListener('change', (e) => {
                const files = e.target.files;
                for (let file of files) { addFile(file); }
                fileInput.value = '';
            });
        }

        async function addFile(file) {
            const id = Date.now() + Math.random().toString(36).substr(2, 9);
            const fileObj = { id, file, duration: 0, pdfCharCount: 0 };
            selectedFiles.push(fileObj);

            // Render immediately with 0/loading
            renderFile(fileObj);

            // Attempt to detect duration for Audio/Video
            if (file.type.startsWith('video') || file.type.startsWith('audio')) {
                const media = document.createElement(file.type.startsWith('video') ? 'video' : 'audio');
                media.preload = 'metadata';
                media.onloadedmetadata = function () {
                    window.URL.revokeObjectURL(media.src);
                    const duration = Math.round(media.duration);
                    updateDuration(id, duration);
                    // Update UI input value
                    const input = document.getElementById(`duration-${id}`);
                    if (input) {
                        input.value = duration;
                        input.classList.add('bg-green-50', 'border-green-300', 'text-green-700');
                    }
                }
                media.onerror = function () {
                    console.log("Could not load media metadata for " + file.name);
                }
                media.src = URL.createObjectURL(file);
            }

            // Handle PDF Text Extraction
            if (file.type === 'application/pdf') {
                if (typeof pdfjsLib === 'undefined') {
                    console.error("PDF.js library not loaded");
                    alert("PDF processing library missing. Token count may be inaccurate.");
                    return;
                }

                try {
                    const loadingTask = pdfjsLib.getDocument(URL.createObjectURL(file));
                    const pdf = await loadingTask.promise;
                    let fullText = '';
                    for (let i = 1; i <= pdf.numPages; i++) {
                        const page = await pdf.getPage(i);
                        const textContent = await page.getTextContent();
                        const pageText = textContent.items.map(item => item.str).join(' ');
                        fullText += pageText + ' ';
                    }
                    const pdfChars = fullText.length;
                    const f = selectedFiles.find(f => f.id === id);
                    if (f) {
                        f.pdfCharCount = pdfChars;
                        calculateTotal();
                        // Update UI
                        const row = document.getElementById(`file-row-${id}`);
                        if (row) {
                            const infoSpan = row.querySelector('.file-info');
                            if (infoSpan) infoSpan.innerHTML += ` <span class="bg-blue-100 text-blue-800 text-[10px] font-bold px-2 py-0.5 rounded ml-2">${pdfChars.toLocaleString()} Chars</span>`;

                            // Update the duration/status div (inside the right-side flex container)
                            const statusDiv = row.querySelector('.italic');
                            if (statusDiv && statusDiv.textContent.includes('Extracting')) {
                                statusDiv.innerHTML = '<span class="text-xs text-green-600 font-bold"><i class="fa-solid fa-check"></i> Ready</span>';
                            }
                        }
                    }
                } catch (err) {
                    console.error("PDF Error:", err);
                    alert("Could not read PDF text. Please ensure it is a valid PDF.");
                }
            }

            calculateTotal();
        }

        if (fileInput) {
            fileInput.addEventListener('change', (e) => {
                const files = e.target.files;
                for (let file of files) { addFile(file); }
                fileInput.value = '';
            });
        }

        // --- Drag & Drop Logic ---
        const dropZone = document.getElementById('drop-zone');
        if (dropZone) {
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, preventDefaults, false);
                document.body.addEventListener(eventName, preventDefaults, false);
            });

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            ['dragenter', 'dragover'].forEach(eventName => {
                dropZone.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, unhighlight, false);
            });

            function highlight(e) {
                dropZone.classList.add('border-brand-blue', 'bg-blue-50');
                dropZone.classList.remove('border-slate-300');
            }

            function unhighlight(e) {
                dropZone.classList.remove('border-brand-blue', 'bg-blue-50');
                dropZone.classList.add('border-slate-300');
            }

            dropZone.addEventListener('drop', handleDrop, false);

            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                if (files.length > 0) {
                    for (let file of files) { addFile(file); }
                }
            }
        }

        function removeFile(id) {
            if (!confirm("Are you sure you want to remove this file?")) {
                return;
            }
            selectedFiles = selectedFiles.filter(f => f.id !== id);
            document.getElementById(`file-row-${id}`).remove();
            calculateTotal();
        }

        function updateDuration(id, seconds) {
            const f = selectedFiles.find(f => f.id === id);
            if (f) { f.duration = parseFloat(seconds) || 0; calculateTotal(); }
        }

        function renderFile(fileObj) {
            const isMedia = fileObj.file.type.startsWith('video') || fileObj.file.type.startsWith('audio');
            const isPdf = fileObj.file.type === 'application/pdf';
            let icon = 'fa-file';
            if (fileObj.file.type.startsWith('image')) icon = 'fa-image text-brand-lime';
            else if (fileObj.file.type.startsWith('video')) icon = 'fa-video text-brand-red';
            else if (fileObj.file.type.startsWith('audio')) icon = 'fa-microphone text-brand-gold';
            else if (isPdf) icon = 'fa-file-pdf text-red-500';

            const div = document.createElement('div');
            div.id = `file-row-${fileObj.id}`;
            div.className = "bg-slate-50 p-3 rounded-lg border border-slate-200 space-y-2";

            let durationInput = isMedia ? `<div class="flex items-center gap-2"><label class="text-xs font-bold text-slate-500 uppercase">Secs:</label><input type="number" id="duration-${fileObj.id}" onchange="updateDuration('${fileObj.id}', this.value)" class="w-20 px-2 py-1 text-sm border border-slate-300 rounded focus:border-brand-blue outline-none transition-colors" placeholder="0"></div>` : '';
            if (isPdf) durationInput = '<div class="text-xs text-slate-400 italic">Extracting text...</div>';

            // Show caption input for images and audio
            const showCaption = fileObj.file.type.startsWith('image') || fileObj.file.type.startsWith('audio');
            const captionInput = showCaption ? `<div class="flex items-center gap-2 mt-1"><label class="text-xs font-bold text-slate-500 uppercase whitespace-nowrap">Caption:</label><input type="text" data-caption-for="${fileObj.file.name}" placeholder="Add a caption…" class="flex-1 px-2 py-1 text-sm border border-slate-300 rounded focus:border-brand-blue outline-none transition-colors" maxlength="500"></div>` : '';

            div.innerHTML = `<div class="flex items-center justify-between"><div class="flex items-center gap-3 overflow-hidden file-info"><i class="fa-solid ${icon} text-lg"></i><span class="text-sm font-medium text-slate-700 truncate max-w-[150px]">${fileObj.file.name}</span><span class="text-xs text-slate-400">(${(fileObj.file.size / 1024 / 1024).toFixed(2)} MB)</span></div><div class="flex items-center gap-4">${durationInput}<button type="button" onclick="removeFile('${fileObj.id}')" class="text-slate-400 hover:text-red-500"><i class="fa-solid fa-trash"></i></button></div></div>${captionInput}`;
            fileList.appendChild(div);
        }

        function calculateTotal() {
            const COST_CHAR = <?php echo COST_PER_CHAR; ?>;
            const COST_IMAGE = <?php echo COST_PER_IMAGE; ?>;
            const COST_VIDEO_SEC = <?php echo COST_PER_VIDEO_SEC; ?>;
            const COST_AUDIO_SEC = <?php echo COST_PER_AUDIO_SEC; ?>;
            const COST_EXTRA_CAT = <?php echo COST_PER_EXTRA_CATEGORY; ?>;
            const BASE_EDIT_FEE = 20; // Default Fee for editing

            const content = quill.root.innerHTML;
            const text = quill.getText(); // Pure text

            // Count Inline Images
            const imgCount = (content.match(/<img /g) || []).length;

            // 1. Text Cost (Excluding HTML tags implicitly by using getText())
            // Note: Base64 strings in img tags are NOT in getText(), so this is safe.
            const charCount = text.trim().length;
            let textCost = charCount * COST_CHAR;

            // 2. Inline Image Cost
            let inlineImageCost = imgCount * COST_IMAGE;

            let imageCost = 0, videoCost = 0, audioCost = 0, pdfCost = 0;

            selectedFiles.forEach(f => {
                if (f.file.type.startsWith('image')) imageCost += COST_IMAGE;
                if (f.file.type.startsWith('video')) videoCost += (f.duration * COST_VIDEO_SEC);
                if (f.file.type.startsWith('audio')) audioCost += (f.duration * COST_AUDIO_SEC);
                if (f.file.type === 'application/pdf') pdfCost += (f.pdfCharCount * COST_CHAR);
            });

            // Calculate Raw Total
            let categoryCost = 0;
            const chainChecked = document.querySelectorAll('input[name="service_chains[]"]\:checked').length;
            const pillarChecked = document.querySelectorAll('input[name="enabling_pillars[]"]\:checked').length;
            const totalCats = chainChecked + pillarChecked;
            if (totalCats > 1) {
                categoryCost = (totalCats - 1) * COST_EXTRA_CAT;
            }
            let total = textCost + imageCost + inlineImageCost + videoCost + audioCost + pdfCost + categoryCost;

            // Handle Edit Mode Cost Calculation
            if (EDIT_MODE) {
                const originalCost = parseInt(document.getElementById('original-cost').value || 0);
                // Cost is Base Fee + Difference (if new is more expensive)
                // If new is cheaper, we just pay base fee.
                let diff = Math.max(0, total - originalCost);
                total = BASE_EDIT_FEE + diff;
            }

            // Update UI
            document.getElementById('total-cost').innerText = total.toLocaleString();
            document.getElementById('summary-text').innerText = textCost.toLocaleString();
            document.getElementById('summary-images').innerHTML = (imageCost + inlineImageCost).toLocaleString() + (imgCount > 0 ? ` <span class="text-[10px] text-slate-400">(${imgCount} inline)</span>` : '');
            document.getElementById('summary-video').innerText = videoCost.toLocaleString();
            document.getElementById('summary-audio').innerText = audioCost.toLocaleString();
            document.getElementById('summary-pdf').innerText = pdfCost.toLocaleString();
            document.getElementById('summary-categories').innerText = categoryCost.toLocaleString();

            // Update Character Count Display
            document.getElementById('char-count').innerText = charCount;
            document.getElementById('text-cost').innerText = textCost.toLocaleString();

            // Sync hidden input with HTML content (including images)
            document.getElementById('hidden-data').value = content;

            // Check Balance (If Logged In)
            if (IS_LOGGED_IN) {
                const balance = USER_BALANCE;
                const remaining = balance - total;
                const submitBtn = document.querySelector('#submission-form button[type="submit"]');
                const warningDiv = document.getElementById('overdraft-warning');
                const affordDiv = document.getElementById('affordability-panel');

                if (remaining < 0) {
                    // Overdraft
                    let needed = total - balance;
                    submitBtn.disabled = true;
                    submitBtn.classList.add('opacity-50', 'cursor-not-allowed');
                    warningDiv.classList.remove('hidden');
                    document.getElementById('needed-tokens').innerText = needed.toLocaleString();
                    document.getElementById('buy-tokens-link').href = 'buy-tokens.php?needed=' + needed;
                    affordDiv.classList.add('opacity-50');
                    document.getElementById('remaining-feedback').innerText = "Limit Exceeded";
                    document.getElementById('capacity-grid').classList.add('hidden');
                } else {
                    // Affordable
                    submitBtn.disabled = false;
                    submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                    warningDiv.classList.add('hidden');
                    affordDiv.classList.remove('opacity-50');
                    calculateCapacity(remaining);
                }
            }
        }

        function calculateCapacity(tokens) {
            const COST_CHAR = <?php echo COST_PER_CHAR; ?>;
            const COST_IMAGE = <?php echo COST_PER_IMAGE; ?>;
            const COST_VIDEO_SEC = <?php echo COST_PER_VIDEO_SEC; ?>;
            const COST_AUDIO_SEC = <?php echo COST_PER_AUDIO_SEC; ?>;
            const capText = Math.floor(tokens / COST_CHAR);
            const capImg = Math.floor(tokens / COST_IMAGE);
            const capVid = (tokens / COST_VIDEO_SEC / 60).toFixed(1); // Mins
            const capAud = (tokens / COST_AUDIO_SEC / 60).toFixed(1); // Mins

            document.getElementById('remaining-feedback').innerText = "Based on your current balance, you can still add ANY ONE of the following:";
            document.getElementById('capacity-grid').classList.remove('hidden');

            document.getElementById('cap-text').innerText = capText > 999 ? (capText / 1000).toFixed(1) + 'k' : capText;
            document.getElementById('cap-img').innerText = capImg;
            document.getElementById('cap-vid').innerText = capVid;
            document.getElementById('cap-aud').innerText = capAud;
        }

    </script>

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

    <script>
        // --- SUBMIT LOGIC ---
        const submissionForm = document.getElementById('submission-form');
        if (submissionForm) {
            submissionForm.addEventListener('submit', async (e) => {
                e.preventDefault(); // CRITICAL: Stop reload immediately

                const btn = submissionForm.querySelector('button[type="submit"]');
                const originalText = btn.innerHTML;

                try {
                    document.getElementById('hidden-data').value = quill.root.innerHTML;

                    // Client-Side Validation — Service Chain is mandatory
                    const serviceChains = document.querySelectorAll('input[name="service_chains[]"]:checked');
                    const enablingPillars = document.querySelectorAll('input[name="enabling_pillars[]"]:checked');

                    if (serviceChains.length === 0) {
                        alert("Please select at least one Service Chain category.");
                        return;
                    }

                    btn.disabled = true;
                    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';

                    const formData = new FormData(submissionForm);

                    // Append actual files
                    selectedFiles.forEach((f) => {
                        formData.append('media_files[]', f.file);
                    });

                    // Append captions (keyed by original filename)
                    document.querySelectorAll('[data-caption-for]').forEach(input => {
                        const filename = input.getAttribute('data-caption-for');
                        if (input.value.trim()) {
                            formData.append(`media_captions[${filename}]`, input.value.trim());
                        }
                    });

                    // Append metadata
                    const metadata = selectedFiles.map(f => ({
                        name: f.file.name,
                        duration: f.duration || 0,
                        chars: f.pdfCharCount || 0 // Backend expects 'chars' key based on logic
                    }));
                    formData.append('media_meta', JSON.stringify(metadata));

                    const response = await fetch(ORG_API_URL, {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();

                    if (result.status === 'success') {
                        alert("Success! " + result.message);
                        window.location.href = 'user_dashboard.php';
                    } else if (result.status === 'pending_verification') {
                        alert("Data submitted successfully! Please check your email to verify your account and to access your dashboard.");
                        window.location.href = 'login.php';
                    } else {
                        throw new Error(result.message || "Submission failed");
                    }
                } catch (err) {
                    console.error("Submission Error:", err);
                    alert("Error: " + (err.message || "An unexpected error occurred."));
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                }
            });

            // --- SAVE DRAFT LOGIC ---
            const draftBtn = document.getElementById('save-draft-btn');

            async function saveDraft(isAutoSave = false) {
                try {
                    document.getElementById('hidden-data').value = quill.root.innerHTML;
                    if (!isAutoSave && draftBtn) {
                        draftBtn.disabled = true;
                        draftBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';
                    }

                    const formData = new FormData(submissionForm);
                    selectedFiles.forEach((f) => { formData.append('media_files[]', f.file); });
                    document.querySelectorAll('[data-caption-for]').forEach(input => {
                        const filename = input.getAttribute('data-caption-for');
                        if (input.value.trim()) formData.append(`media_captions[${filename}]`, input.value.trim());
                    });
                    const metadata = selectedFiles.map(f => ({ name: f.file.name, duration: f.duration || 0, chars: f.pdfCharCount || 0 }));
                    formData.append('media_meta', JSON.stringify(metadata));

                    const response = await fetch('submit.php?action=save_draft', { method: 'POST', body: formData });
                    const result = await response.json();

                    if (result.status === 'success') {
                        if (result.draft_id) {
                            const draftIdInput = document.getElementById('draft-id');
                            if (draftIdInput) draftIdInput.value = result.draft_id;
                        }
                        if (!isAutoSave) {
                            alert('Draft saved! You can continue editing later from your dashboard.');
                            window.location.href = 'user_dashboard.php';
                        }
                    } else {
                        if (!isAutoSave) throw new Error(result.message || 'Failed to save draft');
                    }
                } catch (err) {
                    console.error('Draft Error:', err);
                    if (!isAutoSave) {
                        alert('Error: ' + (err.message || 'An unexpected error occurred.'));
                        if (draftBtn) {
                            draftBtn.disabled = false;
                            draftBtn.innerHTML = '<i class="fa-regular fa-bookmark"></i> Save Draft';
                        }
                    }
                }
            }

            if (draftBtn) {
                draftBtn.addEventListener('click', () => saveDraft(false));
            }

            // Autosave every 5 minutes (300000 ms)
            setInterval(() => {
                const title = document.querySelector('input[name="title"]')?.value.trim();
                const text = quill.getText().trim();
                if ((title && title !== '') || (text && text !== '')) {
                    saveDraft(true);
                }
            }, 300000);

            // Auto-save when clicking Pricing link
            document.querySelectorAll('a[href*="pricing.php"]').forEach(link => {
                link.addEventListener('click', (e) => {
                    const title = document.querySelector('input[name="title"]')?.value.trim();
                    const text = quill.getText().trim();
                    if ((title && title !== '') || (text && text !== '')) {
                        saveDraft(true);
                    }
                });
            });
        }
    </script>
    <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);
                });
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            if (document.getElementById('org-sector-select').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;
                    }
                }
            }
        });

        // County Multi-Select Logic
        (function () {
            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 = [];
            const search = document.getElementById('submit-county-search');
            const dropdown = document.getElementById('submit-county-dropdown');
            const container = document.getElementById('submit-selected-counties');
            if (!search || !dropdown || !container) return;

            function updateUI() {
                container.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.5 py-1 rounded-md text-xs font-semibold';
                    pill.innerHTML = '<span>' + county + '</span>' +
                        '<button type="button" class="hover:text-red-500 ml-1" onclick="window._removeSubmitCounty(\'' + county + '\')">' +
                        '<i class="fa-solid fa-xmark text-[10px]"></i></button>' +
                        '<input type="hidden" name="counties[]" value="' + county + '">';
                    container.appendChild(pill);
                });
            }

            window._removeSubmitCounty = function (county) {
                selectedCounties = selectedCounties.filter(c => c !== county);
                updateUI();
            };
            window._addSubmitCounty = function (county) {
                if (!selectedCounties.includes(county)) {
                    selectedCounties.push(county);
                    updateUI();
                }
                search.value = '';
                dropdown.classList.add('hidden');
            };

            search.addEventListener('input', function (e) {
                const val = e.target.value.toLowerCase();
                if (!val) { dropdown.classList.add('hidden'); return; }
                const filtered = kenyaCounties.filter(c => c.toLowerCase().includes(val) && !selectedCounties.includes(c));
                if (filtered.length > 0) {
                    dropdown.innerHTML = filtered.map(c => '<div onmousedown="event.preventDefault(); window._addSubmitCounty(\'' + c + '\')" class="px-3 py-2 hover:bg-slate-50 cursor-pointer text-sm border-b border-slate-50 last:border-0">' + c + '</div>').join('');
                    dropdown.classList.remove('hidden');
                } else {
                    dropdown.classList.add('hidden');
                }
            });

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

            // Pre-select counties in edit mode
            if (typeof preselectedCounties !== 'undefined' && Array.isArray(preselectedCounties)) {
                preselectedCounties.forEach(function (c) { if (c) selectedCounties.push(c); });
                updateUI();
            }
        })();
    </script>
</body>

</html>