<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/config/config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

function h($value)
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

function asMoney($value)
{
    if (is_numeric($value)) {
        return (float) $value;
    }
    $clean = preg_replace('/[^0-9.\-]/', '', (string) $value);
    if ($clean === '' || $clean === '-' || $clean === '.') {
        return 0.0;
    }
    return (float) $clean;
}

function normalizeLabelResponse($response)
{
    if (is_array($response)) {
        return $response;
    }
    if (is_string($response)) {
        $decoded = json_decode($response, true);
        if (is_array($decoded)) {
            return $decoded;
        }
    }
    return [];
}

function cleanAddress($value)
{
    $value = trim((string) $value);
    if ($value === '') {
        return '';
    }
    $value = preg_replace('/\s*-\s*/', ', ', $value);
    $value = preg_replace('/\s+/', ' ', $value);
    return trim($value, ', ');
}

function resolveLogoPath($logo)
{
    $logo = trim((string) $logo);
    if ($logo === '') {
        return 'assets/images/logo-black.png';
    }
    if (preg_match('#^https?://#i', $logo) || strpos($logo, 'data:image') === 0) {
        return $logo;
    }
    return ltrim($logo, '/');
}

$bookingId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$waybill = trim($_GET['waybill'] ?? '');
$pdfSize = strtoupper(trim($_GET['pdf_size'] ?? 'A4'));
if (!in_array($pdfSize, ['A4', '4R'], true)) {
    $pdfSize = 'A4';
}

$error = '';
$labels = [];

