<?php
/* ================= Session & Security ================= */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

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

// Permissions Check
if (!can('price_offers','add')) {
    die('Access Denied');
}

// Enable Exception Mode for PDO
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/* ================= Fetch Data for Dropdowns ================= */
$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();
$currencies      = $pdo->query("SELECT currency_id, currency_name FROM currencies")->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 = '';

/* ================= Handle Form Submission ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Prepare Numerical Data
        $customer_id     = (int)($_POST['customer_id'] ?? 0);
        $agent_id        = (int)($_POST['agent_id'] ?? 0);
        $user_id         = (int)($_SESSION['user_id'] ?? 0);
        $container_count = (int)($_POST['container_count'] ?? 1);
        $rate            = (float)($_POST['price_per_container'] ?? 0);
        $agent_cost      = (float)($_POST['agent_cost'] ?? 0);
        $grand_total     = $container_count * $rate;

        // Determine Shipping Line (List or Manual)
        $line_src   = $_POST['line_src'] ?? 'list';
        $final_line = ($line_src === 'manual') 
                      ? trim($_POST['line_manual'] ?? '') 
                      : ($_POST['line_id'] ?? '');

        // Insert Query - Using Backticks for SQL keywords safety
        $sql = "INSERT INTO price_offers 
                (`offer_date`, `booking_date`, `order_type`, `expected_departure_date`, `expected_arrival_date`, 
                 `customer_id`, `agent_id`, `currency_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`, `price_per_container`, `agent_cost`, 
                 `grand_total`, `status`, `created_by`) 
                VALUES 
                (CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?)";

        $stmt = $pdo->prepare($sql);
        
        $stmt->execute([
            ($_POST['booking_date'] ?: null),
            ($_POST['order_type'] ?? ''),
            ($_POST['departure_date'] ?: null),
            ($_POST['expected_arrival_date'] ?: null),
            $customer_id,
            $agent_id,
            (int)($_POST['currency_id'] ?? 0),
            (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'] ?: null),
            ($_POST['item_description'] ?? ''),
            ($_POST['shipment_details'] ?? ''),
            $container_count,
            $rate,
            $agent_cost,
            $grand_total,
            $user_id
        ]);

        header("Location: price_offers.php?added=1");
        exit;

    } catch (PDOException $e) {
        $error = "Database Error: " . $e->getMessage();
    } catch (Exception $e) {
        $error = "General Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <title>TMS | Add Price Offer</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; }
        body { font-family: system-ui, -apple-system, sans-serif; background: var(--bg-body); margin: 0; display: flex; height: 100vh; }
        .sidebar { width: 220px; background: var(--sidebar); color: #fff; padding: 20px; }
        .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 / .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-2 { grid-column: span 2; } .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: .8rem; font-weight: 800; color: var(--accent); border-bottom: 1px solid var(--border); padding-bottom: 5px; text-transform: uppercase; letter-spacing: 0.5px; }
        label { font-size: .75rem; font-weight: 600; color: #64748b; margin-bottom: 5px; display: block; }
        input, select, textarea { width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 8px; font-size: .9rem; box-sizing: border-box; }
        .footer-action { padding: 25px 30px; background: #f8fafc; border-top: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
        .btn { padding: 12px 25px; border-radius: 8px; font-weight: 700; border: none; cursor: pointer; text-decoration: none; }
        .btn-submit { background: var(--accent); color: #fff; }
        .btn-back { background: #fff; border: 1px solid var(--border); color: #1e293b; }
        .type-switcher { display: flex; background: #f1f5f9; padding: 4px; border-radius: 8px; border: 1px solid var(--border); width: fit-content; }
        .type-switcher input { display: none; }
        .type-switcher label { padding: 6px 15px; font-size: .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); }
        .error-banner { background: #fee2e2; border: 1px solid #f87171; color: #b91c1c; padding: 15px; margin: 0 30px 20px; border-radius: 8px; }
    </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:.7rem;opacity:.5;text-transform:uppercase;">Price Offers Entry</div>
</aside>

<main class="main-pane">
    <?php if ($error): ?>
        <div class="error-banner"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div>
    <?php endif; ?>

    <div class="system-card">
        <div class="card-header">
            <div style="display:flex;gap:15px;align-items:center">
                <a href="price_offers.php" class="btn btn-back"><i class="fas fa-arrow-left"></i> Back</a>
                <h2 style="margin:0;font-size:1.1rem;">Add Price Offer</h2>
            </div>
        </div>

        <form method="POST" id="offerForm">
            <div class="form-grid">
                <div class="section-label">General Information</div>
                
                <div class="col-4">
                    <label>B/L Number (Optional)</label>
                    <input name="bill_of_lading" placeholder="Bill of Lading">
                </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 name="order_type" placeholder="e.g. Import / Export">
                </div>

                <div class="col-6">
                    <label>Customer</label>
                    <select name="customer_id" class="select2">
                        <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">
                        <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">Shipment Details</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">From 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 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 name="factory_address" placeholder="Enter pickup address">
                </div>

                <div class="col-3"><label>ETD (Departure)</label><input type="date" name="departure_date"></div>
                <div class="col-3"><label>ETA (Arrival)</label><input type="date" name="expected_arrival_date"></div>

                <div class="col-3">
                    <label>POL (Loading Port)</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>POD (Discharge Port)</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">Financial & Cargo Data</div>

                <div class="col-6">
                    <label>Item Description</label>
                    <input name="item_description" placeholder="Cargo description">
                </div>
                <div class="col-6">
                    <label>Handling / Offer Details</label>
                    <input name="shipment_details" placeholder="Additional details">
                </div>

                <div class="col-3">
                    <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 class="col-2">
                    <label>Qty</label>
                    <input type="number" id="qty" name="container_count" value="1" oninput="calc()">
                </div>
                <div class="col-2">
                    <label>Rate Per Container</label>
                    <input type="number" id="rate" name="price_per_container" value="0" step="0.01" oninput="calc()">
                </div>
                <div class="col-2">
                    <label>Agent Cost</label>
                    <input type="number" name="agent_cost" value="0" step="0.01">
                </div>
                <div class="col-3">
                    <label>Currency</label>
                    <select name="currency_id" id="curr" onchange="calc()">
                        <?php foreach($currencies as $cr): ?>
                            <option value="<?= $cr['currency_id'] ?>"><?= $cr['currency_name'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="footer-action">
                <div class="total-display">
                    <span style="font-size:.75rem; color:#64748b">Estimated Total</span>
                    <h2 id="total_ui" style="margin:0; color:#059669">0.00</h2>
                    <div id="curr_ui" style="font-weight:700; color:var(--accent)">---</div>
                </div>
                <button type="submit" class="btn btn-submit">
                    <i class="fas fa-check-circle"></i> Save Price Offer
                </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%'});
    calc(); 
});

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

function toggleLine(m){
    if(m){
        $('#div_list').hide(); $('#div_man').show();
    } else {
        $('#div_list').show(); $('#div_man').hide();
    }
}

function calc(){
    const q = parseFloat($('#qty').val()) || 0;
    const r = parseFloat($('#rate').val()) || 0;
    const t = q * r;
    $('#total_ui').text(t.toLocaleString('en-US', {minimumFractionDigits:2}));
    $('#curr_ui').text($('#curr option:selected').text());
}
</script>

</body>
</html>