<?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 with customer and payment information
$sql_shipment = "SELECT s.*, 
                        c.first_name, c.last_name, c.phone, c.email, c.address_line1, c.customer_code, c.company_name, c.customer_type,
                        st.service_name, st.service_code,
                        ol.location_name as origin_location, ol.location_code as origin_code,
                        dl.location_name as destination_location, dl.location_code as destination_code,
                        creator.full_name as created_by_name,
                        ct.charge_name, ct.charge_code
                 FROM shipments s
                 LEFT JOIN customers c ON s.sender_customer_id = c.customer_id
                 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 users creator ON s.created_by = creator.user_id
                 LEFT JOIN charge_types ct ON ct.charge_code = 'FUEL'
                 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 payment details for this shipment
$sql_payments = "SELECT p.*, pm.method_name, u.full_name as processed_by_name
                 FROM payments p
                 LEFT JOIN payment_methods pm ON p.payment_method_id = pm.method_id
                 LEFT JOIN users u ON p.processed_by = u.user_id
                 WHERE p.shipment_id = ? AND p.status = 'CONFIRMED'
                 ORDER BY p.created_at ASC";
$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $shipment_id);
$stmt_payments->execute();
$payments = $stmt_payments->get_result();

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

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

// Helper function to get setting
function getSetting($key, $default = '') {
    global $settings;
    return $settings[$key] ?? $default;
}