try {
    if ($bookingId <= 0 && $waybill === '') {
        throw new Exception('Booking ID or Waybill is required');
    }

    $sql = "SELECT 
                b.id,
                b.booking_ref_id,
                b.waybill_no,
                b.courier_id,
                b.pickup_point_id,
                b.consignee_name,
                b.consignee_phone,
                b.consignee_address,
                b.consignee_city,
                b.consignee_state,
                b.consignee_pin,
                b.payment_mode,
                b.cod_amount,
                b.invoice_value,
                b.product_desc,
                b.rto_address,
                b.api_response,
                b.created_at,
                p.name AS pickup_name,
                p.address AS pickup_address,
                p.city AS pickup_city,
                p.pin AS pickup_pin,
                p.courier_id AS pickup_courier_id,
                p.company_id AS pickup_company_id,
                br.company_id AS branch_company_id,
                co.company_name,
                co.company_logo AS company_logo
            FROM tbl_bookings b
            LEFT JOIN tbl_pickup_points p ON p.id = b.pickup_point_id
            LEFT JOIN tbl_branch br ON br.id = p.branch_id
            LEFT JOIN tbl_company co ON co.id = COALESCE(p.company_id, br.company_id)
            WHERE " . ($bookingId > 0 ? "b.id = :id" : "b.waybill_no = :waybill") . "
            LIMIT 1";

    $stmt = $pdo->prepare($sql);
    if ($bookingId > 0) {
        $stmt->execute([':id' => $bookingId]);
    } else {
        $stmt->execute([':waybill' => $waybill]);
    }
    $booking = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$booking) {
        throw new Exception('Booking not found');
    }

    $waybillNo = $booking['waybill_no'] ?: $waybill;
    // For MPS, extract all waybills from api_response if available
    $allWaybills = [$waybillNo];
    $apiData = json_decode($booking['api_response'] ?? '', true);
    if (!empty($apiData['packages']) && is_array($apiData['packages'])) {
        $extracted = [];
        foreach ($apiData['packages'] as $pkg) {
            if (!empty($pkg['waybill'])) {
                $extracted[] = $pkg['waybill'];
            }
        }
        if (!empty($extracted)) {
            $allWaybills = $extracted;
        }
    }
    // Convert to comma-separated string for API call
    $waybillParam = implode(',', $allWaybills);

    if ($waybillNo === '') {
        throw new Exception('Waybill not generated yet');
    }

    $courierId = (int) ($booking['courier_id'] ?: $booking['pickup_courier_id']);
    if ($courierId <= 0) {
        throw new Exception('Courier not found for this booking');
    }

    $courierStmt = $pdo->prepare("SELECT id, partner_name, partner_code, api_key, api_url FROM tbl_courier_partner WHERE id = :id LIMIT 1");
    $courierStmt->execute([':id' => $courierId]);
    $courierData = $courierStmt->fetch(PDO::FETCH_ASSOC);
    if (!$courierData) {
        throw new Exception('Courier credentials not found');
    }

    require_once __DIR__ . '/api/label/services/courier_service.php';
    $apiResult = generateLabelFromCourier($courierData, [
        'waybill' => $waybillParam,
        'pdf' => false,
        'pdf_size' => $pdfSize
    ]);

    if (empty($apiResult['success'])) {
        throw new Exception($apiResult['message'] ?? 'Unable to fetch label JSON');
    }

    $decoded = normalizeLabelResponse($apiResult['response'] ?? []);
    if (!isset($decoded['packages']) || !is_array($decoded['packages']) || count($decoded['packages']) === 0) {
        throw new Exception('No package records in Delhivery JSON');
    }

    $clientLogo = resolveLogoPath($booking['company_logo'] ?? '');
    $invoiceValue = asMoney($booking['invoice_value'] ?? 0);
    $bookingCod = asMoney($booking['cod_amount'] ?? 0);

    foreach ($decoded['packages'] as $package) {
        if (!is_array($package)) {
            continue;
        }

        $deliveryType = trim((string) ($package['pt'] ?? $booking['payment_mode'] ?? ''));
        $mode = trim((string) ($package['mot'] ?? ''));
        $amountFromPackage = asMoney($package['rs'] ?? 0);
        $codAmount = asMoney($package['cod'] ?? 0);
        $linePrice = $amountFromPackage > 0 ? $amountFromPackage : ($invoiceValue > 0 ? $invoiceValue : ($bookingCod > 0 ? $bookingCod : 0));
        $lineTotal = strtoupper($deliveryType) === 'COD'
            ? ($codAmount > 0 ? $codAmount : ($bookingCod > 0 ? $bookingCod : $linePrice))
            : $linePrice;

        $productName = trim((string) ($package['prd'] ?? $booking['product_desc'] ?? ''));
        if ($productName === '') {
            $productName = 'Item';
        }

        $sellerAddress = trim((string) ($package['sadd'] ?? ''));
        if ($sellerAddress === '') {
            $sellerAddress = trim((string) (($booking['pickup_address'] ?? '') . ', ' . ($booking['pickup_city'] ?? '') . ' - ' . ($booking['pickup_pin'] ?? '')));
        }

        $returnAddress = trim((string) ($package['radd'] ?? ''));
        if ($returnAddress === '') {
            $returnAddress = trim((string) ($booking['rto_address'] ?? ''));
        }
        if ($returnAddress === '') {
            $returnAddress = trim((string) ($booking['pickup_address'] ?? ''));
        }

        $labels[] = [
            'client_logo' => $clientLogo,
            'delhivery_logo' => trim((string) ($package['delhivery_logo'] ?? '')),
            'courier_name' => trim((string) ($package['courier_name'] ?? $courierData['partner_name'] ?? '')),
            'master_waybill' => trim((string) ($package['mwn'] ?? '')),
            'is_master' => isset($package['mwn'], $package['wbn']) ? ((string) $package['mwn'] === (string) $package['wbn']) : null,
            'waybill' => trim((string) ($package['wbn'] ?? $waybillNo)),
            'short_code' => trim((string) ($package['sort_code'] ?? '')),
            'pincode' => trim((string) ($package['pin'] ?? $booking['consignee_pin'] ?? '')),
            'ship_name' => trim((string) ($package['name'] ?? $booking['consignee_name'] ?? '')),
            'ship_address' => cleanAddress($package['address'] ?? $booking['consignee_address'] ?? ''),
            'ship_destination' => cleanAddress($package['destination'] ?? (($booking['consignee_city'] ?? '') . ' - ' . ($booking['consignee_state'] ?? ''))),
            'delivery_type' => $deliveryType,
            'mode' => $mode,
            'line_price' => $linePrice,
            'line_total' => $lineTotal,
            'product_name' => $productName,
            'seller_name' => trim((string) ($package['snm'] ?? $booking['pickup_name'] ?? $booking['company_name'] ?? '')),
            'seller_address' => cleanAddress($sellerAddress),
            'order_id' => trim((string) ($package['oid'] ?? $booking['booking_ref_id'] ?? '')),
            'return_address' => cleanAddress($returnAddress),
            'return_pin' => trim((string) ($package['rpin'] ?? $booking['pickup_pin'] ?? '')),
            'created_at' => trim((string) ($package['cd'] ?? $booking['created_at'] ?? date('Y-m-d H:i:s'))),
        ];
    }

    if (count($labels) === 0) {
        throw new Exception('No valid package rows found');
    }

} catch (Exception $e) {
    $error = $e->getMessage();
}
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Shipment Label Print</title>
    <style>
        *,
        *::before,
        *::after {
            box-sizing: border-box;
        }

        @page {
            size: 101.6mm 152.4mm;
            margin: 0;
        }

        body {
            margin: 0;
            padding: 0;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 9px;
            line-height: 1.25;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .page {
            width: 101.6mm;
            height: 152.4mm;
            margin: 0;
            padding: 1mm;
            page-break-after: always;
            overflow: hidden;
            position: relative;
            box-sizing: border-box;
        }

        .page:last-child {
            page-break-after: auto;
        }

        .label-table {
            width: 100%;
            height: 100%;
            border-collapse: collapse;
            border-spacing: 0;
            border: 2px solid #000;
            font-size: 9px;
            table-layout: fixed;
            margin: 0;
        }

        .label-table > tbody > tr > td {
            border-top: 1px solid #000;
            border-left: none;
            border-right: none;
            border-bottom: none;
            vertical-align: top;
            padding: 0;
            word-break: break-word;
            overflow-wrap: break-word;
        }

        .label-table > tbody > tr:first-child > td {
            border-top: none;
        }

        .label-table > tbody > tr:last-child > td {
            border-bottom: none;
        }

        .inner-table {
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
            table-layout: fixed;
        }

        .inner-table td {
            border: 1px solid #000;
            padding: 1.8mm;
            vertical-align: top;
        }

        .inner-table td:not(:first-child) {
            border-left: 1px solid #000;
        }

        .inner-table tr:not(:first-child) td {
            border-top: 1px solid #000;
        }

        .center {
            text-align: center;
            vertical-align: middle;
        }

        .v-top {
            vertical-align: top;
        }

        .v-middle {
            vertical-align: middle;
        }

        .fw-bold {
            font-weight: 700;
        }

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

        .logo-section {
            padding: 1.5mm;
            text-align: center;
            vertical-align: middle;
            background: #fff;
        }

        .logo-img {
            max-width: 65px;
            max-height: 20px;
            display: inline-block;
            vertical-align: middle;
        }

        .barcode-section {
            padding: 10px 2mm 2mm 2mm;
            text-align: center;
        }

        .barcode-svg {
            width: 90%;
            height: 40px;
            display: block;
            margin: 0 auto 1.5mm;
        }

        .order-barcode-svg {
            width: 78%;
            height: 34px;
            display: block;
            margin: 0 auto 1mm;
        }

        .waybill-text {
            font-size: 10.5px;
            font-weight: 700;
            letter-spacing: 0.6px;
            margin: 1mm 0;
        }

        .pin-sc-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1mm 2mm 0;
        }

        .pin-text, .sc-text {
            font-size: 10.5px;
            font-weight: 700;
        }

        .section-header {
            font-size: 8.5px;
            font-weight: 700;
            text-transform: uppercase;
            margin-bottom: 0.8mm;
            color: #000;
            letter-spacing: 0.3px;
        }

        .ship-name {
            font-size: 10px;
            font-weight: 700;
            margin-bottom: 0.8mm;
            line-height: 1.2;
        }

        .ship-address {
            font-size: 8.5px;
            line-height: 1.4;
            max-height: 40px;
            overflow: hidden;
        }

        .ship-pin {
            font-size: 10px;
            font-weight: 700;
            margin-top: 0.8mm;
        }

        .payment-box {
            text-align: center;
            line-height: 1.5;
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 100%;
        }

        .payment-type {
            font-size: 10px;
            font-weight: 700;
            margin-bottom: 1mm;
        }

        .payment-mode {
            font-size: 9px;
            font-weight: 700;
            margin-bottom: 1mm;
        }

        .payment-currency {
            font-size: 8.5px;
            margin-bottom: 0.5mm;
        }

        .payment-amount {
            font-size: 11px;
            font-weight: 700;
        }

        .seller-label {
            font-size: 9px;
            font-weight: 700;
        }

        .seller-address {
            font-size: 8px;
            line-height: 1.4;
            max-height: 28px;
            overflow: hidden;
            margin-top: 0.8mm;
        }

        .date-box {
            font-size: 8.5px;
            line-height: 1.5;
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 100%;
        }

        .date-label {
            font-weight: 700;
            font-size: 9px;
            margin-bottom: 0.5mm;
        }

        .product-header {
            background: #f5f5f5;
            font-weight: 700;
            font-size: 8.5px;
            padding: 1.2mm;
            text-align: left;
            vertical-align: middle;
        }

        .product-cell {
            font-size: 8.5px;
            padding: 1.5mm;
        }

        .product-name {
            max-height: 20px;
            overflow: hidden;
            line-height: 1.35;
        }

        .product-price {
            font-size: 8.5px;
            text-align: center;
            line-height: 1.4;
        }

        .product-price b {
            font-size: 9px;
        }

        .order-section {
            padding: 2mm;
            text-align: center;
        }

        .order-text {
            font-size: 9.5px;
            font-weight: 700;
            margin-top: 1mm;
            letter-spacing: 0.3px;
        }

        .return-section {
            padding: 2mm;
        }

        .return-label {
            font-size: 9px;
            font-weight: 700;
        }

        .return-address {
            font-size: 8px;
            line-height: 1.4;
            max-height: 26px;
            overflow: hidden;
            margin-top: 0.8mm;
        }

        .small {
            font-size: 8.5px;
        }

        .error {
            text-align: center;
            color: #b91c1c;
            font-weight: 700;
            padding: 20px;
        }
    </style>
