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


/* ================= جلب البيانات الأساسية (بدون العملات) ================= */
$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 = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // نستخدم Transaction لضمان سلامة البيانات رغم أنها عملية إدخال واحدة حالياً
    $pdo->beginTransaction();

    try {
        /* ========= المدخلات الآمنة ========= */
        $customer_id = (int)($_POST['customer_id'] ?? 0);
        $agent_id    = (int)($_POST['agent_id'] ?? 0);
        $today       = date('Y-m-d');

        $line_src   = $_POST['line_src'] ?? 'list';
        $final_line = ($line_src === 'manual')
            ? trim($_POST['line_manual'] ?? '')
            : ($_POST['line_id'] ?? '');

        /* ========= إدخال الشحنة (بدون مبالغ وبحالة معلقة للتسعير) ========= */
        $stmt = $pdo->prepare("
            INSERT INTO newshipments
            (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,
             container_count, status, pricing_status)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'Active','pending')
        ");

        $stmt->execute([
            $_POST['booking_date'] ?: $today,
            $_POST['order_type'] ?? '',
            ($_POST['departure_date'] ?? '') ?: null,
            ($_POST['expected_arrival_date'] ?? '') ?: null,
            $customer_id,
            $agent_id,
            (int)($_POST['source_hub_id'] ?? 0),
            (int)($_POST['destination_hub_id'] ?? 0),
            (int)($_POST['container_type_id'] ?? 0),
            $_POST['shipment_type'] ?? 'Port to Port',
            $_POST['factory_address'] ?? '',
            $final_line,
            $_POST['bill_of_lading'] ?? '',
            $_POST['item_description'] ?? '',
            $_POST['shipment_details'] ?? '',
            (int)($_POST['container_count'] ?? 1)
        ]);

        $pdo->commit();
        header("Location: shipments.php?added=1&msg=forwarded_to_finance");
        exit;

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TMS | New Shipment Entry</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', system-ui, 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; }
        
        .type-switcher { display: flex; background: #f1f5f9; padding: 4px; border-radius: 8px; border: 1px solid var(--border); }
        .type-switcher input { display: none; }
        .type-switcher label { padding: 6px 15px; font-size: 0.85rem; font-weight: 600; cursor: pointer; border-radius: 6px; }
        .type-switcher input:checked + label { background: #fff; color: var(--accent); box-shadow: 0 2px 4px rgba(0,0,0,0.05); }

        .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, textarea { width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; box-sizing: border-box; }
        
        .footer-action { padding: 25px 30px; background: #f8fafc; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; align-items: center; border-radius: 0 0 12px 12px; }
        
        .btn { padding: 12px 25px; border-radius: 8px; font-weight: 700; cursor: pointer; transition: 0.2s; border: none; text-decoration: none; font-size: 0.9rem; display: inline-flex; align-items: center; gap: 8px; }
        .btn-submit { background: var(--accent); color: #fff; }
        .btn-undo { background: #e2e8f0; color: #475569; margin-right: 10px; }
        .btn-back { background: transparent; color: #64748b; border: 1px solid var(--border); padding: 8px 15px; }
        .btn:hover { opacity: 0.9; transform: translateY(-1px); }
    </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;">Operations Dept</div>
</aside>

<main class="main-pane">
    <div class="system-card">
        <div class="card-header">
            <div style="display: flex; align-items: center; gap: 15px;">
                <a href="shipments.php" class="btn btn-back"><i class="fas fa-arrow-left"></i> Back</a>
                <h2 style="margin:0; font-size:1.1rem;">Shipment Entry (Data Only)</h2>
            </div>
            <div class="type-switcher">
                <input type="radio" name="display_status" id="s_active" checked>
                <label for="s_active">Operation Mode</label>
            </div>
        </div>

        <?php if($error): ?>
            <div style="margin: 20px 30px; padding: 15px; background: #fee2e2; color: #b91c1c; border-radius: 8px; font-size: 0.85rem;">
                <i class="fas fa-exclamation-circle me-2"></i> <?= $error ?>
            </div>
        <?php endif; ?>

        <form method="POST" id="shipmentForm">
            <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" placeholder="B/L Number" required>
                </div>
                <div class="col-4">
                    <label>Booking Date</label>
                    <input type="date" name="booking_date" value="<?= date('Y-m-d') ?>">
                </div>
                <div class="col-4">
                    <label>Order Type </label>
                    <input type="text" name="order_type" placeholder="e.g. Export 40HQ">
                </div>
                
                <div class="col-6">
                    <label>Customer</label>
                    <select name="customer_id" class="select2" required>
                        <option value="">Select Customer</option>
                        <?php foreach($customers as $c): ?> <option value="<?= $c['customer_id'] ?>"><?= $c['name'] ?></option> <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-6">
                    <label>Agent</label>
                    <select name="agent_id" class="select2" required>
                        <option value="">Select Agent</option>
                        <?php foreach($agents as $a): ?> <option value="<?= $a['agent_id'] ?>"><?= $a['name'] ?></option> <?php endforeach; ?>
                    </select>
                </div>

                <div class="section-label">Route & Carriers</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" checked onchange="toggleFact(false)">
                        <label for="p2p">Port-to-Port</label>
                        <input type="radio" name="shipment_type" id="f2p" value="Factory to Port" onchange="toggleFact(true)">
                        <label for="f2p">Ex-Works</label>
                    </div>
                </div>
                <div class="col-4">
                    <label>Carrier Entry</label>
                    <div class="type-switcher">
                        <input type="radio" name="line_src" id="l_list" value="list" checked onchange="toggleLine(false)">
                        <label for="l_list">List</label>
                        <input type="radio" name="line_src" id="l_man" value="manual" onchange="toggleLine(true)">
                        <label for="l_man">Manual</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'] ?>"><?= $l['line_name'] ?></option> <?php endforeach; ?>
                        </select>
                    </div>
                    <div id="div_man" style="display:none;">
                        <input type="text" name="line_manual" placeholder="Enter Line Name">
                    </div>
                </div>

                <div class="col-12" id="fact_div" style="display:none; background:#f8fafc; padding:15px; border-radius:8px; border:1px dashed #cbd5e1;">
                    <label>Factory Address</label>
                    <input type="text" name="factory_address" placeholder="Full Loading Address">
                </div>

                <div class="col-3">
                    <label>Departure Date (ETD)</label>
                    <input type="date" name="departure_date">
                </div>
                <div class="col-3">
                    <label>Arrival Date (ETA)</label>
                    <input type="date" name="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'] ?>"><?= $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'] ?>"><?= $h['hub_name'] ?></option> <?php endforeach; ?>
                    </select>
                </div>

                <div class="section-label">Cargo Details</div>
                <div class="col-6">
                    <label>Item Description</label>
                    <input type="text" name="item_description" placeholder="Goods Description">
                </div>
                <div class="col-6">
                    <label>Handling Details</label>
                    <input type="text" name="shipment_details" placeholder="Special Instructions">
                </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'] ?>"><?= $ct['container_type'] ?></option> <?php endforeach; ?>
                    </select>
                </div>
               
            </div>

            <div class="footer-action">
                <button type="reset" class="btn btn-undo" onclick="return confirm('Clear all inputs?')">
                    <i class="fas fa-undo"></i> Clear Form
                </button>
                <button type="submit" class="btn btn-submit">
                    <i class="fas fa-arrow-right"></i> Save & Send to Finance
                </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').show(); }
    else { $('#div_list').show(); $('#div_man').hide(); }
}
</script>
</body>
</html>