<?php
/**
 * Posts Management Page
 * SSCI Office Platform - Facility & Site Assessment Management
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('posts') . ' - ' . config('app.name');

$action = $_GET['action'] ?? 'list';

require_once __DIR__ . '/../../layouts/header.php';

// Handle assessment report view
if ($action === 'assessment_report') {
    if (!isset($_GET['id'])) {
        header('Location: ?page=posts');
        exit();
    }
    
    $post = $db->fetch("SELECT p.*, u.name as owner_name, creator.name as created_by_name FROM posts p LEFT JOIN users u ON p.owner_id = u.id LEFT JOIN users creator ON p.created_by = creator.id WHERE p.id = ?", [$_GET['id']]);
    if (!$post) {
        header('Location: ?page=posts');
        exit();
    }
    
    // Get company settings from database
    $settings = $db->fetch("SELECT * FROM settings LIMIT 1");
    
    // Prepare assessment report variables
    $facility = $post;
    $assessment_id = 'ASS-' . $post['id'] . '-' . date('Ymd');
    $primary_color = $settings['primary_color'] ?? '#2563eb';
    $site_logo = $settings['logo'] ?? null;
    $site_letterhead = $settings['letterhead'] ?? null;
    
    // Render the assessment report
    require SSCI_VIEWS . '/components/posts_assessment_report.php';
    exit();
}

// Handle contract view
if ($action === 'view_contract') {
    if (!isset($_GET['id'])) {
        header('Location: ?page=posts');
        exit();
    }
    
    $post = $db->fetch("SELECT p.*, u.name as owner_name, creator.name as created_by_name FROM posts p LEFT JOIN users u ON p.owner_id = u.id LEFT JOIN users creator ON p.created_by = creator.id WHERE p.id = ?", [$_GET['id']]);
    if (!$post) {
        header('Location: ?page=posts');
        exit();
    }
    
    // Get company settings from database for contract data
    $settings = $db->fetch("SELECT * FROM settings LIMIT 1");
    
    // Prepare contract variables
    $contract_number = 'FA-' . $post['id'] . '-' . date('Y');
    $contract_date = date('Y-m-d');
    $contract_start = $post['contract_date'] ?? date('Y-m-d');
    $contract_end = $post['contract_end'] ?? date('Y-m-d', strtotime('+12 months'));
    
    $primary_color = $settings['primary_color'] ?? '#D2691E';
    $company_name = $settings['site_name'] ?? 'Shepherd Security & Consultancy International';
    $company_acronym = $settings['site_acronym'] ?? 'SSCI';
    $company_address = $settings['address'] ?? 'Opposite PCSS Buea Town, P.O.Box 554, Buea';
    $company_contact = $settings['phone'] ?? 'Tel: (237) 676037526';
    $company_rep_name = 'Authorized Representative';
    
    $client_name = $post['owner_name'] ?? 'Facility Owner';
    $facility_location = $post['location'] ?? '';
    $facility_type = $post['facility_type'] ?? 'Facility';
    $facility_name = $post['name'] ?? 'Facility';
    $facility_owner = $post['owner_name'] ?? 'Owner';
    $facility_owner_rep = $post['owner_name'] ?? 'Facility Owner Representative';
    $guards_assigned = $post['guards_assigned'] ?? '2-4';
    
    // Build service lines from post data
    $service_lines = [];
    $grand_total = 0;
    
    // Parse services from JSON format stored in services field
    if (!empty($post['services'])) {
        $services_data = json_decode($post['services'], true);
        if (is_array($services_data)) {
            foreach ($services_data as $service) {
                // Handle both old and new format
                $unit_cost = (float)($service['unit_cost'] ?? $service['unit'] ?? 0);
                $qty = (float)($service['qty'] ?? 0);
                $total = $unit_cost * $qty;
                $grand_total += $total;
                
                $service_lines[] = [
                    'ref' => $service['ref'] ?? '',
                    'description' => $service['name'] ?? $service['description'] ?? '',
                    'qty' => $qty,
                    'unit' => $unit_cost,
                    'total' => $total
                ];
            }
        }
    }
    
    // Fallback to default service if no services found
    if (empty($service_lines)) {
        $service_lines = [
            [
                'ref' => '1',
                'description' => 'Facility Security Services - ' . htmlspecialchars($facility_type),
                'qty' => 1,
                'unit' => 40000,
                'total' => 40000
            ]
        ];
        $grand_total = 40000;
    }
    
    // Convert total to words
    $amount_in_words = ucfirst(number_to_words($grand_total));
    
    // Get show_watermark setting
    $show_watermark = true;
    $watermark_text = 'SHEPHERD SECURITY';
    
    // Output contract
    ob_start();
    include __DIR__ . '/../../components/posts_contract.php';
    $contractHtml = ob_get_clean();
    
    // If print/PDF request
    if (!empty($_GET['print'])) {
        header('Content-Type: text/html; charset=utf-8');
        echo $contractHtml;
        exit();
    }
    
    // Otherwise show in modal or page
    echo $contractHtml;
    require_once __DIR__ . '/../../layouts/footer.php';
    exit();
}

if ($action === 'list'): ?>

    <div class="animate__animated animate__fadeIn">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-800">
                <i class="fas fa-building text-blue-600 mr-3"></i><?php echo trans('facilities') ?? 'Facilities & Posts'; ?>
            </h1>
            <a href="?page=posts&action=create" class="bg-gradient-to-r from-blue-600 to-blue-700 text-white px-6 py-3 rounded-lg hover:from-blue-700 hover:to-blue-800 transition font-semibold flex items-center">
                <i class="fas fa-plus mr-2"></i> <?php echo trans('add_facility') ?? 'Add Facility'; ?>
            </a>
        </div>

        <!-- Desktop Table View -->
        <div class="hidden md:block bg-white rounded-lg shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full">
                    <thead class="bg-gray-50 border-b-2 border-gray-200">
                        <tr>
                            <th class="text-left px-6 py-4 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('facility_name') ?? 'Facility Name'; ?></th>
                            <th class="text-left px-6 py-4 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('facility_type') ?? 'Type'; ?></th>
                            <th class="text-left px-6 py-4 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('owner') ?? 'Owner'; ?></th>
                            <th class="text-left px-6 py-4 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('risk_level') ?? 'Risk Level'; ?></th>
                            <th class="text-left px-6 py-4 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('status') ?? 'Status'; ?></th>
                            <th class="text-left px-6 py-4 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('actions') ?? 'Actions'; ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                    <?php
                    $posts = $db->fetchAll("SELECT p.*, u.name as owner_name, creator.name as created_by_name FROM posts p LEFT JOIN users u ON p.owner_id = u.id LEFT JOIN users creator ON p.created_by = creator.id WHERE p.status = 'Active' LIMIT 50");
                    if (empty($posts)): ?>
                        <tr>
                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                <i class="fas fa-inbox text-4xl mb-4 opacity-20 block"></i>
                                <?php echo trans('no_facilities_yet') ?? 'No facilities added yet'; ?>
                            </td>
                        </tr>
                    <?php else: 
                        foreach ($posts as $post):
                    ?>
                    <tr class="hover:bg-gray-50 transition">
                        <td class="px-6 py-4">
                            <div class="font-semibold text-gray-900"><?php echo htmlspecialchars($post['name']); ?></div>
                            <div class="text-sm text-gray-500"><?php echo htmlspecialchars($post['location'] ?? '-'); ?></div>
                        </td>
                        <td class="px-6 py-4">
                            <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm font-medium">
                                <?php echo htmlspecialchars($post['facility_type'] ?? '-'); ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-gray-700"><?php echo htmlspecialchars($post['owner_name'] ?? '-'); ?></td>
                        <td class="px-6 py-4">
                            <?php 
                            $riskScore = (int)($post['overall_risk_score'] ?? 0);
                            $riskColor = $riskScore >= 75 ? 'bg-red-100 text-red-700' : ($riskScore >= 50 ? 'bg-orange-100 text-orange-700' : 'bg-green-100 text-green-700');
                            $riskLabel = $riskScore >= 75 ? (trans('high') ?? 'High') : ($riskScore >= 50 ? (trans('medium') ?? 'Medium') : (trans('low') ?? 'Low'));
                            ?>
                            <span class="px-3 py-1 <?php echo $riskColor; ?> rounded-full text-sm font-medium">
                                <?php echo $riskLabel; ?> (<?php echo $riskScore; ?>%)
                            </span>
                        </td>
                        <td class="px-6 py-4">
                            <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold"><?php echo trans('active') ?? 'Active'; ?></span>
                        </td>
                        <td class="px-6 py-4">
                            <div class="flex gap-2">
                                <a href="?page=posts&action=view&id=<?php echo $post['id']; ?>" class="text-blue-600 hover:text-blue-900 p-2" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="?page=posts&action=edit&id=<?php echo $post['id']; ?>" class="text-blue-600 hover:text-blue-900 p-2" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?page=posts&action=view_contract&id=<?php echo $post['id']; ?>" class="text-green-600 hover:text-green-900 p-2" title="View Contract">
                                    <i class="fas fa-file-contract"></i>
                                </a>
                                <a href="?page=posts&action=assessment_report&id=<?php echo $post['id']; ?>" class="text-purple-600 hover:text-purple-900 p-2" title="Assessment Report">
                                    <i class="fas fa-file-pdf"></i>
                                </a>
                                <button onclick="deleteFacility(<?php echo $post['id']; ?>)" class="text-red-600 hover:text-red-900 p-2" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        endforeach;
                    endif;
                    ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Mobile Card View -->
        <div class="md:hidden space-y-4 pb-20">
            <?php
            $posts = $db->fetchAll("SELECT p.*, u.name as owner_name, creator.name as created_by_name FROM posts p LEFT JOIN users u ON p.owner_id = u.id LEFT JOIN users creator ON p.created_by = creator.id WHERE p.status = 'Active' LIMIT 50");
            if (empty($posts)): ?>
                <div class="text-center py-8 bg-white rounded-lg">
                    <i class="fas fa-inbox text-4xl mb-4 opacity-20 block"></i>
                    <p class="text-gray-500"><?php echo trans('no_facilities_yet') ?? 'No facilities added yet'; ?></p>
                </div>
            <?php else: 
                foreach ($posts as $post):
                    $riskScore = (int)($post['overall_risk_score'] ?? 0);
                    $riskColor = $riskScore >= 75 ? 'bg-red-100 text-red-700 border-red-300' : ($riskScore >= 50 ? 'bg-orange-100 text-orange-700 border-orange-300' : 'bg-green-100 text-green-700 border-green-300');
                    $riskLabel = $riskScore >= 75 ? (trans('high') ?? 'High') : ($riskScore >= 50 ? (trans('medium') ?? 'Medium') : (trans('low') ?? 'Low'));
            ?>
            <div class="bg-white rounded-lg shadow p-4 border-l-4 border-blue-600">
                <div class="flex justify-between items-start mb-3">
                    <div>
                        <h3 class="text-lg font-bold text-gray-900"><?php echo htmlspecialchars($post['name']); ?></h3>
                        <p class="text-xs text-gray-500 mt-1"><?php echo htmlspecialchars($post['location'] ?? '-'); ?></p>
                    </div>
                    <span class="px-2 py-1 <?php echo $riskColor; ?> rounded-full text-xs font-semibold border">
                        <?php echo $riskLabel; ?> (<?php echo $riskScore; ?>%)
                    </span>
                </div>
                <div class="space-y-2 text-sm text-gray-600 mb-4">
                    <div><span class="font-semibold text-gray-700">Type:</span> <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-medium"><?php echo htmlspecialchars($post['facility_type'] ?? '-'); ?></span></div>
                    <div><span class="font-semibold text-gray-700">Owner:</span> <?php echo htmlspecialchars($post['owner_name'] ?? '-'); ?></div>
                </div>
                <div class="flex gap-2">
                    <a href="?page=posts&action=view&id=<?php echo $post['id']; ?>" class="flex-1 text-center text-white px-3 py-2 rounded-lg hover:bg-blue-700 transition text-sm font-semibold bg-blue-600">
                        <i class="fas fa-eye"></i>
                    </a>
                    <a href="?page=posts&action=edit&id=<?php echo $post['id']; ?>" class="flex-1 text-center text-white px-3 py-2 rounded-lg hover:bg-green-700 transition text-sm font-semibold bg-green-600">
                        <i class="fas fa-edit"></i>
                    </a>
                    <a href="?page=posts&action=view_contract&id=<?php echo $post['id']; ?>" class="flex-1 text-center text-white px-3 py-2 rounded-lg hover:bg-purple-700 transition text-sm font-semibold bg-purple-600">
                        <i class="fas fa-file-contract"></i>
                    </a>
                    <a href="?page=posts&action=assessment_report&id=<?php echo $post['id']; ?>" class="flex-1 text-center text-white px-3 py-2 rounded-lg hover:bg-indigo-700 transition text-sm font-semibold bg-indigo-600">
                        <i class="fas fa-file-pdf"></i>
                    </a>
                    <button onclick="deleteFacility(<?php echo $post['id']; ?>)" class="flex-1 text-center text-white px-3 py-2 rounded-lg hover:bg-red-700 transition text-sm font-semibold bg-red-600">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
            <?php endforeach; endif; ?>
        </div>

        <?php elseif ($action === 'create' || $action === 'edit'): 
    $post = null;
    if ($action === 'edit' && isset($_GET['id'])) {
        $post = $db->fetch("SELECT * FROM posts WHERE id = ?", [$_GET['id']]);
    }
    
    // Get all users who are clients (facility owners)
    $owners = $db->fetchAll("SELECT id, name, phone FROM users WHERE role = 'client' AND active = 1 ORDER BY name");
    
    // Facility types
    $facilityTypes = ['Bank', 'Hospital', 'School', 'Government', 'Retail', 'Warehouse', 'Manufacturing', 'Hotel', 'Airport', 'Port', 'Residential Complex', 'Shopping Mall', 'Office Building', 'Data Center', 'Other'];
?>

    <div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-6xl">
        <div class="mb-6">
            <a href="?page=posts" class="text-blue-600 hover:text-blue-800"><i class="fas fa-arrow-left mr-2"></i><?php echo trans('back') ?? 'Back'; ?></a>
            <h1 class="text-2xl sm:text-3xl font-bold text-gray-800 mt-2">
                <i class="fas fa-building text-blue-600 mr-3"></i><?php echo $action === 'create' ? (trans('add_facility') ?? 'Add Facility') : (trans('edit_facility') ?? 'Edit Facility'); ?>
            </h1>
        </div>

        <script>
            // Set the API endpoint URL - dynamically determine the path
            const API_BASE_URL = (function() {
                // Get current page URL
                const currentUrl = window.location.pathname;
                // If we're in /public/index.php, api.php is in the same directory
                if (currentUrl.includes('/public/')) {
                    return '/ssci/public/api.php';
                }
                return '/api.php';
            })();
        </script>

        <form id="facilityForm" data-draft="facilityForm" data-autosave-interval="30000" onsubmit="handleFacilitySubmit(event, <?php echo $action === 'edit' && $post ? $post['id'] : 'null'; ?>)" class="space-y-6">
            
            <!-- Facility Information Section -->
            <div class="bg-white rounded-lg shadow p-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 pb-4 border-b-2 border-blue-200 flex items-center">
                    <i class="fas fa-info-circle text-blue-600 mr-3"></i><?php echo trans('facility_information') ?? 'Facility Information'; ?>
                </h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Facility Name -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-bookmark text-blue-600 mr-2"></i><?php echo trans('facility_name') ?? 'Facility Name'; ?> *
                        </label>
                        <input type="text" name="name" id="facilityName" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                               value="<?php echo htmlspecialchars($post['name'] ?? ''); ?>" placeholder="e.g., ABC Bank Branch, XYZ Hospital">
                    </div>

                    <!-- Facility Type -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-layer-group text-blue-600 mr-2"></i><?php echo trans('facility_type') ?? 'Facility Type'; ?> *
                        </label>
                        <select name="facility_type" id="facilityType" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition">
                            <option value=""><?php echo trans('select_type') ?? 'Select facility type...'; ?></option>
                            <?php foreach ($facilityTypes as $type): ?>
                                <option value="<?php echo $type; ?>" <?php echo (isset($post['facility_type']) && $post['facility_type'] === $type) ? 'selected' : ''; ?>><?php echo $type; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Zone -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-map-marker-alt text-blue-600 mr-2"></i><?php echo trans('zone') ?? 'Zone'; ?> *
                        </label>
                        <select name="zone" id="facilityZone" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition">
                            <option value=""><?php echo trans('select_zone') ?? 'Select zone...'; ?></option>
                            <option value="Buea" <?php echo (isset($post['zone']) && $post['zone'] === 'Buea') ? 'selected' : ''; ?>>Buea</option>
                            <option value="Limbe" <?php echo (isset($post['zone']) && $post['zone'] === 'Limbe') ? 'selected' : ''; ?>>Limbe</option>
                            <option value="Douala" <?php echo (isset($post['zone']) && $post['zone'] === 'Douala') ? 'selected' : ''; ?>>Douala</option>
                            <option value="Tiko" <?php echo (isset($post['zone']) && $post['zone'] === 'Tiko') ? 'selected' : ''; ?>>Tiko</option>
                            <option value="Yaounde" <?php echo (isset($post['zone']) && $post['zone'] === 'Yaounde') ? 'selected' : ''; ?>>Yaounde</option>
                            <option value="Bamenda" <?php echo (isset($post['zone']) && $post['zone'] === 'Bamenda') ? 'selected' : ''; ?>>Bamenda</option>
                            <option value="Kumba" <?php echo (isset($post['zone']) && $post['zone'] === 'Kumba') ? 'selected' : ''; ?>>Kumba</option>
                        </select>
                    </div>

                    <!-- Owner Selection (Client/Facility Owner) -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-user-tie text-blue-600 mr-2"></i><?php echo trans('facility_owner') ?? 'Facility Owner'; ?> *
                        </label>
                        <select id="ownerSelect" name="owner_id" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition">
                            <option value=""><?php echo trans('select_owner') ?? 'Choose facility owner...'; ?></option>
                            <?php foreach ($owners as $owner): ?>
                                <option value="<?php echo $owner['id']; ?>" <?php echo (isset($post['owner_id']) && $post['owner_id'] == $owner['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($owner['name']); ?> (<?php echo htmlspecialchars($owner['phone']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Location -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-map-pin text-blue-600 mr-2"></i><?php echo trans('location') ?? 'Location'; ?>
                        </label>
                        <input type="text" name="location" id="facilityLocation" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                               value="<?php echo htmlspecialchars($post['location'] ?? ''); ?>" placeholder="Street address, city">
                    </div>

                    <!-- Owner Phone -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-phone text-blue-600 mr-2"></i><?php echo trans('phone'); ?>
                        </label>
                        <input type="tel" name="owner_phone" id="ownerPhone" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                               value="<?php echo htmlspecialchars($post['owner_phone'] ?? ''); ?>" placeholder="Contact phone">
                    </div>

                    <!-- Owner Address -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-home text-blue-600 mr-2"></i><?php echo trans('owner_address') ?? 'Owner Address'; ?>
                        </label>
                        <input type="text" name="owner_address" id="ownerAddress" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                               value="<?php echo htmlspecialchars($post['owner_address'] ?? ''); ?>" placeholder="Owner address">
                    </div>
                </div>
            </div>

            <!-- Map & Coordinates Section -->
            <div class="bg-white rounded-lg shadow p-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 pb-4 border-b-2 border-blue-200 flex items-center">
                    <i class="fas fa-map text-blue-600 mr-3"></i><?php echo trans('location_coordinates') ?? 'Location Coordinates'; ?>
                </h2>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <!-- Map -->
                    <div class="lg:col-span-2">
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-crosshairs text-blue-600 mr-2"></i><?php echo trans('facility_location') ?? 'Click on map or use position button'; ?>
                        </label>
                        <div id="facilityMap" style="height: 400px; border: 2px solid #e5e7eb; border-radius: 8px; position: relative;">
                            <div style="position: absolute; top: 10px; right: 10px; z-index: 1000;">
                                <button type="button" onclick="useCurrentPosition()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center gap-2">
                                    <i class="fas fa-location-arrow"></i> <?php echo trans('my_position') ?? 'My Position'; ?>
                                </button>
                            </div>
                        </div>
                        <p class="text-sm text-gray-500 mt-2"><i class="fas fa-info-circle"></i> Drag the marker or click on the map to set coordinates</p>
                    </div>

                    <!-- Coordinates Input -->
                    <div class="space-y-4">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-latitude text-blue-600 mr-2"></i><?php echo trans('latitude') ?? 'Latitude'; ?>
                            </label>
                            <input type="number" name="latitude" id="facilityLatitude" step="0.000001" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                                   value="<?php echo htmlspecialchars($post['latitude'] ?? '0'); ?>" placeholder="-0.000000">
                        </div>

                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-longitude text-blue-600 mr-2"></i><?php echo trans('longitude') ?? 'Longitude'; ?>
                            </label>
                            <input type="number" name="longitude" id="facilityLongitude" step="0.000001" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                                   value="<?php echo htmlspecialchars($post['longitude'] ?? '0'); ?>" placeholder="0.000000">
                        </div>

                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <p class="text-sm text-blue-800">
                                <strong><?php echo trans('current') ?? 'Current'; ?>:</strong><br>
                                <span id="coordDisplay"><?php echo isset($post['latitude']) ? htmlspecialchars($post['latitude']) . ', ' . htmlspecialchars($post['longitude']) : 'No coordinates'; ?></span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Site Assessment Section -->
            <div class="bg-white rounded-lg shadow p-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 pb-4 border-b-2 border-blue-200 flex items-center">
                    <i class="fas fa-clipboard-check text-blue-600 mr-3"></i><?php echo trans('site_assessment') ?? 'Site Assessment'; ?>
                </h2>

                <!-- Infrastructure Factors (Internal) -->
                <div class="mb-8">
                    <h3 class="text-lg font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-building text-orange-600 mr-2"></i>Infrastructure Assessment (Internal Factors)
                    </h3>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <?php 
                        $internalFactors = [
                            'assessment_security_post' => ['name' => 'Security Post', 'icon' => 'fas fa-shield-alt'],
                            'assessment_fence' => ['name' => 'Fence/Perimeter', 'icon' => 'fas fa-fence'],
                            'assessment_cctv_alarms' => ['name' => 'CCTV & Alarms', 'icon' => 'fas fa-video'],
                            'assessment_lighting' => ['name' => 'Interior Lighting', 'icon' => 'fas fa-lightbulb'],
                            'assessment_toilet' => ['name' => 'Toilet Facilities', 'icon' => 'fas fa-restroom'],
                            'assessment_fire_extinguishers' => ['name' => 'Fire Safety', 'icon' => 'fas fa-fire-extinguisher'],
                            'assessment_accessibility' => ['name' => 'Road Accessibility', 'icon' => 'fas fa-road']
                        ];
                        
                        foreach ($internalFactors as $dbField => $info): 
                            $value = $post[$dbField] ?? '';
                            $riskColor = '';
                            if ($value === 'Good') $riskColor = 'border-green-200 bg-green-50';
                            elseif ($value === 'Fair') $riskColor = 'border-yellow-200 bg-yellow-50';
                            elseif ($value === 'Poor') $riskColor = 'border-red-200 bg-red-50';
                            else $riskColor = 'border-gray-200 bg-gray-50';
                        ?>
                        <div class="border-2 <?php echo $riskColor; ?> rounded-lg p-3 transition hover:shadow-md">
                            <label class="flex items-center justify-between mb-2">
                                <span class="flex items-center text-gray-700 font-medium text-sm">
                                    <i class="<?php echo $info['icon']; ?> mr-2 text-orange-600"></i><?php echo $info['name']; ?>
                                </span>
                                <span id="badge_<?php echo $dbField; ?>" class="assessment-badge text-xs font-bold px-2 py-1 rounded-full <?php 
                                    if ($value === 'Good') echo 'bg-green-200 text-green-800';
                                    elseif ($value === 'Fair') echo 'bg-yellow-200 text-yellow-800';
                                    elseif ($value === 'Poor') echo 'bg-red-200 text-red-800';
                                    else echo 'bg-gray-200 text-gray-800';
                                ?>"><?php echo $value ?: 'Not Set'; ?></span>
                            </label>
                            <div class="flex gap-1.5">
                                <!-- Good Radio -->
                                <label class="flex-1 relative">
                                    <input type="radio" name="<?php echo $dbField; ?>" value="Good" <?php echo ($value === 'Good') ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('<?php echo $dbField; ?>', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-green-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-green-700 peer-checked:bg-green-100 peer-checked:shadow-md peer-checked:shadow-green-300 hover:border-green-500">
                                        <div class="text-center">
                                            <div class="font-bold text-green-600 text-base">✓</div>
                                            <div class="text-xs text-gray-700 font-semibold">Good</div>
                                        </div>
                                    </div>
                                </label>
                                <!-- Fair Radio -->
                                <label class="flex-1 relative">
                                    <input type="radio" name="<?php echo $dbField; ?>" value="Fair" <?php echo ($value === 'Fair') ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('<?php echo $dbField; ?>', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-yellow-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-yellow-700 peer-checked:bg-yellow-100 peer-checked:shadow-md peer-checked:shadow-yellow-300 hover:border-yellow-500">
                                        <div class="text-center">
                                            <div class="font-bold text-yellow-600 text-base">≈</div>
                                            <div class="text-xs text-gray-700 font-semibold">Fair</div>
                                        </div>
                                    </div>
                                </label>
                                <!-- Poor Radio -->
                                <label class="flex-1 relative">
                                    <input type="radio" name="<?php echo $dbField; ?>" value="Poor" <?php echo ($value === 'Poor') ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('<?php echo $dbField; ?>', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-red-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-red-700 peer-checked:bg-red-100 peer-checked:shadow-md peer-checked:shadow-red-300 hover:border-red-500">
                                        <div class="text-center">
                                            <div class="font-bold text-red-600 text-base">✗</div>
                                            <div class="text-xs text-gray-700 font-semibold">Poor</div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Physical Infrastructure Metrics with Categories (Radio Selection) -->
                    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Surface Area Categories -->
                        <div class="border-2 border-purple-200 bg-purple-50 rounded-lg p-3">
                            <label class="flex items-center justify-between mb-2">
                                <span class="flex items-center text-gray-700 font-medium text-sm">
                                    <i class="fas fa-ruler text-purple-600 mr-2"></i>Surface Area
                                </span>
                                <span id="badge_surface_area" class="assessment-badge text-xs font-bold px-2 py-1 rounded-full bg-gray-200 text-gray-800">Not Set</span>
                            </label>
                            <div class="flex gap-1.5 flex-wrap">
                                <label class="flex-1 min-w-[100px] relative">
                                    <input type="radio" name="surface_area" value="petite" <?php echo ($post['surface_area'] ?? '') === 'petite' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('surface_area', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-purple-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-purple-700 peer-checked:bg-purple-100 peer-checked:shadow-md peer-checked:shadow-purple-300 hover:border-purple-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">Small</div>
                                            <div class="text-xs text-purple-600"><0.5ha</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[100px] relative">
                                    <input type="radio" name="surface_area" value="normale" <?php echo ($post['surface_area'] ?? '') === 'normale' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('surface_area', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-purple-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-purple-700 peer-checked:bg-purple-100 peer-checked:shadow-md peer-checked:shadow-purple-300 hover:border-purple-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">Normal</div>
                                            <div class="text-xs text-purple-600">0.5-1ha</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[100px] relative">
                                    <input type="radio" name="surface_area" value="vaste" <?php echo ($post['surface_area'] ?? '') === 'vaste' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('surface_area', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-purple-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-purple-700 peer-checked:bg-purple-100 peer-checked:shadow-md peer-checked:shadow-purple-300 hover:border-purple-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">Large</div>
                                            <div class="text-xs text-purple-600">1-5ha</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[100px] relative">
                                    <input type="radio" name="surface_area" value="tres_vaste" <?php echo ($post['surface_area'] ?? '') === 'tres_vaste' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('surface_area', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-purple-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-purple-700 peer-checked:bg-purple-100 peer-checked:shadow-md peer-checked:shadow-purple-300 hover:border-purple-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">Very Large</div>
                                            <div class="text-xs text-purple-600">>5ha</div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <!-- Access Points Categories -->
                        <div class="border-2 border-green-200 bg-green-50 rounded-lg p-3">
                            <label class="flex items-center justify-between mb-2">
                                <span class="flex items-center text-gray-700 font-medium text-sm">
                                    <i class="fas fa-door-open text-green-600 mr-2"></i>Access Points
                                </span>
                                <span id="badge_access_points" class="assessment-badge text-xs font-bold px-2 py-1 rounded-full bg-gray-200 text-gray-800">Not Set</span>
                            </label>
                            <div class="flex gap-1.5 flex-wrap">
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="access_points" value="1_2" <?php echo ($post['access_points'] ?? '') === '1_2' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('access_points', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-green-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-green-700 peer-checked:bg-green-100 peer-checked:shadow-md peer-checked:shadow-green-300 hover:border-green-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">1-2</div>
                                            <div class="text-xs text-green-600">Low</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="access_points" value="3_4" <?php echo ($post['access_points'] ?? '') === '3_4' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('access_points', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-green-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-green-700 peer-checked:bg-green-100 peer-checked:shadow-md peer-checked:shadow-green-300 hover:border-green-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">3-4</div>
                                            <div class="text-xs text-yellow-600">Mod.</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="access_points" value="5" <?php echo ($post['access_points'] ?? '') === '5' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('access_points', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-green-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-green-700 peer-checked:bg-green-100 peer-checked:shadow-md peer-checked:shadow-green-300 hover:border-green-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">5</div>
                                            <div class="text-xs text-orange-600">High</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="access_points" value="5_plus" <?php echo ($post['access_points'] ?? '') === '5_plus' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('access_points', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-green-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-green-700 peer-checked:bg-green-100 peer-checked:shadow-md peer-checked:shadow-green-300 hover:border-green-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">5+</div>
                                            <div class="text-xs text-red-600">Critical</div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <!-- Number of Buildings Categories -->
                        <div class="border-2 border-blue-200 bg-blue-50 rounded-lg p-3">
                            <label class="flex items-center justify-between mb-2">
                                <span class="flex items-center text-gray-700 font-medium text-sm">
                                    <i class="fas fa-building text-blue-600 mr-2"></i>Number of Buildings
                                </span>
                                <span id="badge_num_buildings" class="assessment-badge text-xs font-bold px-2 py-1 rounded-full bg-gray-200 text-gray-800">Not Set</span>
                            </label>
                            <div class="flex gap-1.5 flex-wrap">
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="num_buildings" value="1" <?php echo ($post['num_buildings'] ?? '') === '1' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('num_buildings', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-blue-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-blue-700 peer-checked:bg-blue-100 peer-checked:shadow-md peer-checked:shadow-blue-300 hover:border-blue-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">1 Unit</div>
                                            <div class="text-xs text-green-600">Low</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="num_buildings" value="2" <?php echo ($post['num_buildings'] ?? '') === '2' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('num_buildings', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-blue-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-blue-700 peer-checked:bg-blue-100 peer-checked:shadow-md peer-checked:shadow-blue-300 hover:border-blue-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">2 Units</div>
                                            <div class="text-xs text-yellow-600">Mod.</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="num_buildings" value="3_plus" <?php echo ($post['num_buildings'] ?? '') === '3_plus' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('num_buildings', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-blue-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-blue-700 peer-checked:bg-blue-100 peer-checked:shadow-md peer-checked:shadow-blue-300 hover:border-blue-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold">3+ Units</div>
                                            <div class="text-xs text-red-600">High</div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <!-- Content Value Categories -->
                        <div class="border-2 border-pink-200 bg-pink-50 rounded-lg p-3">
                            <label class="flex items-center justify-between mb-2">
                                <span class="flex items-center text-gray-700 font-medium text-sm">
                                    <i class="fas fa-money-bill-wave text-pink-600 mr-2"></i>Content Value
                                </span>
                                <span id="badge_content_value" class="assessment-badge text-xs font-bold px-2 py-1 rounded-full bg-gray-200 text-gray-800">Not Set</span>
                            </label>
                            <div class="flex gap-1.5 flex-wrap">
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="content_value" value="low" <?php echo ($post['content_value'] ?? '') === 'low' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('content_value', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-pink-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-pink-700 peer-checked:bg-pink-100 peer-checked:shadow-md peer-checked:shadow-pink-300 hover:border-pink-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold\"><2M</div>
                                            <div class="text-xs text-green-600">Low</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="content_value" value="moderate" <?php echo ($post['content_value'] ?? '') === 'moderate' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('content_value', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-pink-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-pink-700 peer-checked:bg-pink-100 peer-checked:shadow-md peer-checked:shadow-pink-300 hover:border-pink-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold\">2-10M</div>
                                            <div class="text-xs text-yellow-600">Mod.</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="content_value" value="high" <?php echo ($post['content_value'] ?? '') === 'high' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('content_value', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-pink-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-pink-700 peer-checked:bg-pink-100 peer-checked:shadow-md peer-checked:shadow-pink-300 hover:border-pink-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold\">10-50M</div>
                                            <div class="text-xs text-orange-600">High</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="flex-1 min-w-[90px] relative">
                                    <input type="radio" name="content_value" value="very_high" <?php echo ($post['content_value'] ?? '') === 'very_high' ? 'checked' : ''; ?> onchange="updateOverallRating(); updateBadge('content_value', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 border-pink-300 bg-white rounded-lg cursor-pointer transition peer-checked:border-pink-700 peer-checked:bg-pink-100 peer-checked:shadow-md peer-checked:shadow-pink-300 hover:border-pink-500">
                                        <div class="text-center">
                                            <div class="text-xs text-gray-700 font-semibold\">>50M</div>
                                            <div class="text-xs text-red-600">V.High</div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Zone/External Factors -->
                <div class="mb-8">
                    <h3 class="text-lg font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-map-marker-alt text-red-600 mr-2"></i>Zone Assessment (External Factors)
                    </h3>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <?php 
                        $externalFactors = [
                            'assessment_crime_rate' => ['name' => 'Crime Rate', 'icon' => 'fas fa-exclamation-triangle', 'options' => ['Low', 'Medium', 'High'], 'colors' => ['green', 'yellow', 'red']],
                            'assessment_living_standards' => ['name' => 'Living Standards', 'icon' => 'fas fa-home', 'options' => ['Low', 'Medium', 'High'], 'colors' => ['red', 'yellow', 'green']],
                            'assessment_public_security_proximity' => ['name' => 'Backup Security Proximity', 'icon' => 'fas fa-siren', 'options' => ['Far', 'Moderate', 'Close'], 'colors' => ['red', 'yellow', 'green']],
                            'assessment_labour_availability' => ['name' => 'Workforce Availability', 'icon' => 'fas fa-users', 'options' => ['Scarce', 'Moderate', 'Abundant'], 'colors' => ['red', 'yellow', 'green']]
                        ];
                        
                        foreach ($externalFactors as $dbField => $info): 
                            $value = $post[$dbField] ?? '';
                            $valueIndex = array_search($value, $info['options']);
                        ?>
                        <div class="border-2 border-gray-200 bg-gray-50 rounded-lg p-3 transition hover:shadow-md">
                            <label class="flex items-center justify-between mb-2">
                                <span class="flex items-center text-gray-700 font-medium text-sm">
                                    <i class="<?php echo $info['icon']; ?> mr-2 text-red-600"></i><?php echo $info['name']; ?>
                                </span>
                                <span id="zone_badge_<?php echo $dbField; ?>" class="assessment-badge text-xs font-bold px-2 py-1 rounded-full <?php 
                                    $colorMap = ['red' => 'bg-red-200 text-red-800', 'yellow' => 'bg-yellow-200 text-yellow-800', 'green' => 'bg-green-200 text-green-800'];
                                    if ($valueIndex !== false) {
                                        echo $colorMap[$info['colors'][$valueIndex]];
                                    } else {
                                        echo 'bg-gray-200 text-gray-800';
                                    }
                                ?>"><?php echo $value ?: 'Not Set'; ?></span>
                            </label>
                            <div class="flex gap-1.5">
                                <?php foreach ($info['options'] as $idx => $opt): 
                                    $colorClass = $info['colors'][$idx];
                                    $colorBorder = $colorClass === 'green' ? 'border-green-300 peer-checked:border-green-600 peer-checked:bg-green-50 hover:border-green-500' : 
                                                   ($colorClass === 'yellow' ? 'border-yellow-300 peer-checked:border-yellow-600 peer-checked:bg-yellow-50 hover:border-yellow-500' : 
                                                   'border-red-300 peer-checked:border-red-600 peer-checked:bg-red-50 hover:border-red-500');
                                    $textColor = $colorClass === 'green' ? 'text-green-600' : ($colorClass === 'yellow' ? 'text-yellow-600' : 'text-red-600');
                                ?>
                                <label class="flex-1 relative">
                                    <input type="radio" name="<?php echo $dbField; ?>" value="<?php echo $opt; ?>" <?php echo ($value === $opt) ? 'checked' : ''; ?> onchange="updateOverallRating(); updateZoneBadge('<?php echo $dbField; ?>', this.value)" class="sr-only peer">
                                    <div class="p-2 border-2 <?php echo $colorBorder; ?> bg-white rounded-lg cursor-pointer transition peer-checked:shadow-md peer-checked:shadow-current" style="border-width: 2px;">
                                        <div class="text-center">
                                            <div class="font-bold <?php echo $textColor; ?> text-base">●</div>
                                            <div class="text-xs text-gray-700 font-semibold"><?php echo $opt; ?></div>
                                        </div>
                                    </div>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Risk Contribution Breakdown -->
                <div class="border-2 border-gray-200 rounded-lg p-6 bg-gray-50 mb-8">
                    <h4 class="font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-chart-pie text-gray-600 mr-2"></i>Risk Contribution Breakdown
                    </h4>
                    <div class="space-y-3">
                        <div class="flex items-center justify-between">
                            <span class="text-gray-700 font-medium">Infrastructure Condition Risk (40% weight)</span>
                            <div class="flex-1 mx-4 bg-gray-300 rounded-full h-2">
                                <div id="infrastructureBar" class="bg-blue-600 h-2 rounded-full" style="width: 50%"></div>
                            </div>
                            <span id="infrastructurePercent" class="text-sm font-bold text-gray-700 w-12 text-right">50%</span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-gray-700 font-medium">Zone Safety Risk (35% weight)</span>
                            <div class="flex-1 mx-4 bg-gray-300 rounded-full h-2">
                                <div id="zoneBar" class="bg-red-600 h-2 rounded-full" style="width: 50%"></div>
                            </div>
                            <span id="zonePercent" class="text-sm font-bold text-gray-700 w-12 text-right">50%</span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-gray-700 font-medium">Physical Assets Risk (25% weight)</span>
                            <div class="flex-1 mx-4 bg-gray-300 rounded-full h-2">
                                <div id="assetsBar" class="bg-green-600 h-2 rounded-full" style="width: 50%"></div>
                            </div>
                            <span id="assetsPercent" class="text-sm font-bold text-gray-700 w-12 text-right">50%</span>
                        </div>
                    </div>
                </div>

                <!-- Overall Security Risk Rating Card -->
                <div class="p-6 bg-gradient-to-r from-red-50 to-orange-50 rounded-lg border-2 border-red-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-700 font-bold text-lg mb-1">Overall Security Risk Level</p>
                            <p class="text-sm text-gray-600">Calculated from infrastructure conditions, zone factors, and physical assets</p>
                        </div>
                        <div class="text-center">
                            <div class="relative w-32 h-32">
                                <svg class="w-32 h-32 transform -rotate-90" viewBox="0 0 120 120">
                                    <circle cx="60" cy="60" r="54" stroke="#e5e7eb" stroke-width="8" fill="none"></circle>
                                    <circle id="riskCircle" cx="60" cy="60" r="54" stroke="#3b82f6" stroke-width="8" fill="none" stroke-dasharray="339.29" stroke-dashoffset="339.29" style="transition: stroke-dashoffset 0.3s ease;"></circle>
                                </svg>
                                <div class="absolute inset-0 flex flex-col items-center justify-center">
                                    <div id="overallRatingPercent" class="text-3xl font-bold text-red-600">50%</div>
                                    <div id="overallRatingLabel" class="text-sm font-semibold text-gray-700">Medium Risk</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Observations & Recommendations Section -->
            <div class="bg-white rounded-lg shadow p-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 pb-4 border-b-2 border-blue-200 flex items-center">
                    <i class="fas fa-lightbulb text-yellow-600 mr-3"></i>Observations & Recommendations
                </h2>

                <div class="space-y-4">
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">Observations</label>
                        <textarea name="observations" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" rows="4" placeholder="Document any observations about the facility..."><?php echo htmlspecialchars($post['observations'] ?? ''); ?></textarea>
                    </div>

                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">Recommendations</label>
                        <textarea name="recommendations" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" rows="4" placeholder="Provide recommendations for improvements..."><?php echo htmlspecialchars($post['recommendations'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- Services Section -->
            <div class="bg-white rounded-lg shadow p-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 pb-4 border-b-2 border-blue-200 flex items-center">
                    <i class="fas fa-briefcase text-green-600 mr-3"></i>Services & Contract
                </h2>

                <div class="mb-6">
                    <label class="block text-gray-700 font-semibold mb-2">Contract Date</label>
                    <input type="date" name="contract_date" id="contractDate" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                           value="<?php echo htmlspecialchars($post['contract_date'] ?? ''); ?>">
                </div>

                <div class="mb-6">
                    <label class="block text-gray-700 font-semibold mb-2">Contract End Date</label>
                    <input type="date" name="contract_end" id="contractEnd" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                           value="<?php echo htmlspecialchars($post['contract_end'] ?? ''); ?>">
                </div>

                <!-- Hidden field to pass services JSON from database to JavaScript -->
                <input type="hidden" id="servicesJson" value='<?php echo htmlspecialchars(json_encode(!empty($post['services']) ? json_decode($post['services'], true) : []), ENT_QUOTES); ?>'>

                <!-- Services Table -->
                <div class="mb-6">
                    <label class="block text-gray-700 font-semibold mb-4">Repeating Services</label>
                    
                    <!-- Service names datalist for autocomplete -->
                    <datalist id="serviceNames">
                        <option value="Day Guards">
                        <option value="Night Guards">
                        <option value="Security Patrols">
                        <option value="CCTV Monitoring">
                        <option value="Access Control">
                        <option value="Alarm Response">
                        <option value="Fire Safety">
                        <option value="First Aid">
                        <option value="Training">
                        <option value="Consultation">
                    </datalist>
                    
                    <div class="overflow-x-auto">
                        <table class="min-w-full border border-gray-300 rounded-lg">
                            <thead class="bg-gray-100">
                                <tr>
                                    <th class="border border-gray-300 px-4 py-2 text-left font-semibold text-gray-700">Service Ref</th>
                                    <th class="border border-gray-300 px-4 py-2 text-left font-semibold text-gray-700">Service Name</th>
                                    <th class="border border-gray-300 px-4 py-2 text-center font-semibold text-gray-700">Quantity</th>
                                    <th class="border border-gray-300 px-4 py-2 text-right font-semibold text-gray-700">Unit Cost (FCFA)</th>
                                    <th class="border border-gray-300 px-4 py-2 text-right font-semibold text-gray-700">Total (FCFA)</th>
                                    <th class="border border-gray-300 px-4 py-2 text-center font-semibold text-gray-700">Action</th>
                                </tr>
                            </thead>
                            <tbody id="servicesTableBody">
                                <!-- Services will be added here by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                    <button type="button" onclick="addServiceRow()" class="mt-3 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition font-semibold">
                        <i class="fas fa-plus mr-2"></i>Add Service
                    </button>
                </div>

                <!-- Grand Total -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="bg-blue-50 border-2 border-blue-200 rounded-lg p-6">
                        <label class="block text-gray-700 font-semibold mb-2">Grand Total (Figures)</label>
                        <div class="text-3xl font-bold text-blue-600" id="grandTotalFigures">0 FCFA</div>
                        <input type="hidden" name="grand_total" id="grandTotalInput" value="0">
                    </div>

                    <div class="bg-green-50 border-2 border-green-200 rounded-lg p-6">
                        <label class="block text-gray-700 font-semibold mb-2">Grand Total (Words)</label>
                        <div class="text-lg font-semibold text-green-700" id="grandTotalWords">Zero FCFA only</div>
                    </div>
                </div>
            </div>

            <!-- Form Actions -->
            <div class="flex gap-4 py-6">
                <button type="submit" class="bg-gradient-to-r from-blue-600 to-blue-700 text-white px-8 py-3 rounded-lg hover:from-blue-700 hover:to-blue-800 transition font-semibold flex items-center">
                    <i class="fas fa-save mr-2"></i> <?php echo trans('save_facility') ?? (trans('save') ?? 'Save'); ?>
                </button>
                <a href="?page=posts" class="bg-gray-500 text-white px-8 py-3 rounded-lg hover:bg-gray-600 transition font-semibold flex items-center">
                    <i class="fas fa-times mr-2"></i> <?php echo trans('cancel') ?? 'Cancel'; ?>
                </a>
            </div>
        </form>
    </div>

    <!-- Include Leaflet CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>

    <script>
    /**
     * Show toast notification using SweetAlert2
     */
    function showToast(type, message) {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer)
                toast.addEventListener('mouseleave', Swal.resumeTimer)
            }
        });

        Toast.fire({
            icon: type,
            title: message
        });
    }

    let facilityMap;
    let facilityMarker;

    /**
     * Initialize Leaflet map for facility location
     */
    function initFacilityMap() {
        const lat = parseFloat(document.getElementById('facilityLatitude').value) || -0.3476;
        const lng = parseFloat(document.getElementById('facilityLongitude').value) || 36.0726;

        facilityMap = L.map('facilityMap').setView([lat, lng], 13);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors',
            maxZoom: 19
        }).addTo(facilityMap);

        facilityMarker = L.marker([lat, lng], {draggable: true}).addTo(facilityMap)
            .bindPopup('<?php echo trans('facility_location') ?? 'Facility Location'; ?>')
            .openPopup();

        facilityMarker.on('dragend', updateCoordinates);
        facilityMap.on('click', function(e) {
            facilityMarker.setLatLng(e.latlng);
            updateCoordinates();
        });
    }

    /**
     * Update coordinates from marker position
     */
    function updateCoordinates() {
        const lat = facilityMarker.getLatLng().lat;
        const lng = facilityMarker.getLatLng().lng;
        
        document.getElementById('facilityLatitude').value = lat.toFixed(6);
        document.getElementById('facilityLongitude').value = lng.toFixed(6);
        document.getElementById('coordDisplay').textContent = lat.toFixed(6) + ', ' + lng.toFixed(6);
    }

    /**
     * Get user's current position
     */
    function useCurrentPosition() {
        if (!navigator.geolocation) {
            alert('Geolocation not supported in your browser');
            return;
        }

        navigator.geolocation.getCurrentPosition(
            function(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                
                facilityMarker.setLatLng([lat, lng]);
                facilityMap.setView([lat, lng], 15);
                updateCoordinates();
                showToast('success', '<?php echo trans('position_updated') ?? 'Position updated'; ?>');
            },
            function(error) {
                showToast('error', 'Error getting position: ' + error.message);
            }
        );
    }

    /**
     * Autofill owner information
     */
    function autofillFromOwner(ownerId) {
        if (!ownerId) {
            document.getElementById('ownerPhone').value = '';
            document.getElementById('ownerAddress').value = '';
            return;
        }

        const select = document.getElementById('ownerSelect');
        const option = select.options[select.selectedIndex];

        document.getElementById('ownerPhone').value = option.dataset.phone || '';
        document.getElementById('ownerAddress').value = option.dataset.address || '';
    }

    /**
     * Calculate overall security rating based on all assessment factors
     */
    function updateOverallRating() {
        try {
            // Infrastructure quality (internal factors) - 40% weight
            // INVERTED: Lower conditions = Higher Risk Score
            const infrastructureFactors = [
                document.querySelector('[name="assessment_security_post"]:checked')?.value || '',
                document.querySelector('[name="assessment_fence"]:checked')?.value || '',
                document.querySelector('[name="assessment_cctv_alarms"]:checked')?.value || '',
                document.querySelector('[name="assessment_lighting"]:checked')?.value || '',
                document.querySelector('[name="assessment_toilet"]:checked')?.value || '',
                document.querySelector('[name="assessment_fire_extinguishers"]:checked')?.value || '',
                document.querySelector('[name="assessment_accessibility"]:checked')?.value || ''
            ];

            let infrastructureScore = 0;
            let infrastructureCount = 0;
            infrastructureFactors.forEach(val => {
                if (val) {
                    // Inverted: Good=0 (low risk), Fair=50, Poor=100 (high risk)
                    infrastructureScore += (val === 'Good' ? 0 : (val === 'Fair' ? 50 : 100));
                    infrastructureCount++;
                }
            });
            const infrastructureRating = infrastructureCount > 0 ? Math.round(infrastructureScore / infrastructureCount) : 50;

            // Zone safety (external factors) - 35% weight
            const zoneFactors = [
                document.querySelector('[name="assessment_crime_rate"]:checked')?.value || '',
                document.querySelector('[name="assessment_living_standards"]:checked')?.value || '',
                document.querySelector('[name="assessment_public_security_proximity"]:checked')?.value || '',
                document.querySelector('[name="assessment_labour_availability"]:checked')?.value || ''
            ];

            let zoneScore = 0;
            let zoneCount = 0;
            zoneFactors.forEach((val, idx) => {
                if (val) {
                    // Crime rate, living standards are inverse (High crime/Low standards = high risk)
                    if (idx === 0 || idx === 1) { // crime_rate, living_standards
                        zoneScore += (val === 'Low' ? 0 : (val === 'Medium' ? 50 : 100));
                    } else {
                        // Security proximity, labour availability (Far/Scarce = high risk)
                        zoneScore += (val === 'Close' || val === 'Abundant' ? 0 : (val === 'Moderate' ? 50 : 100));
                    }
                    zoneCount++;
                }
            });
            const zoneRating = zoneCount > 0 ? Math.round(zoneScore / zoneCount) : 50;

            // Physical assets (categorical selection) - 25% weight
            const surfaceArea = document.querySelector('[name="surface_area"]:checked')?.value || '';
            const accessPoints = document.querySelector('[name="access_points"]:checked')?.value || '';
            const numBuildings = document.querySelector('[name="num_buildings"]:checked')?.value || '';
            const contentValue = document.querySelector('[name="content_value"]:checked')?.value || '';

            // Asset scoring with categorized risk levels
            let totalAssetScore = 0;
            let selectedAssetCount = 0;
        
            if (surfaceArea) {
                const areaScores = {'petite': 0, 'normale': 20, 'vaste': 50, 'tres_vaste': 100};
                totalAssetScore += (areaScores[surfaceArea] || 50);
                selectedAssetCount++;
            }
        
            if (accessPoints) {
                const accessScores = {'1_2': 0, '3_4': 30, '5': 60, '5_plus': 100};
                totalAssetScore += (accessScores[accessPoints] || 50);
                selectedAssetCount++;
            }
        
            if (numBuildings) {
                const buildingScores = {'1': 0, '2': 30, '3_plus': 60};
                totalAssetScore += (buildingScores[numBuildings] || 50);
                selectedAssetCount++;
            }
        
            if (contentValue) {
                const valueScores = {'low': 0, 'moderate': 30, 'high': 60, 'very_high': 100};
                totalAssetScore += (valueScores[contentValue] || 50);
                selectedAssetCount++;
            }
        
            let assetsScore = selectedAssetCount > 0 ? Math.round(totalAssetScore / selectedAssetCount) : 50;
            assetsScore = Math.max(0, Math.min(100, assetsScore)); // Ensure 0-100 range
            
            // Calculate weighted overall rating (now based on RISK, not quality)
            // Higher score = Higher Risk
            const overallRating = Math.round(
                (infrastructureRating * 0.40) +
                (zoneRating * 0.35) +
                (assetsScore * 0.25)
            );

            // Update UI
            document.getElementById('overallRatingPercent').textContent = overallRating + '%';
            document.getElementById('infrastructurePercent').textContent = infrastructureRating + '%';
            
            // Force refresh infrastructure badges
            [
                'assessment_security_post',
                'assessment_fence',
                'assessment_cctv_alarms',
                'assessment_lighting',
                'assessment_toilet',
                'assessment_fire_extinguishers',
                'assessment_accessibility'
            ].forEach(function(field) {
                var val = document.querySelector('[name="' + field + '"]:checked')?.value || '';
                updateBadge(field, val);
            });
            
            document.getElementById('zonePercent').textContent = zoneRating + '%';
            document.getElementById('assetsPercent').textContent = Math.round(assetsScore) + '%';

            // Update progress bars
            const infrastructureBar = document.getElementById('infrastructureBar');
            const zoneBar = document.getElementById('zoneBar');
            const assetsBar = document.getElementById('assetsBar');
            const riskCircle = document.getElementById('riskCircle');
            
            if (infrastructureBar) infrastructureBar.style.width = infrastructureRating + '%';
            if (zoneBar) zoneBar.style.width = zoneRating + '%';
            if (assetsBar) assetsBar.style.width = Math.round(assetsScore) + '%';

            // Update circular progress
            if (riskCircle) {
                const circumference = 2 * Math.PI * 54; // radius = 54
                const offset = circumference - (overallRating / 100) * circumference;
                riskCircle.style.strokeDashoffset = offset;
            }

            // Update rating label and colors
            let ratingLabel = '';
            let circleColor = '';
            if (overallRating >= 75) {
                ratingLabel = 'Critical Risk';
                circleColor = '#7f1d1d'; // dark red
            } else if (overallRating >= 50) {
                ratingLabel = 'High Risk';
                circleColor = '#ef4444'; // red
            } else if (overallRating >= 25) {
                ratingLabel = 'Medium Risk';
                circleColor = '#f59e0b'; // amber
            } else {
                ratingLabel = 'Low Risk';
                circleColor = '#10b981'; // green
            }

            const ratingLabelEl = document.getElementById('overallRatingLabel');
            if (ratingLabelEl) ratingLabelEl.textContent = ratingLabel;
            if (riskCircle) riskCircle.setAttribute('stroke', circleColor);
        } catch (e) {
            console.error('Error calculating overall rating:', e);
        }
    }

    /**
     * Update infrastructure/zone badge when radio is selected
     */
    function updateBadge(fieldName, value) {
        const badgeEl = document.getElementById('badge_' + fieldName);
        if (!badgeEl) return;

        // Map category codes to readable labels
        const categoryLabels = {
            'petite': 'Small (<0.5ha)',
            'normale': 'Normal (0.5-1ha)',
            'vaste': 'Large (1-5ha)',
            'tres_vaste': 'Very Large (>5ha)',
            '1_2': '1-2 (Low)',
            '3_4': '3-4 (Moderate)',
            '5': '5 (High)',
            '5_plus': '5+ (Critical)',
            '1': '1 Unit (Low)',
            '2': '2 Units (Moderate)',
            '3_plus': '3+ Units (High)',
            'low': '<2M FCFA (Low)',
            'moderate': '2-10M FCFA (Moderate)',
            'high': '10-50M FCFA (High)',
            'very_high': '>50M FCFA (Very High)',
            'Good': 'Good',
            'Fair': 'Fair',
            'Poor': 'Poor'
        };

        const badgeClass = {
            'Good': 'bg-green-200 text-green-800',
            'Fair': 'bg-yellow-200 text-yellow-800',
            'Poor': 'bg-red-200 text-red-800'
        }[value] || 'bg-gray-200 text-gray-800';

        const displayValue = categoryLabels[value] || value || 'Not Set';
        badgeEl.className = 'assessment-badge text-xs font-bold px-2 py-1 rounded-full ' + badgeClass;
        badgeEl.textContent = displayValue;
    }
    /**
     * Update zone badge when radio is selected
     */
    function updateZoneBadge(fieldName, value) {
        const badgeEl = document.getElementById('zone_badge_' + fieldName);
        if (!badgeEl) return;

        // Determine badge class based on field and value
        let badgeClass = 'bg-gray-200 text-gray-800';
        
        if (fieldName === 'assessment_crime_rate') {
            badgeClass = {'Low': 'bg-green-200 text-green-800', 'Medium': 'bg-yellow-200 text-yellow-800', 'High': 'bg-red-200 text-red-800'}[value] || 'bg-gray-200 text-gray-800';
        } else if (fieldName === 'assessment_living_standards') {
            badgeClass = {'Low': 'bg-red-200 text-red-800', 'Medium': 'bg-yellow-200 text-yellow-800', 'High': 'bg-green-200 text-green-800'}[value] || 'bg-gray-200 text-gray-800';
        } else if (fieldName === 'assessment_public_security_proximity') {
            badgeClass = {'Far': 'bg-red-200 text-red-800', 'Moderate': 'bg-yellow-200 text-yellow-800', 'Close': 'bg-green-200 text-green-800'}[value] || 'bg-gray-200 text-gray-800';
        } else if (fieldName === 'assessment_labour_availability') {
            badgeClass = {'Scarce': 'bg-red-200 text-red-800', 'Moderate': 'bg-yellow-200 text-yellow-800', 'Abundant': 'bg-green-200 text-green-800'}[value] || 'bg-gray-200 text-gray-800';
        }

        badgeEl.className = 'assessment-badge text-xs font-bold px-2 py-1 rounded-full ' + badgeClass;
        badgeEl.textContent = value || 'Not Set';
    }

    /**
     * Add a new service row to the table
     */
    function addServiceRow(serviceData = null) {
        const tbody = document.getElementById('servicesTableBody');
        const rowCount = tbody.children.length;
        const rowNum = rowCount + 1;

        const ref = serviceData?.ref || `SVC-${rowNum}`;
        const name = serviceData?.name || '';
        const qty = serviceData?.qty || 1;
        const unitCost = serviceData?.unit_cost || 0;
        const total = serviceData?.total || 0;

        const row = document.createElement('tr');
        row.innerHTML = `
            <td class="border border-gray-300 px-4 py-2"><input type="text" class="w-full px-2 py-1 border border-gray-300 rounded service-ref" placeholder="SVC-${rowNum}" value="${ref}"></td>
            <td class="border border-gray-300 px-4 py-2"><input type="text" class="w-full px-2 py-1 border border-gray-300 rounded service-name" placeholder="Service name" value="${name}" list="serviceNames"></td>
            <td class="border border-gray-300 px-4 py-2"><input type="number" class="w-full px-2 py-1 border border-gray-300 rounded text-center quantity-input" value="${qty}" min="1" oninput="updateServiceTotal()" onchange="updateServiceTotal()"></td>
            <td class="border border-gray-300 px-4 py-2"><input type="number" class="w-full px-2 py-1 border border-gray-300 rounded text-right unit-cost-input" placeholder="0" step="0.01" value="${unitCost}" oninput="updateServiceTotal()" onchange="updateServiceTotal()"></td>
            <td class="border border-gray-300 px-4 py-2"><input type="number" class="w-full px-2 py-1 border border-gray-300 rounded text-right bg-gray-100 service-total" readonly placeholder="0" value="${total.toFixed(2)}"></td>
            <td class="border border-gray-300 px-4 py-2 text-center"><button type="button" onclick="cloneServiceRow(this)" class="text-blue-600 hover:text-blue-800 font-bold mr-2" title="Clone">⬡</button><button type="button" onclick="removeServiceRow(this)" class="text-red-600 hover:text-red-800 font-bold">×</button></td>
        `;
        tbody.appendChild(row);
        updateServiceTotal();
    }

    /**
     * Clone a service row
     */
    function cloneServiceRow(button) {
        const row = button.closest('tr');
        const ref = row.querySelector('.service-ref').value;
        const name = row.querySelector('.service-name').value;
        const qty = row.querySelector('.quantity-input').value;
        const unitCost = row.querySelector('.unit-cost-input').value;
        const total = row.querySelector('.service-total').value;
        
        addServiceRow({ref, name, qty, unit_cost: unitCost, total: parseFloat(total)});
        updateServiceTotal();
    }

    /**
     * Remove a service row
     */
    function removeServiceRow(button) {
        button.closest('tr').remove();
        updateServiceTotal();
    }

    /**
     * Update service totals and grand total
     */
    function updateServiceTotal() {
        const tbody = document.getElementById('servicesTableBody');
        const rows = tbody.querySelectorAll('tr');
        let grandTotal = 0;

        rows.forEach(row => {
            const qty = parseFloat(row.querySelector('.quantity-input').value) || 0;
            const unitCost = parseFloat(row.querySelector('.unit-cost-input').value) || 0;
            const total = qty * unitCost;
            row.querySelector('.service-total').value = total.toFixed(2);
            grandTotal += total;
        });

        // Update grand total in figures
        document.getElementById('grandTotalFigures').textContent = grandTotal.toLocaleString('en-US', {style: 'currency', currency: 'XOF'}).replace('XOF', 'FCFA');
        document.getElementById('grandTotalInput').value = grandTotal.toFixed(2);

        // Update grand total in words
        document.getElementById('grandTotalWords').textContent = numberToWords(Math.round(grandTotal)) + ' FCFA only';
    }

    /**
     * Convert number to words in English
     */
    function numberToWords(num) {
        if (num === 0) return 'Zero';
        
        const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
        const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
        const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
        const scales = ['', 'Thousand', 'Million', 'Billion'];

        function convertGroup(n) {
            let result = '';
            const hundred = Math.floor(n / 100);
            const ten = Math.floor((n % 100) / 10);
            const one = n % 10;

            if (hundred > 0) result += ones[hundred] + ' Hundred ';
            if (ten === 1) result += teens[one] + ' ';
            else {
                if (ten > 0) result += tens[ten] + ' ';
                if (one > 0) result += ones[one] + ' ';
            }
            return result.trim();
        }

        if (num < 0) return 'Minus ' + numberToWords(-num);
        if (num === 0) return 'Zero';

        let groupIndex = 0;
        let result = '';

        while (num > 0) {
            if (num % 1000 !== 0) {
                result = convertGroup(num % 1000) + ' ' + scales[groupIndex] + ' ' + result;
            }
            num = Math.floor(num / 1000);
            groupIndex++;
        }

        return result.trim();
    }

    /**
     * Calculate overall risk score from assessment factors
     */
    function calculateRiskScore() {
        const sliders = document.querySelectorAll('.assessment-slider');
        let totalScore = 0;
        let count = sliders.length;

        sliders.forEach(slider => {
            const value = parseInt(slider.value);
            const field = slider.dataset.field;
            document.getElementById(field + '_score').textContent = value + '%';
            totalScore += value;
        });

        const avgScore = Math.round(totalScore / count);
        document.getElementById('overallRiskScore').value = avgScore;
        document.getElementById('riskScoreDisplay').textContent = avgScore + '%';

        // Update risk level color and label
        let riskLevel, riskClass;
        if (avgScore >= 75) {
            riskLevel = '<?php echo trans('high_risk') ?? 'High Risk'; ?>';
            riskClass = 'text-red-600';
        } else if (avgScore >= 50) {
            riskLevel = '<?php echo trans('medium_risk') ?? 'Medium Risk'; ?>';
            riskClass = 'text-orange-600';
        } else {
            riskLevel = '<?php echo trans('low_risk') ?? 'Low Risk'; ?>';
            riskClass = 'text-green-600';
        }

        const display = document.getElementById('riskLevelDisplay');
        display.textContent = riskLevel;
        display.className = 'text-lg font-semibold ' + riskClass + ' mt-2';
    }

    /**
     * Handle facility form submission
     */
    function handleFacilitySubmit(event, facilityId) {
        event.preventDefault();

        try {
            const formData = new FormData(event.target);
            const data = Object.fromEntries(formData);

            if (!data.name.trim()) {
                showToast('error', '<?php echo trans('facility_name_required') ?? 'Facility name is required'; ?>');
                return;
            }

            // Extract services from table rows into proper array
            const services = [];
            const tbody = document.getElementById('servicesTableBody');
            if (tbody) {
                tbody.querySelectorAll('tr').forEach(row => {
                    const ref = row.querySelector('.service-ref').value.trim();
                    const name = row.querySelector('.service-name').value.trim();
                    const qty = parseFloat(row.querySelector('.quantity-input').value) || 0;
                    const unitCost = parseFloat(row.querySelector('.unit-cost-input').value) || 0;
                    const total = parseFloat(row.querySelector('.service-total').value) || 0;
                    
                    // Allow zero and negative values - only require ref and name to be non-empty
                    if (ref && name) {
                        services.push({ref, name, qty, unit_cost: unitCost, total});
                    }
                });
            }

            // Add services as JSON and remove old array fields
            if (services.length > 0) {
                data.services = JSON.stringify(services);
            } else {
                // If no services, keep the existing JSON from hidden field (for edit operations)
                const servicesJsonField = document.getElementById('servicesJson');
                if (servicesJsonField && servicesJsonField.value) {
                    try {
                        const existingServices = JSON.parse(servicesJsonField.value);
                        if (Array.isArray(existingServices) && existingServices.length > 0) {
                            data.services = servicesJsonField.value;
                        }
                    } catch (e) {
                        console.error('Error parsing existing services:', e);
                    }
                }
            }
            delete data['service_ref[]'];
            delete data['service_name[]'];
            delete data['service_qty[]'];
            delete data['service_unit_cost[]'];
            delete data['service_total[]'];

            // Log the data being sent (for debugging)
            console.log('Submitting facility data:', data);

            // Use absolute path - api.php is in the /public directory same as index.php
            const url = facilityId 
                ? `${API_BASE_URL}?endpoint=posts/update&id=${facilityId}` 
                : `${API_BASE_URL}?endpoint=posts/create`;

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(res => {
                const contentType = res.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    // Try to read the response text for debugging
                    return res.text().then(text => {
                        console.error('Non-JSON response:', text);
                        throw new Error('Server returned non-JSON response: ' + text.substring(0, 200));
                    });
                }
                return res.json();
            })
            .then(data => {
                if (data.success) {
                    showToast('success', '<?php echo trans('facility_saved') ?? trans('record_saved'); ?>');
                    setTimeout(() => window.location.href = '?page=posts', 1500);
                } else {
                    showToast('error', data.error || '<?php echo trans('error'); ?>');
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showToast('error', 'Error: ' + err.message);
            });
        } catch(e) {
            console.error('Form error:', e);
            showToast('error', 'Error: ' + e.message);
        }
    }

    /**
     * Delete facility with confirmation
     */
    function deleteFacility(id) {
        if (confirm('<?php echo trans("confirm_delete_facility") ?? "Are you sure you want to delete this facility?"; ?>')) {
            try {
                fetch(`api.php?endpoint=posts/delete&id=${id}`, { method: 'POST' })
                    .then(res => {
                        const contentType = res.headers.get('content-type');
                        if (!contentType || !contentType.includes('application/json')) {
                            throw new Error('Server returned non-JSON response');
                        }
                        return res.json();
                    })
                    .then(data => {
                        if (data.success) {
                            showToast('success', '<?php echo trans('record_deleted'); ?>');
                            setTimeout(() => location.reload(), 1500);
                        } else {
                            showToast('error', data.error || '<?php echo trans('error'); ?>');
                        }
                    })
                    .catch(err => {
                        console.error('Error:', err);
                        showToast('error', 'Error: ' + err.message);
                    });
            } catch(e) {
                console.error('Delete error:', e);
                showToast('error', 'Error: ' + e.message);
            }
        }
    }

    // Initialize map and services when page loads
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(initFacilityMap, 500);
        
        // Initialize services table
        const tbody = document.getElementById('servicesTableBody');
        if (tbody) {
            // Load services from database (via hidden JSON field)
            const servicesJsonField = document.getElementById('servicesJson');
            if (servicesJsonField && servicesJsonField.value) {
                try {
                    const services = JSON.parse(servicesJsonField.value);
                    if (Array.isArray(services) && services.length > 0) {
                        services.forEach(service => {
                            addServiceRow(service);
                        });
                    } else {
                        // Add one empty row if no services exist
                        addServiceRow();
                    }
                } catch (e) {
                    console.error('Error parsing services JSON:', e);
                    addServiceRow();
                }
            } else {
                // Add one empty row if no services exist
                addServiceRow();
            }
            updateServiceTotal();
        }

        // Initialize overall rating calculation
        setTimeout(updateOverallRating, 100);
    });
    </script>

<?php endif;

require_once __DIR__ . '/../../layouts/footer.php'; ?>