</head>

<body>
    <?php if ($error !== ''): ?>
        <div class="error"><?php echo h($error); ?></div>
    <?php else: ?>
        <?php foreach ($labels as $idx => $label): ?>
            <div class="page">
                <table class="label-table">
                    <!-- Logo Section -->
                    <tr>
                        <td colspan="2" style="padding:0;">
                            <table class="inner-table" style="border:none;">
                                <tr>
                                    <td class="logo-section" style="width:50%; border-right:1px solid #000; border-bottom:none;">
                                        <img class="logo-img" src="<?php echo h($label['client_logo']); ?>" alt="Client Logo">
                                    </td>
                                    <td class="logo-section" style="width:50%; border:none;">
                                        <?php if ($label['delhivery_logo'] !== ''): ?>
                                            <img class="logo-img" src="<?php echo h($label['delhivery_logo']); ?>" alt="Courier Logo">
                                        <?php else: ?>
                                            <b style="font-size:11px;"><?php echo h(strtoupper($label['courier_name'] ?: 'COURIER')); ?></b>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <?php if ($label['master_waybill'] !== ''): ?>
                    <!-- Master/Child Package Info -->
                    <tr>
                        <td colspan="2" style="padding:0;">
                            <table class="inner-table" style="border-top:1px solid #000; border-bottom:none;">
                                <tr>
                                    <td class="center small" style="width:50%; padding:0.8mm; border-right:1px solid #000; border-bottom:none;">
                                        <b><?php echo $label['is_master'] ? 'Master Package' : 'Child Package'; ?></b>
                                    </td>
                                    <td class="center small" style="width:50%; padding:0.8mm; border:none;">
                                        <b><?php echo h($label['master_waybill']); ?></b>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <?php endif; ?>

                    <!-- Waybill Barcode Section -->
                    <tr>
                        <td colspan="2" class="barcode-section" style="border-top:1px solid #000;">
                            <svg class="barcode-svg" data-value="<?php echo h($label['waybill']); ?>"></svg>
                            <div class="waybill-text"><?php echo h($label['waybill']); ?></div>
                            <div class="pin-sc-row">
                                <span class="pin-text">PIN: <?php echo h($label['pincode']); ?></span>
                                <span class="sc-text">SC: <?php echo h($label['short_code']); ?></span>
                            </div>
                        </td>
                    </tr>

                    <!-- Ship To & Payment Section -->
                    <tr>
                        <td colspan="2" style="padding:0;">
                            <table class="inner-table">
                                <tr>
                                    <td class="v-top" style="width:68%; padding:1.5mm;">
                                        <div class="section-header">SHIP TO:</div>
                                        <div class="ship-name"><?php echo h($label['ship_name']); ?></div>
                                        <div class="ship-address">
                                            <?php echo h($label['ship_address']); ?><br>
                                            <?php echo h($label['ship_destination']); ?>
                                        </div>
                                        <div class="ship-pin">PIN: <?php echo h($label['pincode']); ?></div>
                                    </td>
                                    <td class="v-middle" style="width:32%; padding:1.5mm;">
                                        <div class="payment-box">
                                            <div class="payment-type"><?php echo h($label['delivery_type']); ?></div>
                                            <div class="payment-mode"><?php echo h($label['mode'] === 'S' ? 'Surface' : ($label['mode'] === 'E' ? 'Express' : $label['mode'])); ?></div>
                                            <div class="payment-currency">INR</div>
                                            <div class="payment-amount"><?php echo h(number_format($label['delivery_type'] === 'COD' ? $label['line_total'] : $label['line_price'], 2)); ?></div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <!-- Seller & Date Section -->
                    <tr>
                        <td colspan="2" style="padding:0;">
                            <table class="inner-table">
                                <tr>
                                    <td class="v-top" style="width:58%; padding:1.5mm;">
                                        <span class="seller-label">Seller: <?php echo h($label['seller_name']); ?></span>
                                        <div class="seller-address"><?php echo h($label['seller_address']); ?></div>
                                    </td>
                                    <td class="v-middle" style="width:42%; padding:1.5mm;">
                                        <div class="date-box">
                                            <span class="date-label">Date:</span><br>
                                            <?php echo h(date('d-M-Y', strtotime($label['created_at']))); ?><br>
                                            <?php echo h(date('H:i', strtotime($label['created_at']))); ?>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <!-- Product Table -->
                    <tr>
                        <td colspan="2" style="padding:0;">
                            <table class="inner-table">
                                <tr>
                                    <td class="product-header" style="width:48%;">Product(Qty)</td>
                                    <td class="product-header center" style="width:26%;">Price</td>
                                    <td class="product-header center" style="width:26%;">Total</td>
                                </tr>
                                <tr>
                                    <td class="product-cell v-top">
                                        <div class="product-name"><?php echo h($label['product_name']); ?></div>
                                    </td>
                                    <td class="product-cell v-middle">
                                        <div class="product-price">
                                            INR<br><b><?php echo h(number_format($label['line_price'], 2)); ?></b>
                                        </div>
                                    </td>
                                    <td class="product-cell v-middle">
                                        <div class="product-price">
                                            INR<br><b><?php echo h(number_format($label['line_total'], 2)); ?></b>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="product-cell fw-bold">Total</td>
                                    <td class="product-cell v-middle">
                                        <div class="product-price">
                                            INR<br><b><?php echo h(number_format($label['line_price'], 2)); ?></b>
                                        </div>
                                    </td>
                                    <td class="product-cell v-middle">
                                        <div class="product-price">
                                            INR<br><b><?php echo h(number_format($label['line_total'], 2)); ?></b>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <!-- Order Barcode Section -->
                    <tr>
                        <td colspan="2" class="order-section center">
                            <svg class="order-barcode-svg" data-value="<?php echo h($label['order_id']); ?>"></svg>
                            <div class="order-text">Order: <?php echo h($label['order_id']); ?></div>
                        </td>
                    </tr>

                    <!-- Return Address Section -->
                    <tr>
                        <td colspan="2" class="return-section v-top">
                            <span class="return-label">Return Address:</span>
                            <div class="return-address">
                                <?php echo h($label['return_address']); ?>
                                <?php echo $label['return_pin'] !== '' ? ', PIN: ' . h($label['return_pin']) : ''; ?>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        <?php endforeach; ?>

        <script>
            (function () {
                function renderBarcodes() {
                    if (typeof JsBarcode !== 'function') {
                        return;
                    }
                    document.querySelectorAll('svg.barcode-svg, svg.order-barcode-svg').forEach(function (svg) {
                        var value = (svg.getAttribute('data-value') || '').trim();
                        if (!value) {
                            return;
                        }
                        try {
                            JsBarcode(svg, value, {
                                format: 'CODE128',
                                displayValue: false,
                                margin: 0,
                                width: 1.4,
                                height: 50
                            });
                        } catch (e) {
                            // keep text fallback only
                        }
                    });
                }

                function doPrint() {
                    setTimeout(function () {
                        window.print();
                    }, 300);
                }

                var js = document.createElement('script');
                js.src = 'https://cdn.jsdelivr.net/npm/jsbarcode@3.12.1/dist/JsBarcode.all.min.js';
                js.onload = function () {
                    renderBarcodes();
                    doPrint();
                };
                js.onerror = function () {
                    doPrint();
                };
                document.head.appendChild(js);
            })();
        </script>
    <?php endif; ?>
</body>

</html>