<?php
session_start();
include '../config.php';
include 'auth_check.php'; // Replaces the Auth Check block
require_once '../smtp_mailer.php'; // Moved from inside the if block
require_once 'email-templates.php'; // Replaces admin_email_templates.php and moved from inside the if block

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$submission = null;
$error = null;
$success = null;

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $org_name = htmlspecialchars($_POST['org_name']);
    $title = htmlspecialchars($_POST['title']);
    $contact_person = htmlspecialchars($_POST['contact_person']);
    $contact_role = htmlspecialchars($_POST['contact_role']);
    $email = htmlspecialchars($_POST['email']);
    $mobile = htmlspecialchars($_POST['mobile']);
    $role = htmlspecialchars($_POST['role'] ?? '');
    // Do NOT escape data again, as it's already escaped in DB and we are editing the raw/escaped version.
    // bind_param handles SQL safety.
    $story = $_POST['data'] ?? '';
    $description = htmlspecialchars($_POST['description'] ?? '');
    // Counties: join multi-select array into comma-separated string
    $counties_arr = isset($_POST['counties']) && is_array($_POST['counties']) ? $_POST['counties'] : [];
    $county = implode(', ', array_map('htmlspecialchars', $counties_arr));
    if (empty($county) && !empty($_POST['county'])) {
        $county = htmlspecialchars($_POST['county']); // fallback for old single select
    }
    $status = $_POST['status']; // 'pending', 'approved', 'rejected'

    // Org Sector (JSON)
    $org_sector_data = [];
    if (isset($_POST['org_sector']) && is_array($_POST['org_sector'])) {
        $org_sector_data = array_map('htmlspecialchars', $_POST['org_sector']);
    }
    $org_sector_json = json_encode($org_sector_data);
    $admin_notes = htmlspecialchars($_POST['admin_notes']);
    $is_verified = ($status === 'approved') ? 1 : 0;

    // Handle Service Chains (Array to JSON)
    $service_chains = isset($_POST['service_chains']) ? $_POST['service_chains'] : [];
    $service_chains_json = json_encode($service_chains);

    // Handle Enabling Pillars (Array to JSON)
    $enabling_pillars = isset($_POST['enabling_pillars']) ? $_POST['enabling_pillars'] : [];
    $pillars_json = json_encode($enabling_pillars);

    // Handle Thematic Categories (Array of ints to JSON)
    $thematic_categories = isset($_POST['thematic_categories']) ? array_map('intval', $_POST['thematic_categories']) : [];
    $thematic_json = json_encode($thematic_categories);

    // Read Field Reviews
    $field_reviews = [
        'categories' => [
            'status' => htmlspecialchars($_POST['field_status']['categories'] ?? 'pending'),
            'comment' => htmlspecialchars($_POST['field_comment']['categories'] ?? '')
        ],
        'data' => [
            'status' => htmlspecialchars($_POST['field_status']['data'] ?? 'pending'),
            'comment' => htmlspecialchars($_POST['field_comment']['data'] ?? '')
        ]
    ];
    $field_reviews_json = json_encode($field_reviews);

    if ($id > 0) {
        // Fetch old status for email trigger
        $old_stmt = $conn->prepare("SELECT status FROM submissions WHERE id = ?");
        $old_stmt->bind_param("i", $id);
        $old_stmt->execute();
        $old_status = $old_stmt->get_result()->fetch_assoc()['status'] ?? 'pending';

        // Update
        $stmt = $conn->prepare("UPDATE submissions SET org_name=?, title=?, contact_person=?, contact_role=?, email=?, mobile=?, role=?, story=?, description=?, county=?, is_verified=?, service_chains=?, enabling_pillars=?, thematic_categories=?, status=?, admin_notes=?, field_reviews=?, org_sector=? WHERE id=?");
        $stmt->bind_param("ssssssssssissssssssi", $org_name, $title, $contact_person, $contact_role, $email, $mobile, $role, $story, $description, $county, $is_verified, $service_chains_json, $pillars_json, $thematic_json, $status, $admin_notes, $field_reviews_json, $org_sector_json, $id);

        if ($stmt->execute()) {
            $success = "Submission updated successfully.";

            // Token Lock-in Finalization
            if ($status !== $old_status && in_array($status, ['approved', 'rejected'])) {
                // Fetch the locked token amount and user info
                $tok_fetch = $conn->prepare("SELECT tokens_locked, user_id FROM submissions WHERE id = ?");
                $tok_fetch->bind_param("i", $id);
                $tok_fetch->execute();
                $tok_data = $tok_fetch->get_result()->fetch_assoc();
                $tok_fetch->close();

                $locked_amount = floatval($tok_data['tokens_locked'] ?? 0);
                $sub_user_id = intval($tok_data['user_id'] ?? 0);

                if ($locked_amount > 0 && $sub_user_id > 0) {
                    // Get active subscription
                    $sub_stmt = $conn->prepare("SELECT id, tokens_remaining FROM user_subscriptions WHERE user_id = ? AND status = 'active' LIMIT 1");
                    $sub_stmt->bind_param("i", $sub_user_id);
                    $sub_stmt->execute();
                    $sub_info = $sub_stmt->get_result()->fetch_assoc();
                    $sub_stmt->close();

                    if ($sub_info) {
                        if ($status === 'approved') {
                            // Convert lock → debit: update existing 'lock' transaction
                            $fin = $conn->prepare("UPDATE token_transactions SET transaction_type = 'debit' WHERE user_id = ? AND amount = ? AND transaction_type = 'lock' ORDER BY created_at DESC LIMIT 1");
                            $fin->bind_param("id", $sub_user_id, $locked_amount);
                            $fin->execute();
                            $fin->close();

                            // Clear tokens_locked on submission
                            $clr = $conn->prepare("UPDATE submissions SET tokens_locked = 0 WHERE id = ?");
                            $clr->bind_param("i", $id);
                            $clr->execute();
                            $clr->close();

                        } elseif ($status === 'rejected') {
                            // Refund: add locked tokens back to balance
                            $new_bal = floatval($sub_info['tokens_remaining']) + $locked_amount;
                            $ref_upd = $conn->prepare("UPDATE user_subscriptions SET tokens_remaining = ? WHERE id = ?");
                            $ref_upd->bind_param("di", $new_bal, $sub_info['id']);
                            $ref_upd->execute();
                            $ref_upd->close();

                            // Log refund transaction
                            $ref_desc = "Refund: Submission #$id rejected";
                            $ref_log = $conn->prepare("INSERT INTO token_transactions (user_id, subscription_id, amount, transaction_type, description) VALUES (?, ?, ?, 'refund', ?)");
                            $ref_log->bind_param("iids", $sub_user_id, $sub_info['id'], $locked_amount, $ref_desc);
                            $ref_log->execute();
                            $ref_log->close();

                            // Remove the original lock transaction
                            $del_lock = $conn->prepare("UPDATE token_transactions SET transaction_type = 'refunded_lock' WHERE user_id = ? AND amount = ? AND transaction_type = 'lock' ORDER BY created_at DESC LIMIT 1");
                            $del_lock->bind_param("id", $sub_user_id, $locked_amount);
                            $del_lock->execute();
                            $del_lock->close();

                            // Clear tokens_locked on submission
                            $clr = $conn->prepare("UPDATE submissions SET tokens_locked = 0 WHERE id = ?");
                            $clr->bind_param("i", $id);
                            $clr->execute();
                            $clr->close();

                            $success .= " " . number_format($locked_amount) . " tokens refunded to user.";
                        }
                    }
                }
            }

            // Email Notification Logic
            if ($status !== $old_status && in_array($status, ['approved', 'rejected'])) {
                // require_once 'smtp_mailer.php'; // Moved to top
                // require_once 'admin_email_templates.php'; // Replaced and moved to top

                $mailer = new SmtpMailer(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS);
                if ($status === 'approved') {
                    $subject = "data Approved: $title";
                    $body = get_approval_email($org_name, $title, $admin_notes);
                } else {
                    $subject = "Submission Update: $title";
                    $body = get_rejection_email($org_name, $title, $admin_notes);
                }

                if ($mailer->send($email, $subject, $body)) {
                    $success .= " Notification email sent to $email.";
                } else {
                    $error = "Update saved, but error sending notification email.";
                }
            }
        } else {
            $error = "Error updating submission: " . $conn->error;
        }
    } else {
        // Create (Optional, but good for completeness)
        $stmt = $conn->prepare("INSERT INTO submissions (org_name, title, contact_person, contact_role, email, mobile, role, story, description, county, is_verified, service_chains, enabling_pillars, thematic_categories, status, admin_notes, field_reviews, org_sector) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssssssisssssss", $org_name, $title, $contact_person, $contact_role, $email, $mobile, $role, $story, $description, $county, $is_verified, $service_chains_json, $pillars_json, $thematic_json, $status, $admin_notes, $field_reviews_json, $org_sector_json);

        if ($stmt->execute()) {
            $success = "Submission created successfully.";
            $id = $stmt->insert_id;
        } else {
            $error = "Error creating submission: " . $conn->error;
        }
    }

    // Save Media Reviews if provided
    if ($success && isset($_POST['media_status']) && is_array($_POST['media_status'])) {
        $u_m_stmt = $conn->prepare("UPDATE media_uploads SET admin_status = ?, admin_comment = ? WHERE id = ? AND submission_id = ?");
        foreach ($_POST['media_status'] as $m_id => $m_status) {
            $m_id = intval($m_id);
            $m_status = htmlspecialchars($m_status);
            $m_comment = isset($_POST['media_comment'][$m_id]) ? htmlspecialchars($_POST['media_comment'][$m_id]) : '';
            $u_m_stmt->bind_param("ssii", $m_status, $m_comment, $m_id, $id);
            if ($u_m_stmt->execute() === false) {
                // Ignore silent errors for now
            }
        }
    }
}

