<?php
/**
 * Site Assessment Report
 * SSCI Office Platform
 * 
 * Variables available:
 * - $facility: Facility details (name, owner, address, type, etc.)
 * - $assessment_date: Assessment date
 * - $contract_status: Contract status
 * - $location_map_url: URL for location map (if available)
 * - $security_assessments: Array of security assessment items
 * - $observations: Observations text
 * - $suggestions: Suggestions text
 * - $services: Services array
 * - $grand_total: Total amount
 * - $assessment_id: Assessment ID for QR code
 */

$facility = $facility ?? [];
// Parse services from JSON format - handle both old and new field names
$services = [];
if (!empty($facility['services'])) {
    $services_data = json_decode($facility['services'], true);
    if (is_array($services_data)) {
        foreach ($services_data as $service) {
            $services[] = [
                'ref' => $service['ref'] ?? '',
                'name' => $service['name'] ?? $service['description'] ?? '',
                'qty' => (float)($service['qty'] ?? 0),
                'unit_cost' => (float)($service['unit_cost'] ?? $service['unit'] ?? 0),
                'total' => (float)($service['total'] ?? 0)
            ];
        }
    }
}
$primary_color = $primary_color ?? '#2563eb';
$site_logo = $site_logo ?? null;
$site_letterhead = $site_letterhead ?? null;

// Generate QR code URL (using qr.io service)
$assessment_id = $assessment_id ?? ($facility['id'] ?? date('YmdHis'));
$qr_code_url = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode("Assessment-{$assessment_id}");

// Security assessment items mapping
$assessment_fields = [
    'assessment_security_post' => 'Security Post',
    'assessment_fence' => 'Fence/Wall',
    'assessment_cctv_alarms' => 'CCTV/Alarms',
    'assessment_lighting' => 'Lighting',
    'assessment_toilet' => 'Toilet Facilities',
    'assessment_fire_extinguishers' => 'Fire Extinguishers',
    'assessment_accessibility' => 'Accessibility'
];

