<?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','print')) { die('Access Denied'); }

/* ==========================================================================
   1. محرك البحث والفلترة (تمت إضافة فلاتر التاريخ من وإلى)
   ========================================================================== */
$f_bl         = trim($_GET['f_bl'] ?? '');
$f_item       = trim($_GET['f_item'] ?? '');
$f_date       = trim($_GET['f_date'] ?? '');
$f_date_from  = trim($_GET['f_date_from'] ?? ''); // التاريخ من
$f_date_to    = trim($_GET['f_date_to'] ?? '');   // التاريخ إلى
$f_status     = trim($_GET['f_status'] ?? '');
$f_agent      = trim($_GET['f_agent'] ?? ''); 
$f_customer   = trim($_GET['f_customer'] ?? ''); 
$f_ct_type    = trim($_GET['f_ct_type'] ?? ''); 

$conditions = ["1=1"];
$params = [];

if ($f_bl !== '') { $conditions[] = "s.bill_of_lading LIKE ?"; $params[] = "%$f_bl%"; }
if ($f_item !== '') { $conditions[] = "s.item_description LIKE ?"; $params[] = "%$f_item%"; }
if ($f_date !== '') { $conditions[] = "s.booking_date = ?"; $params[] = $f_date; }

// إضافة فلاتر التاريخ في الطباعة
if ($f_date_from !== '') { $conditions[] = "s.booking_date >= ?"; $params[] = $f_date_from; }
if ($f_date_to !== '') { $conditions[] = "s.booking_date <= ?"; $params[] = $f_date_to; }

if ($f_agent !== '') { $conditions[] = "s.agent_id = ?"; $params[] = $f_agent; }
if ($f_customer !== '') { $conditions[] = "s.customer_id = ?"; $params[] = $f_customer; }
if ($f_ct_type !== '') { $conditions[] = "s.container_type_id = ?"; $params[] = $f_ct_type; }

if ($f_status === 'Active') {
    $conditions[] = "s.status != 'Inactive'";
} elseif ($f_status === 'Inactive') {
    $conditions[] = "s.status = 'Inactive'";
}

$where = "WHERE " . implode(" AND ", $conditions);