// Generate or fetch receipt number
$receipt_number = '';
$existing_receipt = $conn->query("SELECT receipt_number FROM receipts WHERE shipment_id = $shipment_id LIMIT 1");
if ($existing_receipt && $existing_receipt->num_rows > 0) {
    $receipt_number = $existing_receipt->fetch_assoc()['receipt_number'];
} else {
    // Generate new receipt number based on shipment
    $receipt_number = 'RCP-' . $shipment['tracking_number'];
    
    // Insert receipt record
    $receipt_sql = "INSERT INTO receipts (shipment_id, customer_id, receipt_number, receipt_type, total_amount, payment_method, issued_by) 
                   VALUES (?, ?, ?, 'SHIPMENT', ?, 'FREIGHT', ?)";
    $stmt_receipt = $conn->prepare($receipt_sql);
    $stmt_receipt->bind_param("iisdi", $shipment_id, $shipment['sender_customer_id'], $receipt_number, $shipment['total_charges'], $user_id);
    
    if ($stmt_receipt->execute()) {
        $receipt_id = $conn->insert_id;
        // Update print count
        $conn->query("UPDATE receipts SET printed_count = printed_count + 1 WHERE receipt_id = $receipt_id");
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shipment Receipt #<?php echo $receipt_number; ?> - <?php echo getSetting('company_name', 'Freight Express'); ?></title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Courier New', monospace;
            background: white;
            color: #000;
            line-height: 1.4;
        }
        
        .receipt-container {
            width: 80mm;
            margin: 0 auto;
            padding: 10px;
            background: white;
            min-height: 100vh;
        }
        
        .receipt-header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        
        .company-logo {
            max-width: 60px;
            max-height: 40px;
            margin-bottom: 5px;
        }
        
        .company-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 3px;
            text-transform: uppercase;
        }
        
        .company-details {
            font-size: 10px;
            margin-bottom: 2px;
        }
        
        .receipt-title {
            font-size: 14px;
            font-weight: bold;
            margin: 10px 0 5px 0;
            text-align: center;
            text-decoration: underline;
        }
        
        .receipt-info {
            margin-bottom: 15px;
            font-size: 11px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .customer-section {
            border-top: 1px dashed #000;
            border-bottom: 1px dashed #000;
            padding: 8px 0;
            margin: 10px 0;
        }
        
        .section-title {
            font-weight: bold;
            margin-bottom: 5px;
            text-decoration: underline;
        }
        
        .shipment-details {
            width: 100%;
            font-size: 10px;
            margin: 15px 0;
        }
        
        .shipment-details th {
            border-bottom: 1px solid #000;
            padding: 3px 2px;
            text-align: left;
            font-weight: bold;
        }
        
        .shipment-details td {
            padding: 3px 2px;
            border-bottom: 1px dotted #666;
        }
        
        .text-right {
            text-align: right;
        }
        
        .text-center {
            text-align: center;
        }
        
        .totals-section {
            border-top: 1px solid #000;
            padding-top: 8px;
            margin-top: 10px;
            font-size: 11px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .total-row.grand-total {
            font-weight: bold;
            font-size: 13px;
            border-top: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 5px 0;
            margin-top: 5px;
        }
        
        .payment-section {
            margin: 15px 0;
            font-size: 11px;
        }
        
        .payment-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
        }
        
        .receipt-footer {
            text-align: center;
            margin-top: 20px;
            border-top: 1px dashed #000;
            padding-top: 10px;
            font-size: 10px;
        }
        
        .thank-you {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .footer-info {
            margin-bottom: 3px;
        }
        
        .barcode-section {
            text-align: center;
            margin: 15px 0;
        }
        
        .barcode-text {
            font-size: 8px;
            font-family: monospace;
            letter-spacing: 1px;
            margin-top: 5px;
        }
        
        .status-badge {
            display: inline-block;
            padding: 2px 6px;
            font-size: 8px;
            background: #000;
            color: #fff;
            text-transform: uppercase;
        }
        
        .no-print {
            display: block;
        }
        
        /* Print Styles */
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            
            .receipt-container {
                width: 100%;
                margin: 0;
                padding: 5px;
            }
            
            .no-print {
                display: none !important;
            }
            
            @page {
                margin: 0;
                size: 80mm auto;
            }
        }
        
        /* Mobile Styles */
        @media (max-width: 768px) {
            .receipt-container {
                width: 100%;
                max-width: 350px;
                padding: 15px;
            }
            
            .receipt-header {
                padding-bottom: 15px;
                margin-bottom: 20px;
            }
            
            .company-name {
                font-size: 18px;
            }
            
            .receipt-title {
                font-size: 16px;
            }
            
            .shipment-details {
                font-size: 12px;
            }
            
            .totals-section {
                font-size: 13px;
            }
            
            .total-row.grand-total {
                font-size: 15px;
            }
        }
        
        /* 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 Receipt
        </button>
        <a href="view_shipment.php?id=<?php echo $shipment_id; ?>" class="btn btn-secondary">
            ← Back to Shipment
        </a>
    </div>

    <div class="receipt-container">
        <!-- Header -->
        <div class="receipt-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>
            
            <?php if (getSetting('company_phone')): ?>
            <div class="company-details">Tel: <?php echo getSetting('company_phone'); ?></div>
            <?php endif; ?>
            
            <?php if (getSetting('company_email')): ?>
            <div class="company-details">Email: <?php echo getSetting('company_email'); ?></div>
            <?php endif; ?>
            
            <?php if (getSetting('company_address')): ?>
            <div class="company-details"><?php echo getSetting('company_address'); ?></div>
            <div class="company-details"><?php echo getSetting('company_city', 'Nairobi'); ?></div>
            <?php endif; ?>
            
            <?php if (getSetting('company_tax_id')): ?>
            <div class="company-details">Tax ID: <?php echo getSetting('company_tax_id'); ?></div>
            <?php endif; ?>
        </div>

        <!-- Receipt Title -->
        <div class="receipt-title">SHIPMENT RECEIPT</div>

        <!-- Receipt Information -->
        <div class="receipt-info">
            <div class="info-row">
                <span>Receipt #:</span>
                <span><strong><?php echo $receipt_number; ?></strong></span>
            </div>
            <div class="info-row">
                <span>Tracking #:</span>
                <span><strong><?php echo $shipment['tracking_number']; ?></strong></span>
            </div>
            <div class="info-row">
                <span>Date:</span>
                <span><?php echo date('d/M/Y H:i', strtotime($shipment['booking_date'])); ?></span>
            </div>
            <div class="info-row">
                <span>Created by:</span>
                <span><?php echo $shipment['created_by_name']; ?></span>
            </div>
            <div class="info-row">
                <span>Status:</span>
                <span class="status-badge"><?php echo $shipment['status']; ?></span>
            </div>
        </div>

        <!-- Customer Information -->
        <div class="customer-section">
            <div class="section-title">CUSTOMER DETAILS</div>
            <?php if ($shipment['customer_code']): ?>
            <div class="info-row">
                <span>Customer:</span>
                <span><?php echo $shipment['customer_code']; ?></span>
            </div>
            <div class="info-row">
                <span>Name:</span>
                <span><?php echo $shipment['customer_type'] == 'CORPORATE' ? $shipment['company_name'] : $shipment['first_name'] . ' ' . $shipment['last_name']; ?></span>
            </div>
            <?php else: ?>
            <div class="info-row">
                <span>Sender:</span>
                <span><?php echo $shipment['sender_name']; ?></span>
            </div>
            <?php endif; ?>
            <div class="info-row">
                <span>Phone:</span>
                <span><?php echo $shipment['sender_phone']; ?></span>
            </div>
            <?php if ($shipment['sender_email']): ?>
            <div class="info-row">
                <span>Email:</span>
                <span><?php echo $shipment['sender_email']; ?></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Shipment Details -->
        <table class="shipment-details">
            <thead>
                <tr>
                    <th>Description</th>
                    <th class="text-center">Qty</th>
                    <th class="text-right">Amount</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <strong><?php echo $shipment['service_name']; ?></strong><br>
                        <small><?php echo $shipment['origin_location']; ?> → <?php echo $shipment['destination_location']; ?></small><br>
                        <small><?php echo $shipment['content_description']; ?></small>
                    </td>
                    <td class="text-center"><?php echo $shipment['pieces']; ?> pc(s)<br><small><?php echo number_format($shipment['chargeable_weight'], 2); ?> kg</small></td>
                    <td class="text-right"><?php echo number_format($shipment['freight_charges'], 2); ?></td>
                </tr>
                
                <?php if ($shipment['fuel_surcharge'] > 0): ?>
                <tr>
                    <td>Fuel Surcharge</td>
                    <td class="text-center">-</td>
                    <td class="text-right"><?php echo number_format($shipment['fuel_surcharge'], 2); ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['insurance_charges'] > 0): ?>
                <tr>
                    <td>Insurance</td>
                    <td class="text-center">-</td>
                    <td class="text-right"><?php echo number_format($shipment['insurance_charges'], 2); ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['handling_charges'] > 0): ?>
                <tr>
                    <td>Handling</td>
                    <td class="text-center">-</td>
                    <td class="text-right"><?php echo number_format($shipment['handling_charges'], 2); ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['customs_charges'] > 0): ?>
                <tr>
                    <td>Customs</td>
                    <td class="text-center">-</td>
                    <td class="text-right"><?php echo number_format($shipment['customs_charges'], 2); ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['other_charges'] > 0): ?>
                <tr>
                    <td>Other Charges</td>
                    <td class="text-center">-</td>
                    <td class="text-right"><?php echo number_format($shipment['other_charges'], 2); ?></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Totals Section -->
        <div class="totals-section">
            <div class="total-row">
                <span>Subtotal:</span>
                <span><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($shipment['total_charges'] - $shipment['tax_amount'], 2); ?></span>
            </div>
            
            <?php if ($shipment['tax_amount'] > 0): ?>
            <div class="total-row">
                <span>Tax (16%):</span>
                <span><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($shipment['tax_amount'], 2); ?></span>
            </div>
            <?php endif; ?>
            
            <div class="total-row grand-total">
                <span>TOTAL:</span>
                <span><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['total_charges'], 2); ?></span>
            </div>
        </div>

        <!-- Payment Information -->
        <div class="payment-section">
            <div class="section-title">PAYMENT DETAILS</div>
            
            <?php if ($payments->num_rows > 0): ?>
                <?php while ($payment = $payments->fetch_assoc()): ?>
                <div class="payment-row">
                    <span><?php echo $payment['method_name'] ?? 'Payment'; ?>:</span>
                    <span><?php echo $shipment['currency']; ?> <?php echo number_format($payment['amount'], 2); ?></span>
                </div>
                <div style="font-size: 9px; color: #666; margin-bottom: 5px;">
                    Date: <?php echo date('d/M/Y H:i', strtotime($payment['created_at'])); ?>
                    <?php if ($payment['processed_by_name']): ?>
                    | By: <?php echo $payment['processed_by_name']; ?>
                    <?php endif; ?>
                </div>
                <?php endwhile; ?>
            <?php endif; ?>
            
            <div class="payment-row" style="border-top: 1px dotted #000; padding-top: 5px; margin-top: 5px;">
                <span><strong>Payment Status:</strong></span>
                <span><strong><?php echo ucfirst(strtolower($shipment['payment_status'])); ?></strong></span>
            </div>
        </div>

        <!-- Service Information -->
        <div class="customer-section">
            <div class="section-title">SHIPMENT DETAILS</div>
            
            <div class="info-row">
                <span>Service:</span>
                <span><?php echo $shipment['service_name']; ?></span>
            </div>
            
            <div class="info-row">
                <span>Route:</span>
                <span><?php echo $shipment['origin_location']; ?> → <?php echo $shipment['destination_location']; ?></span>
            </div>
            
            <div class="info-row">
                <span>Package Type:</span>
                <span><?php echo $shipment['package_type']; ?></span>
            </div>
            
            <div class="info-row">
                <span>Weight:</span>
                <span><?php echo number_format($shipment['chargeable_weight'], 2); ?> kg</span>
            </div>
            
            <?php if ($shipment['declared_value'] > 0): ?>
            <div class="info-row">
                <span>Declared Value:</span>
                <span><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['declared_value'], 2); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($shipment['estimated_delivery']): ?>
            <div class="info-row">
                <span>Est. Delivery:</span>
                <span><?php echo date('d/M/Y H:i', strtotime($shipment['estimated_delivery'])); ?></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Addresses -->
        <div class="customer-section">
            <div class="section-title">ADDRESSES</div>
            
            <div style="margin-bottom: 10px;">
                <strong>FROM:</strong><br>
                <?php echo $shipment['sender_name']; ?><br>
                <?php if ($shipment['sender_company']): ?>
                <?php echo $shipment['sender_company']; ?><br>
                <?php endif; ?>
                <?php echo $shipment['sender_address']; ?><br>
                <?php echo $shipment['sender_city']; ?>, <?php echo $shipment['sender_country']; ?><br>
                Tel: <?php echo $shipment['sender_phone']; ?>
            </div>
            
            <div>
                <strong>TO:</strong><br>
                <?php echo $shipment['receiver_name']; ?><br>
                <?php if ($shipment['receiver_company']): ?>
                <?php echo $shipment['receiver_company']; ?><br>
                <?php endif; ?>
                <?php echo $shipment['receiver_address']; ?><br>
                <?php echo $shipment['receiver_city']; ?>, <?php echo $shipment['receiver_country']; ?><br>
                Tel: <?php echo $shipment['receiver_phone']; ?>
            </div>
        </div>

        <!-- Special Instructions -->
        <?php if ($shipment['special_instructions']): ?>
        <div class="customer-section">
            <div class="section-title">SPECIAL INSTRUCTIONS</div>
            <div><?php echo nl2br(htmlspecialchars($shipment['special_instructions'])); ?></div>
        </div>
        <?php endif; ?>

        <!-- Barcode Section -->
        <div class="barcode-section">
            <div style="border: 1px solid #000; padding: 5px; font-size: 8px; letter-spacing: 2px;">
                |||| || ||| |||| | ||| ||||| || |||||
            </div>
            <div class="barcode-text"><?php echo $shipment['tracking_number']; ?></div>
        </div>

        <!-- Footer -->
        <div class="receipt-footer">
            <div class="thank-you">THANK YOU FOR CHOOSING US!</div>
            
            <div class="footer-info">Track your shipment online</div>
            <div class="footer-info">Visit: <?php echo getSetting('company_website', 'www.freight.co.ke'); ?></div>
            <div class="footer-info">Call: <?php echo getSetting('company_phone', '+254700000000'); ?></div>
            
            <div style="margin-top: 10px; font-size: 8px; color: #666;">
                Generated: <?php echo date('d/M/Y H:i:s'); ?>
            </div>
            
            <div style="margin-top: 5px; font-size: 8px; color: #666;">
                Keep this receipt for your records
            </div>
        </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);
            };
        }
        
        // Print function
        function printReceipt() {
            window.print();
        }
        
        // Keyboard shortcut for printing
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
        
        // Mobile-friendly print button
        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>
