<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../app/Utils.php';
require_once __DIR__ . '/../app/Models/Parcel.php';

$parcel_model = new Parcel($pdo);
$tracking_code = $_GET['code'] ?? null;
$parcel = null;

if ($tracking_code) {
    $parcel = $parcel_model->getByTrackingCode($tracking_code);
}

if (!$parcel) {
    die('Parcel not found');
}

// Fetch company settings
$stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
$settings = [];
while ($row = $stmt->fetch()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}
$company_name = $settings['company_name'] ?? 'RoutexShipping';
$company_address = $settings['company_address'] ?? '123 Logistics Ave, Global City';
$company_email = $settings['company_email'] ?? 'info@routexshipping.com';
$company_phone = $settings['company_phone'] ?? '+1-800-ROUTEX-1';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice - <?php echo htmlspecialchars($parcel['tracking_code']); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+39&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        @media print {
            .no-print { display: none !important; }
            body { background: white; padding: 0; }
            .shadow-lg { box-shadow: none; }
            .border { border-color: #e2e8f0; }
            #invoice { max-width: 100%; width: 100%; margin: 0; padding: 0; }
            #map { border: 1px solid #ddd; }
        }
        .barcode {
            font-family: 'Libre Barcode 39', cursive;
            font-size: 48px;
            line-height: 1;
        }
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        body { font-family: 'Inter', sans-serif; }
    </style>
</head>
<body class="bg-slate-50 text-slate-800 min-h-screen p-8 print:p-0">

    <div class="max-w-4xl mx-auto bg-white shadow-xl rounded-2xl p-10 print:rounded-none print:shadow-none" id="invoice">
        <!-- Header / Actions -->
        <div class="flex justify-between items-center mb-8 no-print">
            <a href="/routex/track?code=<?php echo urlencode($parcel['tracking_code']); ?>" class="text-slate-600 hover:text-blue-600 font-medium flex items-center transition">
                <i class="fas fa-arrow-left mr-2"></i> Back to Tracking
            </a>
            <button onclick="window.print()" class="bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700 transition font-medium flex items-center shadow-sm">
                <i class="fas fa-print mr-2"></i> Print Invoice
            </button>
        </div>

        <!-- Invoice Header -->
        <div class="border-b border-slate-200 pb-8 mb-8">
            <div class="flex flex-col md:flex-row justify-between items-start">
                <div class="mb-6 md:mb-0">
                    <div class="flex items-center mb-4">
                        <!-- Company Logo -->
                        <img src="/routex/images/routex-logo.png" alt="<?php echo htmlspecialchars($company_name); ?>" class="h-12 w-auto object-contain">
                    </div>
                    <div class="text-slate-500 text-sm space-y-1">
                        <p><?php echo htmlspecialchars($company_address); ?></p>
                        <p><?php echo htmlspecialchars($company_email); ?></p>
                        <p><?php echo htmlspecialchars($company_phone); ?></p>
                    </div>
                </div>
                <div class="text-left md:text-right">
                    <h2 class="text-xl font-bold text-slate-800 uppercase tracking-wide">Waybill / Invoice</h2>
                    <p class="text-slate-500 mt-1 text-sm">Date: <?php echo date('M d, Y'); ?></p>
                    <div class="mt-4">
                        <div class="barcode text-slate-900"><?php echo htmlspecialchars($parcel['tracking_code']); ?></div>
                        <p class="font-mono font-bold text-lg tracking-wider mt-1 text-slate-700"><?php echo htmlspecialchars($parcel['tracking_code']); ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sender & Receiver -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-12 mb-8">
            <div>
                <h3 class="text-slate-400 font-bold uppercase tracking-wider mb-4 border-b border-slate-100 pb-2 text-xs">From (Sender)</h3>
                <div class="text-slate-700 text-sm space-y-1">
                    <p class="font-bold text-base text-slate-900"><?php echo htmlspecialchars($parcel['sender_name']); ?></p>
                    <p><?php echo htmlspecialchars($parcel['sender_address']); ?></p>
                    <p><?php echo htmlspecialchars($parcel['sender_city'] . ', ' . $parcel['sender_country']); ?></p>
                    <p class="mt-2"><span class="text-slate-400">Phone:</span> <?php echo htmlspecialchars($parcel['sender_phone']); ?></p>
                    <p><span class="text-slate-400">Email:</span> <?php echo htmlspecialchars($parcel['sender_email']); ?></p>
                </div>
            </div>
            <div>
                <h3 class="text-slate-400 font-bold uppercase tracking-wider mb-4 border-b border-slate-100 pb-2 text-xs">To (Receiver)</h3>
                <div class="text-slate-700 text-sm space-y-1">
                    <p class="font-bold text-base text-slate-900"><?php echo htmlspecialchars($parcel['receiver_name']); ?></p>
                    <p><?php echo htmlspecialchars($parcel['receiver_address']); ?></p>
                    <p><?php echo htmlspecialchars($parcel['receiver_city'] . ', ' . $parcel['receiver_country']); ?></p>
                    <p class="mt-2"><span class="text-slate-400">Phone:</span> <?php echo htmlspecialchars($parcel['receiver_phone']); ?></p>
                    <p><span class="text-slate-400">Email:</span> <?php echo htmlspecialchars($parcel['receiver_email']); ?></p>
                </div>
            </div>
        </div>

        <!-- Shipment Details -->
        <div class="mb-8">
            <h3 class="text-slate-400 font-bold uppercase tracking-wider mb-4 border-b border-slate-100 pb-2 text-xs">Shipment Details</h3>
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-slate-50 border-b border-slate-200 print:bg-slate-100">
                        <th class="py-3 px-4 font-semibold text-slate-600 text-sm">Description</th>
                        <th class="py-3 px-4 font-semibold text-slate-600 text-sm">Service</th>
                        <th class="py-3 px-4 font-semibold text-slate-600 text-sm">Weight</th>
                        <th class="py-3 px-4 font-semibold text-slate-600 text-sm">Dimensions</th>
                        <th class="py-3 px-4 font-semibold text-slate-600 text-sm text-right">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="border-b border-slate-100">
                        <td class="py-4 px-4 text-slate-700 text-sm"><?php echo htmlspecialchars($parcel['package_description']); ?></td>
                        <td class="py-4 px-4 text-slate-700 text-sm capitalize"><?php echo str_replace('_', ' ', $parcel['service_type']); ?></td>
                        <td class="py-4 px-4 text-slate-700 text-sm"><?php echo htmlspecialchars($parcel['package_weight']); ?> kg</td>
                        <td class="py-4 px-4 text-slate-700 text-sm"><?php echo htmlspecialchars($parcel['package_dimensions']); ?></td>
                        <td class="py-4 px-4 text-right">
                            <span class="px-2 py-1 rounded text-xs font-bold uppercase bg-slate-100 text-slate-600 border border-slate-200 print:border-slate-300">
                                <?php echo htmlspecialchars($parcel['status']); ?>
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Map Section -->
        <div class="mb-8 break-inside-avoid">
            <h3 class="text-slate-400 font-bold uppercase tracking-wider mb-4 border-b border-slate-100 pb-2 text-xs">Current Location</h3>
            <div id="map" class="w-full h-64 rounded-lg bg-slate-50 border border-slate-200 z-0"></div>
        </div>

        <!-- Footer -->
        <div class="border-t border-slate-200 pt-8 text-center mt-12">
            <p class="text-slate-800 font-semibold mb-2 text-sm">Thank you for choosing <?php echo htmlspecialchars($company_name); ?>.</p>
            <p class="text-xs text-slate-500">This document serves as a proof of shipment. For any queries, please contact our support team.</p>
            <div class="mt-8 pt-4 border-t border-dashed border-slate-300 flex justify-between text-xs text-slate-400">
                <span>Printed on: <?php echo date('Y-m-d H:i:s'); ?></span>
                <span><?php echo htmlspecialchars($_SERVER['HTTP_HOST']); ?></span>
            </div>
        </div>
    </div>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Get coordinates or default to 0,0
            var lat = <?php echo $parcel['current_latitude'] ? $parcel['current_latitude'] : '51.505'; ?>;
            var lng = <?php echo $parcel['current_longitude'] ? $parcel['current_longitude'] : '-0.09'; ?>;
            var locationName = "<?php echo htmlspecialchars($parcel['current_location'] ?? 'Unknown Location'); ?>";

            var map = L.map('map', {
                zoomControl: false,
                attributionControl: false
            }).setView([lat, lng], 13);

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

            L.marker([lat, lng]).addTo(map).bindPopup(locationName).openPopup();
        });
    </script>
</body>
</html>