$zone_assessment_fields = [
    'assessment_crime_rate' => 'Crime Rate',
    'assessment_living_standards' => 'Living Standards',
    'assessment_public_security_proximity' => 'Public Security Proximity',
    'assessment_labour_availability' => 'Labour Availability'
];
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Site Assessment Report - <?= htmlspecialchars($facility['name'] ?? 'Assessment') ?></title>

    <!-- Google font -->
    <link href="https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@400;700&display=swap" rel="stylesheet">

    <!-- Leaflet Map -->
    <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>

    <style>
        :root {
            --primary-color: <?= htmlspecialchars($primary_color) ?>;
            --accent-dark: #1f2937;
            --muted: #6b7280;
            --light-bg: #f9fafb;
            --border-color: #e5e7eb;
            --page-width: 900px;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
        }

        html, body {
            font-family: 'PT Sans Narrow', Arial, sans-serif;
            color: #111827;
            margin: 0;
            padding: 0;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
            background: #fafafa;
        }

        .page {
            width: var(--page-width);
            margin: 20px auto;
            padding: 32px 40px;
            box-sizing: border-box;
            background: #fff;
            color: #111;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            page-break-after: always;
        }

        /* Letterhead */
        .letterhead {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 3px solid var(--primary-color);
        }

        .letterhead-left {
            display: flex;
            gap: 12px;
            align-items: center;
            flex: 1;
        }

        .logo {
            width: 60px;
            height: 60px;
            border-radius: 6px;
            background: linear-gradient(135deg, var(--primary-color), rgba(37, 99, 235, 0.7));
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            color: #fff;
            font-size: 24px;
        }

        .brand-info h1 {
            font-size: 18px;
            margin: 0 0 2px 0;
            color: var(--accent-dark);
            font-weight: 700;
        }

        .brand-info p {
            margin: 0;
            font-size: 11px;
            color: var(--muted);
        }

        .letterhead-right {
            text-align: right;
            font-size: 12px;
            color: var(--muted);
        }

        .letterhead-right strong {
            display: block;
            color: var(--accent-dark);
            font-size: 11px;
            margin-bottom: 2px;
        }

        /* Section Headers */
        .section-title {
            background: linear-gradient(135deg, var(--primary-color), rgba(37, 99, 235, 0.8));
            color: #fff;
            padding: 12px 16px;
            margin: 28px 0 16px 0;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .section-icon {
            font-size: 16px;
        }

        /* Content Sections */
        .section {
            margin: 0 0 20px 0;
            line-height: 1.6;
            font-size: 13px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;
            margin-bottom: 16px;
        }

        .info-item {
            background: var(--light-bg);
            padding: 12px 14px;
            border-radius: 4px;
            border-left: 3px solid var(--primary-color);
        }

        .info-label {
            font-weight: 700;
            color: var(--accent-dark);
            font-size: 11px;
            text-transform: uppercase;
            margin-bottom: 4px;
            letter-spacing: 0.3px;
        }

        .info-value {
            color: #1f2937;
            font-size: 13px;
        }

        /* Location Map */
        .location-map {
            width: 100%;
            height: 300px;
            background: var(--light-bg);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            margin: 16px 0;
            position: relative;
            overflow: hidden;
        }

        #mapContainer {
            width: 100%;
            height: 100%;
            border-radius: 4px;
        }

        .leaflet-container {
            font-family: 'PT Sans Narrow', Arial, sans-serif;
        }

        .location-map img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* Assessment Grid */
        .assessment-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 12px;
            margin: 16px 0;
        }

        .assessment-item {
            background: var(--light-bg);
            padding: 12px;
            border-radius: 4px;
            border: 1px solid var(--border-color);
            text-align: center;
        }

        .assessment-label {
            font-size: 11px;
            font-weight: 600;
            color: var(--muted);
            margin-bottom: 6px;
            text-transform: uppercase;
        }

        .assessment-value {
            font-size: 13px;
            font-weight: 700;
            padding: 6px;
            border-radius: 3px;
            display: inline-block;
        }

        .assessment-value.good {
            background: rgba(16, 185, 129, 0.15);
            color: #059669;
        }

        .assessment-value.fair {
            background: rgba(245, 158, 11, 0.15);
            color: #d97706;
        }

        .assessment-value.poor {
            background: rgba(239, 68, 68, 0.15);
            color: #dc2626;
        }

        /* Text Sections */
        .text-section {
            background: var(--light-bg);
            padding: 14px;
            border-left: 3px solid var(--primary-color);
            border-radius: 4px;
            margin: 14px 0;
            line-height: 1.6;
            font-size: 13px;
        }

        .text-section p {
            margin: 0;
            white-space: pre-wrap;
        }

        /* Service Table */
        .services-table {
            width: 100%;
            border-collapse: collapse;
            margin: 16px 0;
            background: #fff;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            overflow: hidden;
        }

        .services-table thead {
            background: linear-gradient(135deg, rgba(37, 99, 235, 0.1), rgba(37, 99, 235, 0.05));
            border-bottom: 2px solid var(--primary-color);
        }

        .services-table th {
            padding: 10px 12px;
            text-align: left;
            font-weight: 700;
            color: var(--accent-dark);
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .services-table td {
            padding: 10px 12px;
            border-bottom: 1px solid var(--border-color);
            font-size: 13px;
        }

        .services-table tbody tr:hover {
            background: var(--light-bg);
        }

        .services-table .text-right {
            text-align: right;
        }

        .services-table .total-row {
            background: linear-gradient(135deg, rgba(37, 99, 235, 0.08), rgba(37, 99, 235, 0.04));
            font-weight: 700;
            border-top: 2px solid var(--primary-color);
        }

        /* Summary Box */
        .summary-box {
            background: linear-gradient(135deg, rgba(37, 99, 235, 0.08), rgba(37, 99, 235, 0.04));
            border: 2px solid var(--primary-color);
            padding: 16px;
            border-radius: 4px;
            margin: 20px 0;
            text-align: center;
        }

        .summary-label {
            font-size: 11px;
            color: var(--muted);
            text-transform: uppercase;
            font-weight: 600;
            margin-bottom: 6px;
        }

        .summary-amount {
            font-size: 28px;
            font-weight: 700;
            color: var(--primary-color);
            margin-bottom: 4px;
        }

        .summary-text {
            font-size: 12px;
            color: var(--accent-dark);
            font-weight: 600;
        }

        /* Signature Section */
        .signature-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            margin-top: 40px;
            page-break-inside: avoid;
        }

        .signature-box {
            text-align: center;
        }

        .signature-line {
            border-top: 1px solid #000;
            height: 60px;
            margin-bottom: 8px;
        }

        .signature-label {
            font-size: 12px;
            color: var(--accent-dark);
            font-weight: 600;
        }

        .signature-date {
            font-size: 11px;
            color: var(--muted);
            margin-top: 4px;
        }

        .qr-section {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .qr-code {
            width: 120px;
            height: 120px;
            background: var(--light-bg);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 6px;
        }

        .qr-code img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .qr-text {
            font-size: 10px;
            color: var(--muted);
            text-align: center;
            text-transform: uppercase;
            font-weight: 600;
        }

        /* Footer */
        .footer {
            margin-top: 24px;
            padding-top: 16px;
            border-top: 1px solid var(--border-color);
            text-align: center;
            font-size: 11px;
            color: var(--muted);
        }

        /* Print styles */
        @media print {
            body {
                background: #fff;
            }
            .page {
                box-shadow: none;
                margin: 0;
                padding: 40px;
            }
        }

        @page {
            margin: 0.5cm;
        }
    </style>
</head>
<body>

<div class="page">
    <!-- Letterhead -->
    <div class="letterhead">
        <div class="letterhead-left">
            <div class="logo">SSCI</div>
            <div class="brand-info">
                <h1>SSCI SECURITY</h1>
                <p>Site Assessment Report</p>
            </div>
        </div>
        <div class="letterhead-right">
            <strong>Assessment ID:</strong>
            <span><?= htmlspecialchars($assessment_id) ?></span><br>
            <strong>Report Date:</strong>
            <span><?= date('M d, Y') ?></span>
        </div>
    </div>

    <!-- Facility Information Section -->
    <div class="section-title">
        <span class="section-icon">📍</span>
        <span>Facility Information</span>
    </div>

    <div class="info-grid">
        <div class="info-item">
            <div class="info-label">Facility Name</div>
            <div class="info-value"><?= htmlspecialchars($facility['name'] ?? 'N/A') ?></div>
        </div>
        <div class="info-item">
            <div class="info-label">Facility Type</div>
            <div class="info-value"><?= htmlspecialchars($facility['facility_type'] ?? 'N/A') ?></div>
        </div>
        <div class="info-item">
            <div class="info-label">Owner</div>
            <div class="info-value"><?= htmlspecialchars($facility['owner_name'] ?? 'N/A') ?></div>
        </div>
        <div class="info-item">
            <div class="info-label">Assessment Date</div>
            <div class="info-value"><?= $facility['created_at'] ? date('M d, Y', strtotime($facility['created_at'])) : date('M d, Y') ?></div>
        </div>
        <div class="info-item">
            <div class="info-label">Address</div>
            <div class="info-value"><?= htmlspecialchars($facility['location'] ?? 'N/A') ?></div>
        </div>
        <div class="info-item">
            <div class="info-label">Contract Status</div>
            <div class="info-value"><?= htmlspecialchars($facility['status'] ?? 'N/A') ?></div>
        </div>
    </div>

    <!-- Location Map -->
    <?php if (!empty($facility['latitude']) && !empty($facility['longitude'])): ?>
    <div class="section-title" style="margin-top: 24px;">
        <span class="section-icon">🗺️</span>
        <span>Location Map</span>
    </div>
    <div class="location-map">
        <div id="mapContainer"></div>
    </div>
    <?php endif; ?>

    <!-- Infrastructure Assessment -->
    <div class="section-title">
        <span class="section-icon">🔒</span>
        <span>Infrastructure Assessment</span>
    </div>

    <div class="assessment-grid">
        <?php foreach ($assessment_fields as $field => $label): ?>
            <?php if (!empty($facility[$field])): ?>
            <div class="assessment-item">
                <div class="assessment-label"><?= htmlspecialchars($label) ?></div>
                <div class="assessment-value <?= strtolower($facility[$field]) ?>">
                    <?= htmlspecialchars(ucfirst($facility[$field])) ?>
                </div>
            </div>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>

    <!-- Zone Assessment -->
    <div class="section-title">
        <span class="section-icon">🌍</span>
        <span>Zone Assessment</span>
    </div>

    <div class="assessment-grid">
        <?php foreach ($zone_assessment_fields as $field => $label): ?>
            <?php if (!empty($facility[$field])): ?>
            <div class="assessment-item">
                <div class="assessment-label"><?= htmlspecialchars($label) ?></div>
                <div class="assessment-value">
                    <?= htmlspecialchars($facility[$field]) ?>
                </div>
            </div>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>

    <!-- Observations -->
    <?php if (!empty($facility['observations'])): ?>
    <div class="section-title">
        <span class="section-icon">📝</span>
        <span>Observations</span>
    </div>
    <div class="text-section">
        <p><?= htmlspecialchars($facility['observations']) ?></p>
    </div>
    <?php endif; ?>

    <!-- Suggestions -->
    <?php if (!empty($facility['recommendations'])): ?>
    <div class="section-title">
        <span class="section-icon">💡</span>
        <span>Recommendations</span>
    </div>
    <div class="text-section">
        <p><?= htmlspecialchars($facility['recommendations']) ?></p>
    </div>
    <?php endif; ?>

    <!-- Service Proposal -->
    <?php if (!empty($services) && is_array($services) && count($services) > 0): ?>
    <div class="section-title">
        <span class="section-icon">📋</span>
        <span>Service Proposal</span>
    </div>

    <table class="services-table">
        <thead>
            <tr>
                <th>Service</th>
                <th class="text-right">Quantity</th>
                <th class="text-right">Unit Cost</th>
                <th class="text-right">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $total = 0;
            foreach ($services as $service): 
                $service_total = (float)($service['total'] ?? 0);
                $total += $service_total;
            ?>
            <tr>
                <td><?= htmlspecialchars($service['name'] ?? '') ?></td>
                <td class="text-right"><?= number_format((float)($service['qty'] ?? 0)) ?></td>
                <td class="text-right"><?= number_format((float)($service['unit_cost'] ?? 0), 2) ?> FCFA</td>
                <td class="text-right"><strong><?= number_format($service_total, 2) ?> FCFA</strong></td>
            </tr>
            <?php endforeach; ?>
            <tr class="total-row">
                <td colspan="3" style="text-align: right;">TOTAL AMOUNT:</td>
                <td class="text-right"><?= number_format($total, 2) ?> FCFA</td>
            </tr>
        </tbody>
    </table>

    <!-- Summary Box -->
    <div class="summary-box">
        <div class="summary-label">Proposed Investment</div>
        <div class="summary-amount"><?= number_format($total, 0) ?> FCFA</div>
        <div class="summary-text">
            <?php 
            // Convert to words (you can use your number_to_words function here)
            $words = number_to_words($total);
            echo ucfirst($words);
            ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Signature & QR Code -->
    <div class="signature-section">
        <div class="signature-box">
            <div class="signature-line"></div>
            <div class="signature-label">Assessed By</div>
            <div class="signature-date"><?= date('M d, Y') ?></div>
        </div>
        <div class="qr-section">
            <div class="qr-code">
                <img src="<?= htmlspecialchars($qr_code_url) ?>" alt="QR Code" />
            </div>
            <div class="qr-text">Scan to verify</div>
        </div>
    </div>

    <!-- Footer -->
    <div class="footer">
        <p>This assessment report is prepared by SSCI Security Services. For inquiries, contact us at support@ssci.com | www.ssci.com</p>
        <p style="font-size: 10px; margin-top: 8px;">This is an official document and should be handled with confidentiality.</p>
    </div>
</div>

<script>
    // Initialize Leaflet map if coordinates are available
    <?php if (!empty($facility['latitude']) && !empty($facility['longitude'])): ?>
    (function() {
        // Ensure map container exists
        if (document.getElementById('mapContainer')) {
            const latitude = <?= floatval($facility['latitude']) ?>;
            const longitude = <?= floatval($facility['longitude']) ?>;
            
            // Initialize the map
            const map = L.map('mapContainer', {
                center: [latitude, longitude],
                zoom: 16,
                dragging: false,
                touchZoom: false,
                scrollWheelZoom: false,
                doubleClickZoom: false,
                boxZoom: false,
                keyboard: false,
                zoomControl: true
            });

            // Add OpenStreetMap tiles
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; OpenStreetMap contributors',
                maxZoom: 19
            }).addTo(map);

            // Add marker at facility location
            const marker = L.marker([latitude, longitude], {
                title: '<?= htmlspecialchars($facility['name'] ?? 'Facility') ?>'
            }).addTo(map);

            // Add popup to marker
            marker.bindPopup('<strong><?= htmlspecialchars($facility['name'] ?? 'Facility') ?></strong><br><?= htmlspecialchars($facility['location'] ?? '') ?>');

            // Fit bounds to show marker
            map.fitBounds(marker.getBounds(), {padding: [50, 50]});
        }
    })();
    <?php endif; ?>
</script>

</body>
</html>
