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

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

if (!can('shipments','view')) {
    die('Access Denied');
}

date_default_timezone_set('Asia/Aden');

$print_date = date('d/m/Y H:i');

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { die('Invalid Shipment ID'); }

/* جلب إعدادات الشركة */
$conf = $pdo->query("SELECT * FROM company_settings LIMIT 1")->fetch();

/* جلب بيانات الشحنة */
$stmt = $pdo->prepare("
    SELECT 
        s.*,
        c.name AS customer_name,
        src.hub_name AS pol_name,
        dst.hub_name AS pod_name,
        cur.currency_code,
        ct.container_type AS container_name_display
    FROM newshipments s
    LEFT JOIN customers c ON s.customer_id = c.customer_id
    LEFT JOIN transport_hubs src ON s.source_hub_id = src.hub_id
    LEFT JOIN transport_hubs dst ON s.destination_hub_id = dst.hub_id
    LEFT JOIN currencies cur ON s.currency_id = cur.currency_id
    LEFT JOIN container_types ct ON s.container_type_id = ct.container_id
    WHERE s.shipment_id = ?
");
$stmt->execute([$id]);
$s = $stmt->fetch();

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

$base_total = (float)$s['grand_total'];
$extra = (float)($s['extra_charges'] ?? 0);
$final_grand_total = $base_total + $extra;

$banks = $pdo->query("SELECT * FROM bank_accounts WHERE is_active = 1 LIMIT 3")->fetchAll();
$is_inactive = strtolower($s['status']) === 'inactive';

$status_label = (strtolower($s['status']) === 'inactive') ? 'inactive' : 'invoice';

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shipment Order #<?= str_pad($id,6,'0',STR_PAD_LEFT) ?></title>
<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@700;900&display=swap');
    
    @page { size: A4; margin: 10mm; }
    
    :root {
        --text-blue: #010552;   /* أزرق داكن للكتابة */
        --border-brown: #000000; /* بني لخطوط الجداول */
        --pure-white: #ffffff;
    }

    body {
        font-family: 'Roboto', sans-serif;
        margin: 0; padding: 0;
        background: #f0f2f5; /* لون خلفية خفيف للمعاينة فقط */
        color: var(--text-blue);
        font-size: 13px;
        font-weight: 900; 
    }

    .container {
        max-width: 800px;
        margin: 20px auto;
        padding: 40px;
        background: var(--pure-white); 
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
        position: relative;
    }

    /* زر الطباعة العائم للجوال */
    .print-btn-container {
        position: fixed;
        bottom: 20px;
        right: 20px;
        z-index: 9999;
    }

    .print-button {
        background: #2563eb;
        color: white;
        border: none;
        padding: 15px 25px;
        border-radius: 50px;
        font-weight: bold;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 16px;
    }

    /* الهيدر */
    .header {
        width: 100%;
        border-bottom: 4px solid var(--border-brown);
        margin-bottom: 15px;
        padding-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .company-name {
        font-size: 18px;
        color: var(--text-blue);
        text-transform: uppercase;
    }

    .logo img {
        max-width: 250px;
        max-height: 100px;
    }

    /* مربعات المعلومات */
    .info-section {
        display: flex;
        gap: 15px;
        margin-bottom: 20px;
    }

    .info-box {
        flex: 1;
        border: 2px solid var(--border-brown);
    }

    .info-box h4 {
        margin: 0;
        border-bottom: 2px solid var(--border-brown);
        color: var(--text-blue);
        padding: 6px 12px;
        font-size: 14px;
        text-transform: uppercase;
    }

    .info-content {
        padding: 10px 12px;
        line-height: 1.6;
    }

    /* الجداول */
    table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 15px;
        background: var(--pure-white);
    }

    table th, table td {
        border: 2px solid var(--border-brown);
        padding: 8px;
        text-align: center;
        color: var(--text-blue);
    }

    table th {
        font-size: 14px;
        text-transform: uppercase;
        background: #f8fafc;
    }

    .description-table td {
        text-align: left;
        vertical-align: top;
    }

    .extra-table {
        width: 100%;
        max-width: 350px;
        margin-left: auto;
        border: 2px solid var(--border-brown);
    }

    /* الإجمالي النهائي */
    .grand-total-box {
        width: 100%;
        border: 3px solid var(--border-brown);
        display: flex;
        margin-bottom: 20px;
    }

    .total-label {
        flex: 2;
        padding: 12px;
        text-align: right;
        font-size: 14px;
        border-right: 3px solid var(--border-brown);
    }

    .total-value {
        flex: 1;
        padding: 12px;
        text-align: center;
        font-size: 16px;
        background: #f1f5f9;
    }

    /* التذييل والتوقيع */
    .footer-flex {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
    }

    .bank-area {
        width: 60%;
        border: 2px solid var(--border-brown);
        padding: 10px;
        font-size: 11px;
    }

    .signature-container {
        width: 35%;
        border: 2px solid var(--border-brown);
        padding: 15px;
        text-align: center;
    }

    .signature-container img { max-width: 140px; }

    .footer-text {
        margin-top: 40px;
        border-top: 2px solid var(--border-brown);
        padding-top: 5px;
        text-align: center;
        font-size: 10px;
        color: var(--text-blue);
    }

    /* تنسيقات الطباعة (تخفي الزر وتزيل المسافات) */
    @media print {
        body { background: white; }
        .container { 
            margin: 0; 
            padding: 0; 
            box-shadow: none; 
            max-width: 100%;
        }
        .print-btn-container { display: none !important; }
    }

    /* تنسيق خاص لشاشات الجوال في المعاينة */
    @media screen and (max-width: 768px) {
        .container {
            margin: 10px;
            padding: 15px;
        }
        .info-section {
            flex-direction: column;
        }
        .header {
            flex-direction: column;
            text-align: center;
        }
        .logo { margin-top: 10px; }
        .footer-flex {
            flex-direction: column;
            gap: 15px;
        }
        .bank-area, .signature-container {
            width: 100%;
        }
        .total-label { font-size: 11px; }
    }
</style>
</head>
<body>

<div class="print-btn-container">
    <button onclick="window.print();" class="print-button">
        <svg style="width:24px;height:24px" viewBox="0 0 24 24">
            <path fill="currentColor" d="M18,3H6V7H18M19,12A1,1 0 0,1 18,11A1,1 0 0,1 19,10A1,1 0 0,1 20,11A1,1 0 0,1 19,12M16,19H8V14H16M19,8H5A3,3 0 0,0 2,11V17H6V21H18V17H22V11A3,3 0 0,0 19,8Z" />
        </svg>
        Print / طباعة
    </button>
</div>

<div class="container">

    <div class="header">
        <div>
            <div class="company-name"><?= htmlspecialchars($conf['company_name_en']) ?></div>
            <div style="margin-top: 5px; font-size: 11px;">
                TEL: <?= htmlspecialchars($conf['phones_en']) ?>
            </div>
        </div>
        <div class="logo">
            <?php if(!empty($conf['logo_path'])): ?>
                <img src="../assets/img/<?= htmlspecialchars($conf['logo_path']) ?>">
            <?php endif; ?>
        </div>
    </div>

    <div style="text-align: right; font-size: 11px; margin-bottom: 5px;">
        STATUS: <span style="color: <?= $is_inactive ? 'red' : 'green' ?>"><?= strtoupper($status_label) ?></span>
    </div>

    <div class="info-section">
        <div class="info-box">
            <h4>Client & Route / العميل والمسار</h4>
            <div class="info-content">
                <div>CLIENT: <?= htmlspecialchars($s['customer_name']) ?></div>
                <div>SHIPPING LINE: <?= htmlspecialchars($s['shipping_line'] ?: '---') ?></div>
                <div>ROUTE: <?= htmlspecialchars($s['pol_name']) ?> TO <?= htmlspecialchars($s['pod_name']) ?></div>
                <div>VOLUMES: <?= (int)$s['container_count'] ?> × <?= htmlspecialchars($s['container_name_display']) ?></div>
            </div>
        </div>
        <div class="info-box">
            <h4>Order Details / تفاصيل الشحنة</h4>
            <div class="info-content">
                <div><strong>Print Date:</strong> <?= $print_date ?></div>
                <div>REF NO: #<?= str_pad($id,6,'0',STR_PAD_LEFT) ?></div>
                <div>BOOKING: <?= $s['booking_date'] ? date('d/m/Y', strtotime($s['booking_date'])) : '---' ?></div>
                <div>ETD / ETA: <?= $s['departure_date'] ? date('d/m/Y', strtotime($s['departure_date'])) : '---' ?> / <?= $s['expected_arrival_date'] ? date('d/m/Y', strtotime($s['expected_arrival_date'])) : '---' ?></div>
                <div>B/L NO: <?= htmlspecialchars($s['bill_of_lading'] ?: '---') ?></div>
            </div>
        </div>
    </div>

    <table class="description-table">
        <thead>
            <tr><th style="text-align: left;">PRODUCT DESCRIPTION / وصف المنتج والخدمة</th></tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <div style="font-size: 15px; margin-bottom: 8px; text-decoration: underline;">
                        <?= htmlspecialchars($s['item_description']) ?>
                    </div>
                    <div style="line-height: 1.5; font-size: 12px; font-weight: normal;">
                        <?= nl2br(htmlspecialchars($s['shipment_details'])) ?>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>

    <table>
        <thead>
            <tr>
                <th>Order Type</th>
                <th>Qty</th>
                <th>Unit</th>
                <th>Rate (<?= $s['currency_code'] ?>)</th>
                <th>Sub-Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><?= htmlspecialchars($s['order_type'] ?: 'Freight Services') ?></td>
                <td><?= (int)$s['container_count'] ?></td>
                <td><?= htmlspecialchars($s['container_name_display']) ?></td>
                <td><?= number_format($s['price_per_container'], 2) ?></td>
                <td><?= number_format($base_total, 2) ?></td>
            </tr>
        </tbody>
    </table>

    <?php if ($extra > 0): ?>
    <table class="extra-table">
        <thead>
            <tr><th colspan="2">ADDITIONAL CHARGES / مصاريف إضافية</th></tr>
        </thead>
        <tbody>
            <tr>
                <td style="text-align: left; font-size: 11px;"><?= htmlspecialchars($s['extra_charges_notes']) ?></td>
                <td style="width: 100px; font-weight: bold;"><?= number_format($extra, 2) ?></td>
            </tr>
        </tbody>
    </table>
    <?php endif; ?>

    <div class="grand-total-box">
        <div class="total-label">NET PAYABLE AMOUNT (<?= $s['currency_code'] ?>)</div>
        <div class="total-value"><?= number_format($final_grand_total, 2) ?></div>
    </div>

    <div class="footer-flex">
        <div class="bank-area">
            <div style="text-decoration: underline; margin-bottom: 8px; font-weight: bold;">BANK ACCOUNT DETAILS:</div>
            <?php foreach($banks as $bank): ?>
                <div style="margin-bottom: 4px;">
                    <?= htmlspecialchars($bank['bank_name_ar'] ?? $bank['bank_name']) ?>: 
                    <span style="font-family: monospace;"><?= htmlspecialchars($bank['account_number']) ?></span>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="signature-container">
            <div style="font-size: 11px; margin-bottom: 5px;">FOR <?= htmlspecialchars($conf['company_name_en']) ?></div>
            <?php if(file_exists('../assets/signatures/company_signature.png')): ?>
                <img src="../assets/signatures/company_signature.png">
            <?php else: ?>
                <div style="height: 60px;"></div>
            <?php endif; ?>
            <div style="border-top: 2px solid var(--border-brown); padding-top: 5px; font-size: 11px;">AUTHORISED SIGNATORY</div>
        </div>
    </div>

    <div class="footer-text">
        <?= htmlspecialchars($conf['footer_text_en'] ?? 'All transactions are subject to company standard terms and conditions.') ?>
    </div>
</div>

</body>
</html>