<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$shipment_id = isset($_GET['shipment_id']) ? intval($_GET['shipment_id']) : 0;

if (!$shipment_id) {
    die('Invalid shipment ID');
}

// Fetch complete shipment details
$sql_shipment = "SELECT s.*, 
                        st.service_name, st.service_code, st.service_category,
                        ol.location_name as origin_location, ol.location_code as origin_code,
                        dl.location_name as destination_location, dl.location_code as destination_code,
                        oc.country_name as origin_country,
                        dc.country_name as destination_country,
                        creator.full_name as created_by_name
                 FROM shipments s
                 LEFT JOIN service_types st ON s.service_id = st.service_id
                 LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
                 LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
                 LEFT JOIN countries oc ON ol.country_id = oc.country_id
                 LEFT JOIN countries dc ON dl.country_id = dc.country_id
                 LEFT JOIN users creator ON s.created_by = creator.user_id
                 WHERE s.shipment_id = ?";

$stmt_shipment = $conn->prepare($sql_shipment);
$stmt_shipment->bind_param("i", $shipment_id);
$stmt_shipment->execute();
$shipment = $stmt_shipment->get_result()->fetch_assoc();

if (!$shipment) {
    die('Shipment not found');
}

// Fetch latest tracking event
$sql_tracking = "SELECT event_type, event_status, event_description, location, event_date
                 FROM tracking_events 
                 WHERE shipment_id = ? 
                 ORDER BY event_date DESC 
                 LIMIT 1";
$stmt_tracking = $conn->prepare($sql_tracking);
$stmt_tracking->bind_param("i", $shipment_id);
$stmt_tracking->execute();
$latest_tracking = $stmt_tracking->get_result()->fetch_assoc();

// Fetch company settings
$sql_settings = "SELECT setting_key, setting_value FROM settings 
                 WHERE setting_key IN ('company_name', 'company_phone', 'company_address', 
                                       'company_city', 'company_logo', 'company_website')";
$result_settings = $conn->query($sql_settings);

