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


$id = (int)($_GET['id'] ?? 0);

/* ================= جلب بيانات الشحنة الحالية ================= */
$stmt = $pdo->prepare("SELECT * FROM newshipments WHERE shipment_id = ?");
$stmt->execute([$id]);
$shipment = $stmt->fetch();

if (!$shipment) {
    die("Shipment not found!");
}

/* ================= جلب القوائم المنسدلة ================= */
$customers       = $pdo->query("SELECT customer_id, name FROM customers WHERE status='active'")->fetchAll();
$agents          = $pdo->query("SELECT agent_id, name FROM agents WHERE status='active'")->fetchAll();
$hubs            = $pdo->query("SELECT hub_id, hub_name FROM transport_hubs")->fetchAll();
$container_types = $pdo->query("SELECT container_id, container_type FROM container_types WHERE status='active'")->fetchAll();
$shipping_lines  = $pdo->query("SELECT line_name FROM shipping_lines WHERE status='active'")->fetchAll();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $customer_id = (int)($_POST['customer_id'] ?? 0);
        $agent_id    = (int)($_POST['agent_id'] ?? 0);
        
        // منطق اختيار شركة الشحن
        $line_src   = $_POST['line_src'] ?? 'list';
        $final_line = ($line_src === 'manual') 
            ? trim($_POST['line_manual'] ?? '') 
            : ($_POST['line_id'] ?? '');

        /* ========= تحديث البيانات التشغيلية فقط ========= */
        $sql = "UPDATE newshipments SET 
                booking_date = ?, order_type = ?, departure_date = ?, expected_arrival_date = ?,
                customer_id = ?, agent_id = ?, source_hub_id = ?, destination_hub_id = ?,
                container_type_id = ?, shipment_type = ?, factory_address = ?, shipping_line = ?,
                bill_of_lading = ?, item_description = ?, shipment_details = ?
                WHERE shipment_id = ?";

        $pdo->prepare($sql)->execute([
            $_POST['booking_date'],
            $_POST['order_type'],
            $_POST['departure_date'] ?: null,
            $_POST['expected_arrival_date'] ?: null,
            $customer_id,
            $agent_id,
            (int)$_POST['source_hub_id'],
            (int)$_POST['destination_hub_id'],
            (int)$_POST['container_type_id'],
            $_POST['shipment_type'],
            $_POST['factory_address'],
            $final_line,
            $_POST['bill_of_lading'],
            $_POST['item_description'],
            $_POST['shipment_details'],
                        $id
        ]);

        $success = "تم تحديث بيانات الشحنة بنجاح";
        // إعادة جلب البيانات المحدثة للعرض
        $stmt->execute([$id]);
        $shipment = $stmt->fetch();

    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TMS | Edit Shipment</title>
    <link rel="stylesheet" href="../assets/css/select2.min.css">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <style>
        :root {
            --bg-body: #f1f5f9; --sidebar: #0f172a; --accent: #2563eb;
            --border: #e2e8f0; --text-primary: #1e293b;
        }
        body { font-family: 'Inter', sans-serif; background: var(--bg-body); color: var(--text-primary); margin: 0; display: flex; height: 100vh; }
        .sidebar { width: 220px; background: var(--sidebar); color: #fff; padding: 20px; flex-shrink: 0; }
        .main-pane { flex: 1; overflow-y: auto; padding: 30px; }
        .system-card { background: #fff; border-radius: 12px; border: 1px solid var(--border); box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); }
        .card-header { padding: 20px 30px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
        
        .form-grid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 20px; padding: 30px; }
        .col-3 { grid-column: span 3; } .col-4 { grid-column: span 4; } .col-6 { grid-column: span 6; } .col-12 { grid-column: span 12; }
        
        .section-label { grid-column: span 12; font-size: 0.75rem; font-weight: 800; text-transform: uppercase; color: var(--accent); border-bottom: 1px solid var(--border); padding-bottom: 5px; margin-top: 15px; }
        label { display: block; font-size: 0.75rem; font-weight: 600; margin-bottom: 6px; color: #64748b; }
        input, select { width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; box-sizing: border-box; }
        
        /* التنسيق الخاص بأزرار الاختيار Type Switcher */
        .type-switcher { display: flex; background: #f1f5f9; padding: 4px; border-radius: 8px; border: 1px solid var(--border); }
        .type-switcher input { display: none; }
        .type-switcher label { flex: 1; text-align: center; padding: 6px 10px; font-size: 0.8rem; font-weight: 600; cursor: pointer; border-radius: 6px; transition: 0.2s; }
        .type-switcher input:checked + label { background: #fff; color: var(--accent); box-shadow: 0 2px 4px rgba(0,0,0,0.05); }

        .footer-action { padding: 25px 30px; background: #f8fafc; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; border-radius: 0 0 12px 12px; }
        .btn { padding: 12px 25px; border-radius: 8px; font-weight: 700; cursor: pointer; border: none; font-size: 0.9rem; display: inline-flex; align-items: center; gap: 8px; }
        .btn-submit { background: var(--accent); color: #fff; }
        .alert { margin: 20px 30px; padding: 15px; border-radius: 8px; font-size: 0.85rem; }
        .alert-success { background: #dcfce7; color: #15803d; }
        .alert-error { background: #fee2e2; color: #b91c1c; }
    </style>
</head>
<body>

<aside class="sidebar">
    <div style="font-size: 1.4rem; font-weight: 800; margin-bottom: 40px;">TMS<span style="color:var(--accent);">PRO</span></div>
    <div style="font-size: 0.7rem; opacity: 0.5; text-transform: uppercase;">Operation Edit</div>
</aside>

<main class="main-pane">
    <div class="system-card">
        <div class="card-header">
            <h2 style="margin:0; font-size:1.1rem;">تعديل بيانات الشحنة #<?= $id ?></h2>
            <a href="shipments.php" style="text-decoration:none; color:#64748b; font-size:0.8rem;"><i class="fas fa-arrow-left"></i> Back to List</a>
        </div>

        <?php if($success): ?> <div class="alert alert-success"><?= $success ?></div> <?php endif; ?>
        <?php if($error): ?> <div class="alert alert-error"><?= $error ?></div> <?php endif; ?>

        <form method="POST">
            <div class="form-grid">
                <div class="section-label">General Information</div>
                <div class="col-4">
                    <label>Bill of Lading (B/L)</label>
                    <input type="text" name="bill_of_lading" value="<?= htmlspecialchars($shipment['bill_of_lading']) ?>" required>
                </div>
                <div class="col-4">
                    <label>Booking Date</label>
                    <input type="date" name="booking_date" value="<?= $shipment['booking_date'] ?>">
                </div>
                <div class="col-4">
                    <label> Order Type</label>
                    <input type="text" name="order_type" value="<?= htmlspecialchars($shipment['order_type']) ?>">
                </div>
                
                <div class="col-6">
                    <label>Customer</label>
                    <select name="customer_id" class="select2">
                        <?php foreach($customers as $c): ?> 
                            <option value="<?= $c['customer_id'] ?>" <?= $shipment['customer_id'] == $c['customer_id'] ? 'selected' : '' ?>>
                                <?= $c['name'] ?>
                            </option> 
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-6">
                    <label>Agent</label>
                    <select name="agent_id" class="select2">
                        <?php foreach($agents as $a): ?> 
                            <option value="<?= $a['agent_id'] ?>" <?= $shipment['agent_id'] == $a['agent_id'] ? 'selected' : '' ?>>
                                <?= $a['name'] ?>
                            </option> 
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="section-label">Carrier & Route</div>
                <div class="col-4">
                    <label>Carrier Entry Method</label>
                    <div class="type-switcher">
                        <input type="radio" name="line_src" id="l_list" value="list" checked onchange="toggleLine(false)">
                        <label for="l_list">From List</label>
                        <input type="radio" name="line_src" id="l_man" value="manual" onchange="toggleLine(true)">
                        <label for="l_man">Manual Entry</label>
                    </div>
                </div>

                <div class="col-4">
                    <label>Shipping Line</label>
                    <div id="div_list">
                        <select name="line_id" class="select2">
                            <?php foreach($shipping_lines as $l): ?> 
                                <option value="<?= $l['line_name'] ?>" <?= $shipment['shipping_line'] == $l['line_name'] ? 'selected' : '' ?>>
                                    <?= $l['line_name'] ?>
                                </option> 
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div id="div_man" style="display:none;">
                        <input type="text" name="line_manual" placeholder="Type line name..." value="<?= htmlspecialchars($shipment['shipping_line']) ?>">
                    </div>
                </div>

                <div class="col-4">
                    <label>Shipment Type</label>
                    <div class="type-switcher">
                        <input type="radio" name="shipment_type" id="p2p" value="Port to Port" <?= $shipment['shipment_type'] == 'Port to Port' ? 'checked' : '' ?> onchange="toggleFact(false)">
                        <label for="p2p">Port-to-Port</label>
                        <input type="radio" name="shipment_type" id="f2p" value="Factory to Port" <?= $shipment['shipment_type'] == 'Factory to Port' ? 'checked' : '' ?> onchange="toggleFact(true)">
                        <label for="f2p">Ex-Works</label>
                    </div>
                </div>

                <div class="col-12" id="fact_div" style="<?= $shipment['shipment_type'] == 'Factory to Port' ? '' : 'display:none;' ?> background:#f8fafc; padding:15px; border-radius:8px; border:1px dashed #cbd5e1;">
                    <label>Factory Address</label>
                    <input type="text" name="factory_address" value="<?= htmlspecialchars($shipment['factory_address']) ?>">
                </div>

                <div class="col-3">
                    <label>Departure Date (ETD)</label>
                    <input type="date" name="departure_date" value="<?= $shipment['departure_date'] ?>">
                </div>
                <div class="col-3">
                    <label>Arrival Date (ETA)</label>
                    <input type="date" name="expected_arrival_date" value="<?= $shipment['expected_arrival_date'] ?>">
                </div>
                <div class="col-3">
                    <label>Port of Loading</label>
                    <select name="source_hub_id" class="select2">
                        <?php foreach($hubs as $h): ?> 
                            <option value="<?= $h['hub_id'] ?>" <?= $shipment['source_hub_id'] == $h['hub_id'] ? 'selected' : '' ?>>
                                <?= $h['hub_name'] ?>
                            </option> 
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-3">
                    <label>Port of Discharge</label>
                    <select name="destination_hub_id" class="select2">
                        <?php foreach($hubs as $h): ?> 
                            <option value="<?= $h['hub_id'] ?>" <?= $shipment['destination_hub_id'] == $h['hub_id'] ? 'selected' : '' ?>>
                                <?= $h['hub_name'] ?>
                            </option> 
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="section-label">Cargo & VOLUMES</div>
                <div class="col-6">
                    <label>VOLUMES</label>
                    <select name="container_type_id" class="select2">
                        <?php foreach($container_types as $ct): ?> 
                            <option value="<?= $ct['container_id'] ?>" <?= $shipment['container_type_id'] == $ct['container_id'] ? 'selected' : '' ?>>
                                <?= $ct['container_type'] ?>
                            </option> 
                        <?php endforeach; ?>
                    </select>
                </div>
            

                <div class="col-6">
                    <label>Item Description</label>
                    <input type="text" name="item_description" value="<?= htmlspecialchars($shipment['item_description']) ?>">
                </div>
                <div class="col-6">
                    <label>Handling Details</label>
                    <input type="text" name="shipment_details" value="<?= htmlspecialchars($shipment['shipment_details']) ?>">
                </div>
            </div>

            <div class="footer-action">
                <button type="submit" class="btn btn-submit">
                    <i class="fas fa-save"></i> Save Changes
                </button>
            </div>
        </form>
    </div>
</main>

<script src="../assets/js/jquery-3.6.0.min.js"></script>
<script src="../assets/js/select2.min.js"></script>
<script>
$(document).ready(function() { 
    $('.select2').select2({ width: '100%' }); 
});

function toggleFact(show) { show ? $('#fact_div').fadeIn() : $('#fact_div').hide(); }

function toggleLine(man) {
    if(man) {
        $('#div_list').hide();
        $('#div_man').fadeIn();
    } else {
        $('#div_list').fadeIn();
        $('#div_man').hide();
    }
}
</script>
</body>
</html>