// Fetch Submission Data
if ($id > 0) {
    $stmt = $conn->prepare("SELECT * FROM submissions WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $submission = $res->fetch_assoc();

    // Fetch user token balance
    $user_tokens = 0;
    if (!empty($submission['user_id'])) {
        $tok_stmt = $conn->prepare("SELECT tokens_remaining FROM user_subscriptions WHERE user_id = ? AND status = 'active' LIMIT 1");
        $tok_stmt->bind_param("i", $submission['user_id']);
        $tok_stmt->execute();
        $tok_stmt->bind_result($user_tokens);
        $tok_stmt->fetch();
        $tok_stmt->close();
    }

    // Fetch Media Uploads
    $media_uploads = [];
    $m_stmt = $conn->prepare("SELECT id, title, file_path, media_type, file_size, mime_type, caption, original_filename, admin_status, admin_comment FROM media_uploads WHERE submission_id = ?");
    $m_stmt->bind_param("i", $id);
    $m_stmt->execute();
    $m_result = $m_stmt->get_result();
    while ($row = $m_result->fetch_assoc()) {
        $media_uploads[] = $row;
    }

    // Decode field_reviews
    $field_reviews_data = [];
    if (!empty($submission['field_reviews'])) {
        $field_reviews_data = json_decode($submission['field_reviews'], true) ?: [];
    }
}

// Helper for Service Chains
$current_chains = [];
if (isset($submission['service_chains']) && !empty($submission['service_chains'])) {
    $decoded = json_decode($submission['service_chains'], true);
    if (is_array($decoded)) {
        $current_chains = $decoded;
    }
}

// Helper for Enabling Pillars
$current_pillars = [];
if (isset($submission['enabling_pillars']) && !empty($submission['enabling_pillars'])) {
    $decoded = json_decode($submission['enabling_pillars'], true);
    if (is_array($decoded)) {
        $current_pillars = $decoded;
    }
}

// Helper for Thematic Categories
$current_thematic = [];
if (isset($submission['thematic_categories']) && !empty($submission['thematic_categories'])) {
    $decoded = json_decode($submission['thematic_categories'], true);
    if (is_array($decoded)) {
        $current_thematic = $decoded;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo $id > 0 ? 'Edit' : 'Add'; ?> Submission - SaniBook Admin
    </title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
    <style>
        .form-input {
            width: 100%;
            border: 1px solid #e2e8f0;
            border-radius: 0.5rem;
            padding: 0.5rem 1rem;
            outline: none;
            transition: border-color 0.2s;
        }

        .form-input:focus {
            border-color: #3b82f6;
            ring: 2px solid #93c5fd;
        }

        #quill-editor {
            min-height: 250px;
            background: #f8fafc;
        }

        .ql-toolbar.ql-snow {
            border-radius: 0.5rem 0.5rem 0 0;
            border-color: #e2e8f0;
        }

        .ql-container.ql-snow {
            border-radius: 0 0 0.5rem 0.5rem;
            border-color: #e2e8f0;
        }
    </style>
</head>

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

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

    <div class="max-w-4xl mx-auto p-6">
        <div class="flex items-center gap-4 mb-6">
            <a href="submissions.php" class="text-slate-500 hover:text-blue-600"><i
                    class="fa-solid fa-arrow-left mr-1"></i> Back to Submissions</a>
            <h2 class="text-2xl font-bold text-slate-800">
                <?php echo $id > 0 ? 'Edit Submission' : 'Add New Submission'; ?>
            </h2>
        </div>

        <?php if ($error): ?>
            <div class="bg-red-100 text-red-700 p-4 rounded-lg mb-6 border border-red-200">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="bg-green-100 text-green-700 p-4 rounded-lg mb-6 border border-green-200">
                <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-8">
            <form method="POST" class="space-y-6">

                <!-- Organization Details -->
                <div class="p-4 bg-slate-50 rounded-lg border border-slate-200">
                    <h3 class="font-bold text-lg mb-4 text-slate-800 flex items-center justify-between">
                        <span><i class="fa-solid fa-building mr-2"></i>Organization & Project</span>
                        <?php if (isset($user_tokens)): ?>
                            <span class="text-xs bg-blue-100 text-brand-blue px-3 py-1 rounded-full border border-blue-200">
                                <i class="fa-solid fa-coins mr-1"></i> <?php echo number_format($user_tokens); ?> Tokens
                                Available
                            </span>
                        <?php endif; ?>
                    </h3>
                    <div class="grid md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Organization Name</label>
                            <input type="text" name="org_name" required
                                value="<?php echo htmlspecialchars($submission['org_name'] ?? ''); ?>"
                                class="form-input">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Project Title</label>
                            <input type="text" name="title"
                                value="<?php echo htmlspecialchars($submission['title'] ?? ''); ?>" class="form-input">
                        </div>
                    </div>
                </div>

                <!-- Contact Details -->
                <div class="p-4 bg-slate-50 rounded-lg border border-slate-200">
                    <h3 class="font-bold text-lg mb-4 text-slate-800"><i
                            class="fa-solid fa-address-card mr-2"></i>Contact Information</h3>
                    <div class="grid md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Contact Person</label>
                            <input type="text" name="contact_person" required
                                value="<?php echo htmlspecialchars($submission['contact_person'] ?? ''); ?>"
                                class="form-input">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Contact Role</label>
                            <input type="text" name="contact_role"
                                value="<?php echo htmlspecialchars($submission['contact_role'] ?? ''); ?>"
                                class="form-input">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Email</label>
                            <input type="email" name="email" required
                                value="<?php echo htmlspecialchars($submission['email'] ?? ''); ?>" class="form-input">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Mobile</label>
                            <input type="text" name="mobile" required
                                value="<?php echo htmlspecialchars($submission['mobile'] ?? ''); ?>" class="form-input">
                        </div>
                    </div>
                </div>

                <!-- Organization Sector / Type -->
                <?php
                $selected_sector = '';
                $selected_sub = '';
                $selected_spec = '';
                $selected_other = '';
                if (!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="p-4 bg-slate-50 rounded-lg border border-slate-200">
                    <h3 class="font-bold text-sm text-slate-800 mb-3"><i
                            class="fa-solid fa-sitemap mr-2"></i>Organization Sector / Type</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-3">
                        <select id="org-sector-select" name="org_sector[sector]" onchange="updateSubTypes()"
                            class="form-input bg-white">
                            <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 &amp; 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 &amp; 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="form-input bg-white <?php echo empty($selected_sub) ? 'hidden' : ''; ?>">
                            <option value="">Select Sub-Type...</option>
                        </select>

                        <select id="org-specialisation-select" name="org_sector[specialisation]"
                            class="form-input bg-white <?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="form-input bg-white <?php echo $selected_sector === 'Others' ? '' : 'hidden'; ?>">

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

                    <!-- Legacy role field (hidden, auto-filled from sector) -->
                    <input type="hidden" name="role" id="admin-role-hidden"
                        value="<?php echo htmlspecialchars($submission['role'] ?? ''); ?>">
                </div>

                <!-- County (Multi-Select) -->
                <div class="p-4 bg-slate-50 rounded-lg border border-slate-200">
                    <h3 class="font-bold text-sm text-slate-800 mb-3"><i
                            class="fa-solid fa-map-location-dot mr-2"></i>Counties (where the data relates to)</h3>
                    <div class="relative" id="admin-county-multi-select">
                        <div
                            class="flex flex-wrap gap-1.5 p-2.5 border border-slate-200 rounded-lg bg-white min-h-[48px] transition-all focus-within:ring-2 focus-within:ring-blue-500">
                            <div id="admin-selected-counties" class="flex flex-wrap gap-1.5"></div>
                            <input type="text" id="admin-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="admin-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 (!empty($submission['county'])): ?>
                        <script>var preselectedCounties = <?php echo json_encode(array_map('trim', explode(',', $submission['county']))); ?>;</script>
                    <?php endif; ?>
                </div>

                <!-- Service Chains -->
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Service Chains</label>
                    <div class="flex flex-wrap gap-4">
                        <?php
                        $chains = ['Capture & Containment', 'Transport', 'Emptying', 'Treatment', 'Safe Reuse'];
                        foreach ($chains as $chain):
                            $checked = in_array($chain, $current_chains) ? 'checked' : '';
                            ?>
                            <label
                                class="flex items-center space-x-2 p-3 border rounded-lg hover:bg-slate-50 cursor-pointer">
                                <input type="checkbox" name="service_chains[]" value="<?php echo $chain; ?>" <?php echo $checked; ?> class="w-4 h-4 text-blue-600 rounded">
                                <span class="text-sm font-medium text-slate-700">
                                    <?php echo $chain; ?>
                                </span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Enabling Pillars -->
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Enabling Pillars</label>
                    <div class="flex flex-wrap gap-4">
                        <?php
                        $pillar_list = ['Financing', 'Governance', 'Research & Learning', 'Collaboration', 'Menstrual Health Management', 'Capacity Building'];
                        foreach ($pillar_list as $pillar):
                            $p_checked = in_array($pillar, $current_pillars) ? 'checked' : '';
                            ?>
                            <label
                                class="flex items-center space-x-2 p-3 border rounded-lg hover:bg-orange-50 cursor-pointer">
                                <input type="checkbox" name="enabling_pillars[]" value="<?php echo $pillar; ?>" <?php echo $p_checked; ?> class="w-4 h-4 text-orange-500 rounded">
                                <span class="text-sm font-medium text-slate-700"><?php echo $pillar; ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Thematic Categories -->
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Barriers Categories</label>
                    <div class="flex flex-wrap gap-4">
                        <?php
                        $thematic_options = [
                            1 => 'Why Sanitation Matters',
                            2 => 'Coverage Gaps',
                            3 => 'Behavioral Barriers',
                            4 => 'Technology Adoption',
                            5 => 'Chronic Underfunding',
                            6 => 'Fragmented Governance',
                            7 => 'Data Deficiencies',
                            8 => 'Unmet Aspirations',
                            9 => 'Stakeholder Portal',
                        ];
                        foreach ($thematic_options as $t_id => $t_label):
                            $t_checked = in_array($t_id, $current_thematic) ? 'checked' : '';
                            ?>
                            <label
                                class="flex items-center space-x-2 p-3 border rounded-lg hover:bg-teal-50 cursor-pointer">
                                <input type="checkbox" name="thematic_categories[]" value="<?php echo $t_id; ?>" <?php echo $t_checked; ?> class="w-4 h-4 text-teal-500 rounded">
                                <span class="text-sm font-medium text-slate-700"><?php echo $t_label; ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Categories Review Block -->
                <div class="mt-4 p-4 bg-slate-100 rounded-lg border border-slate-200">
                    <h4 class="font-bold text-sm text-slate-800 mb-2">Review Categories</h4>
                    <div class="grid md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-600 mb-1">Status</label>
                            <select name="field_status[categories]" class="form-input text-sm">
                                <option value="pending" <?php echo (($field_reviews_data['categories']['status'] ?? 'pending') === 'pending') ? 'selected' : ''; ?>>Pending</option>
                                <option value="approved" <?php echo (($field_reviews_data['categories']['status'] ?? 'pending') === 'approved') ? 'selected' : ''; ?>>Approved</option>
                                <option value="rejected" <?php echo (($field_reviews_data['categories']['status'] ?? 'pending') === 'rejected') ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-slate-600 mb-1">Comment</label>
                            <input type="text" name="field_comment[categories]"
                                value="<?php echo htmlspecialchars($field_reviews_data['categories']['comment'] ?? ''); ?>"
                                class="form-input text-sm" placeholder="Feedback on categories...">
                        </div>
                    </div>
                </div>

                <!-- Brief Description -->
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Brief Description</label>
                    <textarea name="description" rows="2" class="form-input"
                        placeholder="Max 50 words summary..."><?php echo htmlspecialchars($submission['description'] ?? ''); ?></textarea>
                    <p class="text-xs text-slate-500 mt-1">Short summary (max 50 words) shown in listings.</p>
                </div>

                <!-- data / Content (Rich Text Editor) -->
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Project Description / data</label>
                    <div id="quill-editor"></div>
                    <input type="hidden" name="data" id="hidden-data">
                    <div id="existing-data" style="display:none;">
                        <?php echo html_entity_decode($submission['story'] ?? ''); ?>
                    </div>
                </div>

                <!-- Data Review Block -->
                <div class="mt-4 p-4 bg-slate-100 rounded-lg border border-slate-200">
                    <h4 class="font-bold text-sm text-slate-800 mb-2">Review Content / Data</h4>
                    <div class="grid md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-600 mb-1">Status</label>
                            <select name="field_status[data]" class="form-input text-sm">
                                <option value="pending" <?php echo (($field_reviews_data['data']['status'] ?? 'pending') === 'pending') ? 'selected' : ''; ?>>Pending</option>
                                <option value="approved" <?php echo (($field_reviews_data['data']['status'] ?? 'pending') === 'approved') ? 'selected' : ''; ?>>Approved</option>
                                <option value="rejected" <?php echo (($field_reviews_data['data']['status'] ?? 'pending') === 'rejected') ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-slate-600 mb-1">Comment</label>
                            <input type="text" name="field_comment[data]"
                                value="<?php echo htmlspecialchars($field_reviews_data['data']['comment'] ?? ''); ?>"
                                class="form-input text-sm" placeholder="Feedback on content...">
                        </div>
                    </div>
                </div>

                <!-- Media Display and Review -->
                <?php if (!empty($media_uploads)): ?>
                    <div class="p-6 bg-slate-50 rounded-xl border-2 border-slate-200 mt-6 mb-6">
                        <h3 class="font-bold text-lg mb-4 text-slate-800"><i class="fa-solid fa-photo-video mr-2"></i>Media
                            Review</h3>
                        <div class="space-y-6">
                            <?php foreach ($media_uploads as $media): ?>
                                <div class="bg-white p-4 rounded-lg border border-slate-200">
                                    <!-- Media Info Header -->
                                    <div class="flex items-center justify-between mb-3">
                                        <div>
                                            <h4 class="font-bold text-sm text-slate-800 break-all">
                                                <?php echo htmlspecialchars($media['original_filename'] ?? 'Media Item'); ?>
                                            </h4>
                                            <p class="text-xs text-slate-500">
                                                <?php echo htmlspecialchars($media['caption'] ?? ''); ?>
                                                <span class="ml-2 text-slate-400"><?php echo ucfirst($media['media_type']); ?> &middot; <?php echo $media['file_size'] ? round($media['file_size'] / 1024, 1) . ' KB' : ''; ?></span>
                                            </p>
                                        </div>
                                        <a href="../serve_file.php?id=<?php echo $media['id']; ?>&download=1"
                                            class="text-xs text-blue-600 hover:text-blue-800 font-bold flex items-center gap-1" target="_blank">
                                            <i class="fa-solid fa-download"></i> Download
                                        </a>
                                    </div>

                                    <!-- Inline Media Viewer -->
                                    <div class="mb-4 rounded-lg overflow-hidden border border-slate-200 bg-slate-100">
                                        <?php if ($media['media_type'] === 'image'): ?>
                                            <img src="../serve_file.php?id=<?php echo $media['id']; ?>"
                                                class="w-full max-h-[500px] object-contain bg-white" alt="Image">

                                        <?php elseif ($media['media_type'] === 'video'): ?>
                                            <video src="../serve_file.php?id=<?php echo $media['id']; ?>"
                                                class="w-full max-h-[500px] bg-black" controls preload="metadata"></video>

                                        <?php elseif ($media['media_type'] === 'audio'): ?>
                                            <div class="p-6 bg-gradient-to-br from-slate-50 to-blue-50 flex flex-col items-center gap-4">
                                                <i class="fa-solid fa-headphones text-3xl text-blue-500"></i>
                                                <audio src="../serve_file.php?id=<?php echo $media['id']; ?>" class="w-full" controls preload="metadata"></audio>
                                            </div>

                                        <?php elseif ($media['media_type'] === 'pdf'): ?>
                                            <iframe src="../serve_file.php?id=<?php echo $media['id']; ?>#toolbar=1&navpanes=1"
                                                class="w-full border-0" style="height: 600px;" loading="lazy"></iframe>

                                        <?php else: ?>
                                            <div class="p-6 text-center">
                                                <i class="fa-solid fa-file text-4xl text-slate-400 mb-2"></i>
                                                <span class="block text-xs font-bold text-slate-500">Preview not available</span>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Review Controls -->
                                    <div class="grid md:grid-cols-2 gap-4">
                                        <div>
                                            <label class="block text-xs font-bold text-slate-600 mb-1">Status</label>
                                            <select name="media_status[<?php echo $media['id']; ?>]"
                                                class="form-input text-sm">
                                                <option value="pending" <?php echo (($media['admin_status'] ?? 'pending') === 'pending') ? 'selected' : ''; ?>>Pending</option>
                                                <option value="approved" <?php echo (($media['admin_status'] ?? 'pending') === 'approved') ? 'selected' : ''; ?>>Approved</option>
                                                <option value="rejected" <?php echo (($media['admin_status'] ?? 'pending') === 'rejected') ? 'selected' : ''; ?>>Rejected</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-xs font-bold text-slate-600 mb-1">Comment</label>
                                            <input type="text" name="media_comment[<?php echo $media['id']; ?>]"
                                                value="<?php echo htmlspecialchars($media['admin_comment'] ?? ''); ?>"
                                                class="form-input text-sm" placeholder="Feedback for this file...">
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Moderation Status -->
                <div class="p-6 bg-slate-50 rounded-xl border-2 border-slate-200">
                    <h3 class="font-bold text-lg mb-4 text-slate-800"><i
                            class="fa-solid fa-clipboard-check mr-2"></i>Content Moderation</h3>
                    <div class="grid md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Publishing Status</label>
                            <select name="status" class="form-input bg-white font-bold <?php
                            echo match ($submission['status'] ?? 'pending') {
                                'approved' => 'text-green-600',
                                'rejected' => 'text-red-600',
                                default => 'text-amber-600'
                            };
                            ?>">
                                <option value="pending" <?php echo ($submission['status'] ?? '') === 'pending' ? 'selected' : ''; ?>>Pending Review</option>
                                <option value="approved" <?php echo ($submission['status'] ?? '') === 'approved' ? 'selected' : ''; ?>>Approved / Published</option>
                                <option value="rejected" <?php echo ($submission['status'] ?? '') === 'rejected' ? 'selected' : ''; ?>>Rejected / Requires Changes</option>
                            </select>
                            <p class="text-xs text-slate-500 mt-2">Changing status to Approved or Rejected will trigger
                                an automated email to the user.</p>
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Admin Notes / Feedback (Sent in
                                email)</label>
                            <textarea name="admin_notes" rows="3" class="form-input bg-white"
                                placeholder="Explain the decision or suggest edits..."><?php echo htmlspecialchars($submission['admin_notes'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>

                <div class="pt-4 flex justify-end">
                    <button type="submit"
                        class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-lg shadow-lg transition-all transform hover:scale-105">
                        <i class="fa-solid fa-save mr-2"></i> Save Submission
                    </button>
                </div>

            </form>
        </div>
    </div>
    <script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
    <script>
        var quill = new Quill('#quill-editor', {
            theme: 'snow',
            modules: {
                toolbar: [
                    [{ 'header': [1, 2, 3, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                    ['blockquote', 'link', 'image'],
                    ['clean']
                ]
            },
            placeholder: 'Write the project data here...'
        });

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

        // On form submit, copy Quill content to hidden input and set role from sector
        document.querySelector('form').addEventListener('submit', function () {
            document.getElementById('hidden-data').value = quill.root.innerHTML;
            // Auto-fill role from sector selection for backwards compat
            var sectorVal = document.getElementById('org-sector-select');
            if (sectorVal && sectorVal.value) {
                document.getElementById('admin-role-hidden').value = sectorVal.value;
            }
        });

        // === Organization Sector Taxonomy ===
        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);
                });
            }
        }

        // Init org taxonomy on load (edit mode pre-population)
        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 ===
        (function () {
            const kenyaCounties = ["Mombasa", "Kwale", "Kilifi", "Tana River", "Lamu", "Taita Taveta", "Garissa", "Wajir", "Mandera", "Marsabit", "Isiolo", "Meru", "Tharaka-Nithi", "Embu", "Kitui", "Machakos", "Makueni", "Nyandarua", "Nyeri", "Kirinyaga", "Murang'a", "Kiambu", "Turkana", "West Pokot", "Samburu", "Trans-Nzoia", "Uasin Gishu", "Elgeyo-Marakwet", "Nandi", "Baringo", "Laikipia", "Nakuru", "Narok", "Kajiado", "Kericho", "Bomet", "Kakamega", "Vihiga", "Bungoma", "Busia", "Siaya", "Kisumu", "Homa Bay", "Migori", "Kisii", "Nyamira", "Nairobi"];
            let selectedCounties = [];
            const search = document.getElementById('admin-county-search');
            const dropdown = document.getElementById('admin-county-dropdown');
            const container = document.getElementById('admin-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._removeAdminCounty(\'' + county + '\')"><i class="fa-solid fa-xmark text-[10px]"></i></button>' +
                        '<input type="hidden" name="counties[]" value="' + county + '">';
                    container.appendChild(pill);
                });
            }

            window._removeAdminCounty = function (county) {
                selectedCounties = selectedCounties.filter(c => c !== county);
                updateUI();
            };
            window._addAdminCounty = 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._addAdminCounty(\'' + 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('admin-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>