$settings = [];
while ($row = $result_settings->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

function getSetting($key, $default = '') {
    global $settings;
    return $settings[$key] ?? $default;
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shipping Label - <?php echo $shipment['tracking_number']; ?></title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: white;
            color: #000;
            line-height: 1.3;
        }
        
        .label-container {
            width: 100mm;
            height: 150mm;
            margin: 0 auto;
            padding: 8px;
            background: white;
            border: 2px solid #000;
            position: relative;
            page-break-after: always;
        }
        
        .label-header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 8px;
            margin-bottom: 8px;
        }
        
        .company-logo {
            max-width: 40px;
            max-height: 30px;
            margin-bottom: 3px;
        }
        
        .company-name {
            font-size: 12px;
            font-weight: bold;
            margin-bottom: 2px;
        }
        
        .company-contact {
            font-size: 8px;
            margin-bottom: 1px;
        }
        
        .label-title {
            font-size: 10px;
            font-weight: bold;
            text-align: center;
            background: #000;
            color: #fff;
            padding: 3px;
            margin: 6px 0;
        }
        
        .tracking-section {
            text-align: center;
            background: #f0f0f0;
            border: 2px solid #000;
            padding: 6px;
            margin: 6px 0;
        }
        
        .tracking-number {
            font-size: 16px;
            font-weight: bold;
            font-family: 'Courier New', monospace;
            letter-spacing: 1px;
            margin-bottom: 3px;
        }
        
        .service-info {
            font-size: 9px;
            margin-bottom: 2px;
        }
        
        .address-section {
            margin: 8px 0;
            font-size: 9px;
        }
        
        .address-title {
            font-weight: bold;
            background: #eee;
            padding: 2px;
            margin-bottom: 3px;
            border: 1px solid #ccc;
        }
        
        .address-content {
            padding: 3px;
            border: 1px solid #ccc;
            min-height: 25mm;
            background: white;
        }
        
        .address-name {
            font-weight: bold;
            font-size: 10px;
            margin-bottom: 2px;
        }
        
        .address-company {
            font-style: italic;
            margin-bottom: 2px;
        }
        
        .address-line {
            margin-bottom: 1px;
        }
        
        .package-details {
            display: flex;
            justify-content: space-between;
            font-size: 8px;
            border: 1px solid #000;
            padding: 4px;
            margin: 6px 0;
            background: #f8f8f8;
        }
        
        .detail-item {
            text-align: center;
        }
        
        .detail-label {
            font-weight: bold;
            display: block;
        }
        
        .detail-value {
            font-size: 9px;
            margin-top: 1px;
        }
        
        .barcode-section {
            text-align: center;
            margin: 6px 0;
            padding: 4px;
            border: 1px dashed #000;
        }
        
        .barcode {
            font-family: 'Courier New', monospace;
            font-size: 8px;
            letter-spacing: 1px;
            margin: 2px 0;
        }
        
        .barcode-lines {
            font-family: monospace;
            font-size: 10px;
            letter-spacing: 0.5px;
        }
        
        .status-section {
            display: flex;
            justify-content: space-between;
            font-size: 8px;
            margin: 4px 0;
        }
        
        .status-box {
            border: 1px solid #000;
            padding: 2px;
            text-align: center;
            flex: 1;
            margin: 0 1px;
        }
        
        .priority-urgent {
            background: #ffebee;
            border-color: #f44336;
        }
        
        .priority-high {
            background: #fff3e0;
            border-color: #ff9800;
        }
        
        .priority-normal {
            background: #f5f5f5;
            border-color: #666;
        }
        
        .route-section {
            background: #e3f2fd;
            border: 2px solid #1976d2;
            padding: 4px;
            margin: 6px 0;
            text-align: center;
        }
        
        .route-title {
            font-weight: bold;
            font-size: 9px;
            margin-bottom: 2px;
        }
        
        .route-info {
            font-size: 11px;
            font-weight: bold;
        }
        
        .footer-info {
            font-size: 7px;
            text-align: center;
            margin-top: 6px;
            border-top: 1px solid #ccc;
            padding-top: 3px;
        }
        
        .no-print {
            display: block;
        }
        
        /* Print Styles */
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            
            .label-container {
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 5px;
                border: 2px solid #000;
            }
            
            .no-print {
                display: none !important;
            }
            
            @page {
                margin: 0;
                size: 100mm 150mm;
            }
        }
        
        /* Action Buttons */
        .action-buttons {
            position: fixed;
            top: 20px;
            right: 20px;
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-weight: 600;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-secondary {
            background: #64748b;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
    </style>
</head>

<body>
    <!-- Action Buttons -->
    <div class="action-buttons no-print">
        <button onclick="window.print()" class="btn btn-primary">
            🖨️ Print Label
        </button>
        <a href="view_shipment.php?id=<?php echo $shipment_id; ?>" class="btn btn-secondary">
            ← Back to Shipment
        </a>
    </div>

    <div class="label-container">
        <!-- Header -->
        <div class="label-header">
            <?php if (getSetting('company_logo')): ?>
            <img src="<?php echo getSetting('company_logo'); ?>" alt="Logo" class="company-logo">
            <?php endif; ?>
            
            <div class="company-name"><?php echo getSetting('company_name', 'Freight Express'); ?></div>
            <div class="company-contact"><?php echo getSetting('company_phone'); ?> | <?php echo getSetting('company_website'); ?></div>
        </div>

        <!-- Tracking Number -->
        <div class="tracking-section">
            <div class="tracking-number"><?php echo $shipment['tracking_number']; ?></div>
            <div class="service-info"><?php echo $shipment['service_name']; ?> | <?php echo $shipment['service_category']; ?></div>
            <div class="service-info">Booking: <?php echo date('d/M/Y H:i', strtotime($shipment['booking_date'])); ?></div>
        </div>

        <!-- Route Information -->
        <div class="route-section">
            <div class="route-title">ROUTE</div>
            <div class="route-info">
                <?php echo $shipment['origin_code']; ?> ➜ <?php echo $shipment['destination_code']; ?>
            </div>
            <div style="font-size: 8px; margin-top: 2px;">
                <?php echo $shipment['origin_location']; ?> to <?php echo $shipment['destination_location']; ?>
            </div>
        </div>

        <!-- Sender Information -->
        <div class="address-section">
            <div class="address-title">📤 FROM (SENDER)</div>
            <div class="address-content">
                <div class="address-name"><?php echo $shipment['sender_name']; ?></div>
                <?php if ($shipment['sender_company']): ?>
                <div class="address-company"><?php echo $shipment['sender_company']; ?></div>
                <?php endif; ?>
                <div class="address-line"><?php echo $shipment['sender_address']; ?></div>
                <div class="address-line">
                    <?php echo $shipment['sender_city']; ?><?php echo $shipment['sender_state'] ? ', ' . $shipment['sender_state'] : ''; ?>
                    <?php echo $shipment['sender_postal_code'] ? ' ' . $shipment['sender_postal_code'] : ''; ?>
                </div>
                <div class="address-line"><strong><?php echo $shipment['sender_country']; ?></strong></div>
                <div class="address-line">Tel: <?php echo $shipment['sender_phone']; ?></div>
            </div>
        </div>

        <!-- Receiver Information -->
        <div class="address-section">
            <div class="address-title">📥 TO (RECEIVER)</div>
            <div class="address-content">
                <div class="address-name"><?php echo $shipment['receiver_name']; ?></div>
                <?php if ($shipment['receiver_company']): ?>
                <div class="address-company"><?php echo $shipment['receiver_company']; ?></div>
                <?php endif; ?>
                <div class="address-line"><?php echo $shipment['receiver_address']; ?></div>
                <div class="address-line">
                    <?php echo $shipment['receiver_city']; ?><?php echo $shipment['receiver_state'] ? ', ' . $shipment['receiver_state'] : ''; ?>
                    <?php echo $shipment['receiver_postal_code'] ? ' ' . $shipment['receiver_postal_code'] : ''; ?>
                </div>
                <div class="address-line"><strong><?php echo $shipment['receiver_country']; ?></strong></div>
                <div class="address-line">Tel: <?php echo $shipment['receiver_phone']; ?></div>
            </div>
        </div>

        <!-- Package Details -->
        <div class="package-details">
            <div class="detail-item">
                <span class="detail-label">PIECES</span>
                <div class="detail-value"><?php echo $shipment['pieces']; ?></div>
            </div>
            <div class="detail-item">
                <span class="detail-label">WEIGHT</span>
                <div class="detail-value"><?php echo number_format($shipment['chargeable_weight'], 2); ?> KG</div>
            </div>
            <div class="detail-item">
                <span class="detail-label">VALUE</span>
                <div class="detail-value"><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['declared_value'], 2); ?></div>
            </div>
            <div class="detail-item">
                <span class="detail-label">TYPE</span>
                <div class="detail-value"><?php echo $shipment['package_type']; ?></div>
            </div>
        </div>

        <!-- Content Description -->
        <div style="border: 1px solid #ccc; padding: 3px; margin: 4px 0; font-size: 8px;">
            <strong>CONTENTS:</strong> <?php echo $shipment['content_description']; ?>
        </div>

        <!-- Status and Special Instructions -->
        <?php if ($shipment['special_instructions']): ?>
        <div style="background: #fffacd; border: 1px solid #000; padding: 3px; margin: 4px 0; font-size: 8px;">
            <strong>SPECIAL INSTRUCTIONS:</strong><br>
            <?php echo nl2br(htmlspecialchars($shipment['special_instructions'])); ?>
        </div>
        <?php endif; ?>

        <!-- Status Information -->
        <div class="status-section">
            <div class="status-box">
                <strong>STATUS</strong><br>
                <?php echo $shipment['status']; ?>
            </div>
            <div class="status-box">
                <strong>PAYMENT</strong><br>
                <?php echo $shipment['payment_status']; ?>
            </div>
            <?php if ($shipment['customs_status']): ?>
            <div class="status-box">
                <strong>CUSTOMS</strong><br>
                <?php echo $shipment['customs_status']; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Barcode Section -->
        <div class="barcode-section">
            <div class="barcode-lines">|||| || ||| |||| | ||| ||||| || |||||</div>
            <div class="barcode"><?php echo $shipment['tracking_number']; ?></div>
        </div>

        <!-- Footer -->
        <div class="footer-info">
            Track online: <?php echo getSetting('company_website', 'www.freight.co.ke'); ?><br>
            Generated: <?php echo date('d/M/Y H:i'); ?> | Created by: <?php echo $shipment['created_by_name']; ?>
            <?php if ($latest_tracking): ?>
            <br>Last Update: <?php echo $latest_tracking['event_description']; ?> (<?php echo date('d/M H:i', strtotime($latest_tracking['event_date'])); ?>)
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Auto print on load for direct print links
        if (window.location.search.includes('auto_print=1')) {
            window.onload = function() {
                setTimeout(function() {
                    window.print();
                }, 500);
            };
        }
        
        // Keyboard shortcut for printing
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
        
        // Mobile adjustments
        if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
            document.querySelector('.action-buttons').style.position = 'relative';
            document.querySelector('.action-buttons').style.top = 'auto';
            document.querySelector('.action-buttons').style.right = 'auto';
            document.querySelector('.action-buttons').style.marginBottom = '20px';
            document.querySelector('.action-buttons').style.justifyContent = 'center';
        }
    </script>
</body>
</html>