<?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');
}

/* ==========================================================================
   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'] ?? ''); 

// بناء مصفوفة المتغيرات لاستخدامها في رابط الطباعة
$query_params = $_GET; 
$print_url = "shipment_print.php?" . http_build_query($query_params);

$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);

// جلب بيانات القوائم المنسدلة
$all_agents = $pdo->query("SELECT agent_id, name FROM agents ORDER BY name ASC")->fetchAll();
$all_customers = $pdo->query("SELECT customer_id, name FROM customers ORDER BY name ASC")->fetchAll();
$container_types = $pdo->query("SELECT container_id, container_type FROM container_types ORDER BY container_type ASC")->fetchAll();

// الاستعلام الشامل
$stmt = $pdo->prepare("
    SELECT s.*, 
            u.full_name AS employee_name, 
            ag.name AS agent_name, 
            c.name AS customer_name,
            ct.container_type AS container_type_name, 
            h1.hub_name AS source_name, 
            h2.hub_name AS destination_name
    FROM newshipments s
    LEFT JOIN users u ON s.user_id = u.user_id 
    LEFT JOIN agents ag ON s.agent_id = ag.agent_id
    LEFT JOIN customers c ON s.customer_id = c.customer_id
    LEFT JOIN container_types ct ON s.container_type_id = ct.container_id
    LEFT JOIN transport_hubs h1 ON s.source_hub_id = h1.hub_id
    LEFT JOIN transport_hubs h2 ON s.destination_hub_id = h2.hub_id
    $where
    ORDER BY s.shipment_id DESC
");
$stmt->execute($params);
$shipments = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detailed Logistics Management</title>
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/css/select2.min.css" rel="stylesheet" />
    
    <style>
        :root{
            --bg:#f8fafc; --card:#ffffff; --border:#e2e8f0; --text:#1e293b;
            --muted:#64748b; --primary:#2563eb; --success:#10b981;
            --danger:#ef4444; --warning:#f59e0b; --shadow:0 4px 6px -1px rgba(0,0,0,0.1);
        }
        body{ margin:0; font-family:'Segoe UI', sans-serif; background:var(--bg); color:var(--text); font-size: 13px; }
        .container{padding:20px}
        .page-header{ display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; }
        .btn{ padding:8px 16px; border-radius:8px; font-size:12px; font-weight:600; text-decoration:none; display:inline-flex; align-items:center; gap:8px; border:none; cursor:pointer; color:#fff; }
        .btn-primary{background:var(--primary)}
        .btn-success{background:var(--success)}
        .btn-gray{background:#475569}
        .btn-print{background:#0891b2}

        .filter-card { background: var(--card); padding: 20px; border-radius: 12px; border: 1px solid var(--border); margin-bottom: 20px; box-shadow: var(--shadow); }
        .filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; }
        .filter-item label { font-size: 11px; font-weight: bold; color: var(--muted); margin-bottom: 5px; display: block; text-transform: uppercase; }
        
        .select2-container--default .select2-selection--single { height: 40px !important; border: 1px solid var(--border) !important; border-radius: 6px !important; }
        .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 38px !important; }

        .card{ background:var(--card); border-radius:12px; box-shadow:var(--shadow); border:1px solid var(--border); overflow:hidden; }
        table{width:100%; border-collapse:collapse; min-width: 1000px;}
        th{ background:#f1f5f9; padding:12px; font-size:11px; text-align: left; color:var(--muted); border-bottom: 2px solid var(--border); text-transform: uppercase; }
        td{ padding:15px 12px; border-bottom: 1px solid var(--border); vertical-align: top; }

        .info-label { font-size: 10px; color: var(--muted); font-weight: bold; text-transform: uppercase; display: block; margin-bottom: 2px; }
        .info-value { display: block; margin-bottom: 8px; }
        .route-path { font-weight: bold; color: #1e293b; display: flex; align-items: center; gap: 5px; }
        .date-item { display: flex; align-items: center; gap: 5px; margin-bottom: 4px; font-family: monospace; white-space: nowrap; }
        
        .money { font-weight: bold; color: #000; }
        .grand-total { color: var(--success); font-size: 14px; }
        
        .badge{ padding:3px 8px; border-radius:6px; font-size:10px; font-weight:700; text-transform: uppercase; }
        .badge-active{background:#dcfce7; color:#065f46}
        .badge-inactive{background:#fee2e2; color:#991b1b}
        
        .action-btns { display: flex; gap: 5px; flex-wrap: wrap; }
        .act-btn { width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 6px; color: #fff; text-decoration: none; font-size: 12px; }

        /* ==========================================================================
           تنسيقات الجوال (Responsive Design)
           ========================================================================== */

        @media (max-width: 992px) {
            .container { padding: 10px; }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .page-header div {
                width: 100%;
                flex-direction: column;
            }

            .btn { width: 100%; justify-content: center; }

            .filter-grid {
                grid-template-columns: 1fr;
            }

            table, thead, tbody, th, td, tr {
                display: block; 
                min-width: auto;
            }

            thead tr {
                display: none; 
            }

            .card { border: none; background: transparent; box-shadow: none; }

            tr {
                background: var(--card);
                margin-bottom: 15px;
                border-radius: 12px;
                border: 1px solid var(--border);
                box-shadow: var(--shadow);
                padding: 10px;
            }

            td {
                border-bottom: 1px solid #f1f5f9;
                position: relative;
                padding: 10px 10px 10px 45% !important; 
                min-height: 40px;
                text-align: right; 
            }

            td:last-child { border-bottom: none; }

            td::before {
                content: attr(data-label); 
                position: absolute;
                left: 10px;
                width: 40%;
                font-weight: bold;
                color: var(--muted);
                font-size: 10px;
                text-transform: uppercase;
                text-align: left;
                top: 15px;
            }

            .action-btns {
                justify-content: flex-end;
                gap: 10px;
                padding: 10px 0;
            }

            .act-btn {
                width: 40px;
                height: 40px;
                font-size: 16px;
            }

            .route-path {
                justify-content: flex-end;
            }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="page-header">
        <h2 style="margin:0">🚢 Detailed Logistics Management</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?= $print_url ?>" target="_blank" class="btn btn-print">
                <i class="fas fa-print"></i> View Print Version
            </a>
            <a href="dashboard.php" class="btn btn-gray"><i class="fas fa-arrow-left"></i> Back</a>
            <a href="shipment_add.php" class="btn btn-success"><i class="fas fa-plus"></i> New Shipment</a>
        </div>
    </div>

    <div class="filter-card">
        <form method="GET" id="filterForm">
            <div class="filter-grid">
                <div class="filter-item">
                    <label>B/L & Shipping Line</label>
                    <input type="text" name="f_bl" value="<?= htmlspecialchars($f_bl) ?>" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px;" placeholder="B/L or Line...">
                </div>
                
                <div class="filter-item">
                    <label>Agent (Searchable)</label>
                    <select name="f_agent" class="select-search">
                        <option value="">All Agents</option>
                        <?php foreach($all_agents as $ag): ?>
                            <option value="<?= $ag['agent_id'] ?>" <?= $f_agent == $ag['agent_id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($ag['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-item">
                    <label>Customer (Searchable)</label>
                    <select name="f_customer" class="select-search">
                        <option value="">All Customers</option>
                        <?php foreach($all_customers as $cust): ?>
                            <option value="<?= $cust['customer_id'] ?>" <?= $f_customer == $cust['customer_id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cust['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-item">
                    <label>Volume Type</label>
                    <select name="f_ct_type" class="select-search">
                        <option value="">All Types</option>
                        <?php foreach($container_types as $ct): ?>
                            <option value="<?= $ct['container_id'] ?>" <?= $f_ct_type == $ct['container_id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($ct['container_type']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-item">
                    <label>Booking From (من)</label>
                    <input type="date" name="f_date_from" value="<?= htmlspecialchars($f_date_from) ?>" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px;">
                </div>

                <div class="filter-item">
                    <label>Booking To (إلى)</label>
                    <input type="date" name="f_date_to" value="<?= htmlspecialchars($f_date_to) ?>" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px;">
                </div>

                <div class="filter-item">
                    <label>Status</label>
                    <select name="f_status" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px;">
                        <option value="">All Status</option>
                        <option value="Active" <?= $f_status == 'Active' ? 'selected' : '' ?>>Active</option>
                        <option value="Inactive" <?= $f_status == 'Inactive' ? 'selected' : '' ?>>Inactive</option>
                    </select>
                </div>
            </div>
            <button type="submit" class="btn btn-primary" style="margin-top:15px;"><i class="fas fa-filter"></i> Apply Filters</button>
            <a href="shipments.php" class="btn btn-gray" style="margin-top:15px; background:#94a3b8;"><i class="fas fa-redo"></i> Reset</a>
        </form>
    </div>

    <div class="card">
        <table>
            <thead>
                <tr>
                    <th>REF / B/L / AGENT / CUST</th>
                    <th>ROUTE & LINE</th>
                    <th>DATES (BOOKING/ETD/ETA)</th>
                    <th>CARGO & CONTAINER</th>
                    <th>FINANCIALS</th>
                    <th>USER & STATUS</th>
                    <th>ACTIONS</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($shipments as $s): 
                    $is_priced = (!empty($s['grand_total']) && $s['grand_total'] > 0);
                ?>
                <tr>
                    <td data-label="Shipment Info">
                        <span class="info-label">Shipment ID</span>
                        <strong class="info-value">#<?= $s['shipment_id']  ?></strong>
                        
                        <span class="info-label">Customer</span>
                        <span class="info-value" style="color:var(--success); font-weight:600;"><?= htmlspecialchars($s['customer_name'] ?: 'N/A') ?></span>

                        <span class="info-label">Agent/Client</span>
                        <span class="info-value" style="color:var(--primary); font-weight:600;"><?= htmlspecialchars($s['agent_name'] ?: 'N/A') ?></span>
                        
                        <span class="info-label">B/L Number</span>
                        <code style="color:var(--primary); font-weight:bold;"><?= htmlspecialchars($s['bill_of_lading'] ?: '---') ?></code>
                    </td>

                    <td data-label="Route & Line">
                        <span class="info-label">Route Path</span>
                        <div class="info-value route-path">
                            <?= htmlspecialchars($s['source_name']) ?> 
                            <i class="fas fa-arrow-right" style="font-size:10px; color:var(--primary)"></i> 
                            <?= htmlspecialchars($s['destination_name']) ?>
                        </div>

                        <span class="info-label">Shipping Line</span>
                        <div class="info-value"><i class="fas fa-ship"></i> <?= htmlspecialchars($s['shipping_line'] ?: 'Maersk Line') ?></div>
                        
                        <span class="info-label">Type</span>
                        <div class="info-value"><?= htmlspecialchars($s['shipment_type'] ?: 'Port to Port') ?></div>
                    </td>

                    <td data-label="Dates">
                        <div class="date-item">
                            <i class="fas fa-calendar-alt" style="color:var(--muted)"></i>
                            <span class="info-label" style="width: 60px; margin:0">BOOKING:</span>
                            <span><?= $s['booking_date'] ?></span>
                        </div>
                        <div class="date-item">
                            <i class="fas fa-plane-departure" style="color:var(--muted)"></i>
                            <span class="info-label" style="width: 60px; margin:0">ETD:</span>
                            <span><?= $s['departure_date'] ?: '---' ?></span>
                        </div>
                        <div class="date-item">
                            <i class="fas fa-plane-arrival" style="color:var(--muted)"></i>
                            <span class="info-label" style="width: 60px; margin:0">ETA:</span>
                            <span><?= $s['expected_arrival_date'] ?: '---' ?></span>
                        </div>
                    </td>

                    <td data-label="Cargo & Container">
                        <span class="info-label">Description</span>
                        <strong class="info-value"><?= htmlspecialchars($s['item_description'] ?: '---') ?></strong>

                        <span class="info-label">Container Type & Qty</span>
                        <div class="info-value">
                            <span class="badge" style="background:#e0e7ff; color:#3730a3"><?= htmlspecialchars($s['container_type_name']) ?></span>
                            <span class="badge" style="background:#fef3c7; color:#92400e">X<?= $s['container_count'] ?></span>
                        </div>
                    </td>

                    <td data-label="Financials">
                        <span class="info-label">Price / Unit</span>
                        <span class="info-value money"><?= number_format($s['price_per_container'], 2) ?></span>

                        <span class="info-label">Grand Total</span>
                        <span class="info-value money grand-total"><?= number_format($s['grand_total'], 2) ?></span>
                    </td>

                    <td data-label="In-Charge & Status">
                        <span class="info-label">In-Charge</span>
                        <div class="info-value"><i class="fas fa-user-circle"></i> <?= htmlspecialchars($s['employee_name'] ?: 'System') ?></div>
                        
                        <span class="badge <?= $s['status'] != 'Inactive' ? 'badge-active' : 'badge-inactive' ?>">
                            <?= $s['status'] ?>
                        </span>
                    </td>

                    <td data-label="Actions">
                        <div class="action-btns">
                            <a href="shipment_view.php?id=<?= $s['shipment_id'] ?>" class="act-btn" style="background:var(--primary)" title="View"><i class="fas fa-eye"></i></a>
                            <a href="shipment_edit.php?id=<?= $s['shipment_id'] ?>" class="act-btn" style="background:var(--warning)" title="Edit"><i class="fas fa-edit"></i></a>
                            <a href="shipment_pricing_add.php?id=<?= $s['shipment_id'] ?>" class="act-btn" style="background:var(--warning)" title="+"><i class="fas fa-edit"></i></a>

                            <?php if (!$is_priced): ?>
                                <a href="shipment_pricing.php?id=<?= $s['shipment_id'] ?>" class="act-btn" style="background:#8b5cf6" title="Financials"><i class="fas fa-file-invoice-dollar"></i></a>
                            <?php endif; ?>

                            <a href="shipment_delete.php?id=<?= $s['shipment_id'] ?>" class="act-btn" style="background:var(--danger)" title="Delete" onclick="return confirm('Are you sure?')"><i class="fas fa-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script src="../assets/js/jquery-3.6.0.min.js"></script>
<script src="../assets/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    $('.select-search').select2({
        placeholder: "Search and Select...",
        allowClear: true,
        width: '100%'
    });
});
</script>

</body>
</html>