// 2. Comprehensive Query
$stmt = $pdo->prepare("
    SELECT s.*, 
            u.full_name AS employee_name,
            c.name AS customer_name,
            a.name AS agent_name,
            src.hub_name AS pol_name, 
            dst.hub_name AS pod_name,
            ct.container_type AS container_type_display,
            cur.currency_code
    FROM newshipments s
    LEFT JOIN users u ON s.user_id = u.user_id 
    LEFT JOIN customers c ON s.customer_id = c.customer_id
    LEFT JOIN agents a ON s.agent_id = a.agent_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
    ORDER BY s.shipment_id DESC
");
$stmt->execute($params);
$shipments = $stmt->fetchAll();

$conf = $pdo->query("SELECT * FROM company_settings LIMIT 1")->fetch();

// متغيرات لتخزين الإجماليات
$total_cnee = 0;
$total_agent = 0;
$total_balance = 0;
$total_extra = 0;
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comprehensive Shipment Report</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, sans-serif; margin: 0; padding: 0; background: #fff; font-size: 10px; color: #1e293b; }
        .no-print-bar { background: #f1f5f9; padding: 15px; border-bottom: 2px solid #cbd5e1; text-align: center; }
        .column-toggle-container { 
            background: #ffffff; 
            padding: 15px; 
            display: flex; 
            flex-wrap: wrap; 
            justify-content: center; 
            gap: 15px;
            border-bottom: 1px solid #e2e8f0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .column-toggle-container label { 
            font-size: 11px; 
            font-weight: 600;
            color: #334155; 
            cursor: pointer; 
            display: flex; 
            align-items: center; 
            gap: 5px; 
            padding: 4px 8px;
            border-radius: 5px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
        }
        .btn { padding: 10px 20px; color: #fff; text-decoration: none; border-radius: 6px; font-weight: bold; cursor: pointer; border: none; font-size: 13px; display: inline-flex; align-items: center; gap: 8px; }
        .btn-print { background: #10b981; }
        .btn-back { background: #64748b; margin-left: 10px; }
        .report-container { width: 98%; margin: 20px auto; }
        .header-table { width: 100%; border-bottom: 2px solid #0f172a; margin-bottom: 15px; }

        /* التنسيق المتجاوب للجدول */
        .table-responsive {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        .results-table { width: 100%; border-collapse: collapse; table-layout: fixed; border: 1px solid #cbd5e1; min-width: 1200px; }
        .results-table th { background: #f8fafc; border: 1px solid #cbd5e1; padding: 8px; font-size: 9px; color: #334155; text-transform: uppercase; }
        .results-table td { border: 1px solid #e2e8f0; padding: 8px; vertical-align: top; word-wrap: break-word; text-align: center; line-height: 1.4; }
        .tfoot-total { background: #f8fafc; font-weight: bold; border-top: 2px solid #0f172a; }
        .text-blue { color: #2563eb; font-weight: bold; }
        .text-red { color: #dc2626; font-weight: bold; }
        .text-green { color: #059669; font-weight: bold; }
        
        .strike-amount { 
            text-decoration: line-through !important; 
            color: #94a3b8 !important; 
            font-style: italic; 
        }
        
        .hide-col { display: none !important; }

        /* تنسيقات خاصة بالجوال */
        @media screen and (max-width: 768px) {
            .no-print-bar { padding: 10px; }
            .btn { padding: 8px 12px; font-size: 11px; }
            .header-table td { display: block; width: 100% !important; text-align: center !important; margin-bottom: 10px; }
            .column-toggle-container { gap: 8px; padding: 10px; }
            .column-toggle-container label { font-size: 10px; padding: 3px 6px; }
        }

        @media print {
            @page { size: landscape; margin: 5mm; }
            .no-print-bar, .column-toggle-container { display: none !important; }
            body { font-size: 9px; }
            .results-table { min-width: 100%; table-layout: auto; }
            .results-table th { background: #f8fafc !important; -webkit-print-color-adjust: exact; }
            .tfoot-total { background: #f8fafc !important; -webkit-print-color-adjust: exact; }
            .report-container { width: 100%; margin: 0; }
            .table-responsive { overflow: visible; }
        }
    </style>
</head>
<body>

<div class="no-print-bar">
    <button class="btn btn-print" onclick="window.print()">
        <svg style="width:18px;height:18px" 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 Report
    </button>
    <a href="shipments.php" class="btn btn-back">Back to Shipments</a>
</div>

<div class="column-toggle-container">
    <strong style="width: 100%; text-align: center; margin-bottom: 5px; color: #64748b; font-size: 11px;">تخصيص الأعمدة والمجاميع:</strong>
    <label><input type="checkbox" checked onchange="toggleCol(0)"> #ID</label>
    <label><input type="checkbox" checked onchange="toggleCol(1)"> Booking Date</label>
    <label><input type="checkbox" checked onchange="toggleCol(2)"> Customer</label>
    <label><input type="checkbox" checked onchange="toggleCol(3)"> Agent</label>
    <label><input type="checkbox" checked onchange="toggleCol(4)"> Route</label>
    <label><input type="checkbox" checked onchange="toggleCol(5)"> Schedule</label>
    <label><input type="checkbox" checked onchange="toggleCol(6)"> Cargo </label>
    <label><input type="checkbox" checked onchange="toggleCol(7)"> Line</label>
    <label><input type="checkbox" checked onchange="toggleCol(8)"> Volume</label> 
    <label><input type="checkbox" checked onchange="toggleCol(9)"> Qty</label>
    <label><input type="checkbox" checked onchange="toggleCol(10)"> Cnee Rate</label>
    <label><input type="checkbox" checked onchange="toggleCol(11)"> Agent Rate</label>
    <label><input type="checkbox" checked onchange="toggleCol(12)"> Balance</label>
    <label><input type="checkbox" checked onchange="toggleCol(13)"> Extra Charges</label>
    <label><input type="checkbox" checked onchange="toggleCol(14)"> Status</label>
    <label style="color: #10b981;"><input type="checkbox" checked onchange="toggleTotals()"> <strong>Show Totals Row</strong></label>
</div>

<div class="report-container">
    <table class="header-table">
        <tr>
            <td width="35%" align="left">
                <strong style="font-size: 14px;"><?= htmlspecialchars($conf['company_name_en'] ?? 'Company Name') ?></strong><br>
                <?= htmlspecialchars($conf['address_en'] ?? '') ?>
            </td>
            <td width="30%" align="center">
                <h2 style="margin:0">SHIPMENT DETAILS REPORT</h2>
                <p style="margin:5px 0;">Total Records: <?= count($shipments) ?></p>
                <?php if($f_date_from || $f_date_to): ?>
                    <p style="margin:0; font-weight:bold;">Period: <?= $f_date_from ?: '...' ?> To <?= $f_date_to ?: '...' ?></p>
                <?php endif; ?>
            </td>
            <td width="35%" align="right">
                <strong style="font-size: 14px;"><?= htmlspecialchars($conf['company_name_ar'] ?? 'اسم الشركة') ?></strong><br>
                <?= htmlspecialchars($conf['address_ar'] ?? '') ?>
            </td>
        </tr>
    </table>

    <div class="table-responsive">
        <table class="results-table" id="reportTable">
            <thead>
                <tr>
                    <th width="40">ID</th>
                    <th width="80">Booking Date</th>
                    <th width="100">Customer</th>
                    <th width="100">Agent</th>
                    <th width="120">Route</th>
                    <th width="100">Schedule</th>
                    <th width="120">Cargo</th>
                    <th width="100">Line</th>
                    <th width="80">Container</th> 
                    <th width="40">Qty</th>
                    <th width="80">Cnee Rate</th>
                    <th width="80">Agent Rate</th>
                    <th width="80">Balance</th>
                    <th width="80">Extra</th>
                    <th width="70">Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($shipments as $s): 
                    $current_status_clean = strtoupper(trim($s['status']));
                    $is_inactive = ($current_status_clean === 'INACTIVE');
                    
                    $cnee_rate = (float)$s['grand_total'];
                    $agent_rate = (float)$s['agent_cost'] * (int)$s['container_count'];
                    $balance = $cnee_rate - $agent_rate;
                    $extra = (float)($s['extra_charges'] ?? 0);
                    
                    if (!$is_inactive) {
                        $total_cnee += $cnee_rate;
                        $total_agent += $agent_rate;
                        $total_balance += $balance;
                        $total_extra += $extra;
                    }

                    $amount_class = $is_inactive ? 'strike-amount' : '';
                ?>
                <tr style="<?= $is_inactive ? 'background-color: #fdf2f2;' : '' ?>">
                    <td>#<?= $s['shipment_id'] ?></td>
                    <td><?= $s['booking_date'] ?></td>
                    <td align="left"><strong><?= htmlspecialchars($s['customer_name'] ?? 'N/A') ?></strong></td>
                    <td align="left"><?= htmlspecialchars($s['agent_name'] ?: 'Direct') ?></td>
                    <td><?= htmlspecialchars($s['pol_name']) ?> &rarr; <?= htmlspecialchars($s['pod_name']) ?></td>
                    <td>ETD: <?= $s['departure_date'] ?><br>ETA: <?= $s['expected_arrival_date'] ?></td>
                    <td align="left"><b><?= htmlspecialchars($s['item_description']) ?></b></td>
                    <td align="left">Line: <?= htmlspecialchars($s['shipping_line']) ?></td>
                    <td><?= htmlspecialchars($s['container_type_display']) ?></td> 
                    <td><?= $s['container_count'] ?></td>
                    
                    <td class="<?= $amount_class ?> <?= !$is_inactive ? 'text-blue' : '' ?>" align="right">
                        <?= number_format($cnee_rate, 2) ?>
                    </td>
                    <td class="<?= $amount_class ?> <?= !$is_inactive ? 'text-red' : '' ?>" align="right">
                        <?= number_format($agent_rate, 2) ?>
                    </td>
                    <td class="<?= $amount_class ?> <?= !$is_inactive ? 'text-green' : '' ?>" align="right">
                        <?= number_format($balance, 2) ?>
                    </td>
                    <td class="<?= $amount_class ?>" align="right">
                        <?= number_format($extra, 2) ?>
                    </td>
                    <td style="<?= $is_inactive ? 'color:red; font-weight:bold;' : 'color:green; font-weight:bold;' ?>">
                        <?= $s['status'] ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot id="totalsFooter">
                <tr class="tfoot-total" id="totalsRow">
                    <td id="labelCell" colspan="10" align="right">TOTALS (Active Only):</td>
                    <td align="right" class="text-blue"><?= number_format($total_cnee, 2) ?></td>
                    <td align="right" class="text-red"><?= number_format($total_agent, 2) ?></td>
                    <td align="right" class="text-green"><?= number_format($total_balance, 2) ?></td>
                    <td align="right"><?= number_format($total_extra, 2) ?></td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<script>
function toggleCol(index) {
    const table = document.getElementById('reportTable');
    const rows = table.rows;

    for (let i = 0; i < rows.length; i++) {
        const cell = rows[i].cells[index];
        if (cell) {
            cell.classList.toggle('hide-col');
        }
    }
    updateFooterColspan();
}

function updateFooterColspan() {
    const labelCell = document.getElementById('labelCell');
    const headerCells = document.querySelectorAll('#reportTable thead th');
    
    let visibleBeforeFinancials = 0;
    // نحسب عدد الأعمدة الظاهرة قبل عمود Cnee Rate (رقم 10)
    for (let i = 0; i < 10; i++) {
        if (!headerCells[i].classList.contains('hide-col')) {
            visibleBeforeFinancials++;
        }
    }
    labelCell.colSpan = visibleBeforeFinancials;
}

function toggleTotals() {
    const totalsRow = document.getElementById('totalsRow');
    totalsRow.classList.toggle('hide-col');
}
</script>

</body>
</html>