<?php
session_start();
require_once("../config/config.php");

$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

function generateDCCode(mysqli $conn): string {
    $sql = "SELECT dc_code FROM delivery_challan ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['dc_code'], 3) + 1;
    }
    return sprintf("DC-%04d", $next);
}

$success = "";
$error = "";
$generated_code = generateDCCode($conn);

// Fetch Projects
$projects = $conn->query("
    SELECT id, project_code, project_name, project_address, gst_number 
    FROM project_master 
    WHERE project_status IN ('Active', 'In Progress') 
    ORDER BY project_name ASC
");

// Fetch Items for dropdown
$items_result = $conn->query("
    SELECT id, name, model_no, uom 
    FROM inventory_master 
    ORDER BY name ASC
");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $dc_code          = trim($_POST['dc_code'] ?? '');
    $dc_date          = $_POST['dc_date'] ?? date('Y-m-d');
    $project_id       = !empty($_POST['project_id']) ? (int)$_POST['project_id'] : null;
    $receiver_name    = trim($_POST['receiver_name'] ?? '');
    $receiver_mobile  = trim($_POST['receiver_mobile'] ?? '');
    $delivery_address = trim($_POST['delivery_address'] ?? '');
    $client_gst       = trim($_POST['client_gst_number'] ?? '');
    $vehicle_no       = trim($_POST['vehicle_no'] ?? '');
    $po_no            = trim($_POST['po_no'] ?? '');
    $po_date          = $_POST['po_date'] ?? null;
    $eway_bill_no     = trim($_POST['eway_bill_no'] ?? '');
    $remarks          = trim($_POST['remarks'] ?? '');

    $item_ids      = $_POST['item_id'] ?? [];
    $quantities    = $_POST['quantity'] ?? [];
    $rates         = $_POST['rate'] ?? [];
    $billing_types = $_POST['billing_type'] ?? [];
    $serial_nos    = $_POST['serial_no'] ?? [];

    if (empty($receiver_name) || empty($dc_date)) {
        $error = "Receiver Name and DC Date are required.";
    } elseif (empty($item_ids) || count(array_filter($quantities, fn($q) => (float)$q > 0)) === 0) {
        $error = "Please add at least one item with quantity > 0.";
    } else {
        try {
            $conn->begin_transaction();

            $dc_sql = "INSERT INTO delivery_challan 
                (dc_code, dc_date, project_id, receiver_name, receiver_mobile, delivery_address, 
                 client_gst_number, vehicle_no, po_no, po_date, eway_bill_no, remarks, issued_by, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Issued')";

            $dc_stmt = $conn->prepare($dc_sql);
            $dc_stmt->bind_param("ssisssssssssi", 
                $dc_code, $dc_date, $project_id, $receiver_name, $receiver_mobile,
                $delivery_address, $client_gst, $vehicle_no, $po_no, $po_date, 
                $eway_bill_no, $remarks, $user_id);
            $dc_stmt->execute();
            $dc_id = $conn->insert_id;

            $item_stmt = $conn->prepare("INSERT INTO delivery_challan_items 
                (dc_id, item_id, issued_qty, rate, unit, billing_type, serial_number) 
                VALUES (?, ?, ?, ?, ?, ?, ?)");

            $deduct_stmt = $conn->prepare("UPDATE inventory_master 
                SET current_stock = GREATEST(COALESCE(current_stock,0) - ?, 0) 
                WHERE id = ?");

            $serial_update_stmt = $conn->prepare("
                UPDATE inventory_serials 
                 SET status = 'Sold', issued_date = NOW() 
                WHERE inventory_id = ? 
                AND serial_number = ? 
                AND status = 'In Stock'
                ");

            foreach ($item_ids as $idx => $item_id) {
                $qty = isset($quantities[$idx]) ? (float)$quantities[$idx] : 0;
                if ($qty <= 0 || $item_id <= 0) continue;

                $rate    = isset($rates[$idx]) ? (float)$rates[$idx] : 0;
                $billing = isset($billing_types[$idx]) ? $billing_types[$idx] : 'Billable';
                $serial  = isset($serial_nos[$idx]) ? trim($serial_nos[$idx]) : '';

                $unit_q = $conn->prepare("SELECT uom FROM inventory_master WHERE id = ?");
                $unit_q->bind_param("i", $item_id);
                $unit_q->execute();
                $unit = $unit_q->get_result()->fetch_assoc()['uom'] ?? 'NOS';

                $item_stmt->bind_param("iidssss", $dc_id, $item_id, $qty, $rate, $unit, $billing, $serial);
                $item_stmt->execute();

                $deduct_stmt->bind_param("di", $qty, $item_id);
                $deduct_stmt->execute();
                 // 🔥 SERIAL LOGIC
                if (!empty($serial)) {

                // Update serial status
                $serial_update_stmt->bind_param("is", $item_id, $serial);
                $serial_update_stmt->execute();

                    // ❌ If no row updated → serial already used or invalid
                    if ($serial_update_stmt->affected_rows === 0) {
                    throw new Exception("Serial not available or already issued: $serial");
                    }
                }
            }

            $conn->commit();
            $success = "Delivery Challan <strong>$dc_code</strong> created successfully!";

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Delivery Challan</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
    :root {
        --primary: #a855f7;
        --accent: #c084fc;
        --glass: rgba(255, 255, 255, 0.09);
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', system-ui, sans-serif;
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.82), rgba(0, 0, 0, 0.95)), url('../background.jpeg') center/cover fixed;
        color: #f1f5f9;
        min-height: 100vh;
        padding: 20px;
    }

    .glass-container {
        background: var(--glass);
        backdrop-filter: blur(28px);
        border-radius: 28px;
        border: 1px solid rgba(255, 255, 255, 0.18);
        box-shadow: 0 30px 90px rgba(0, 0, 0, 0.7);
        overflow: hidden;
    }

    .header {
        background: linear-gradient(90deg, rgba(168, 85, 247, 0.4), rgba(147, 51, 234, 0.3));
        padding: 50px 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 20px;
    }

    .content {
        padding: 45px 40px;
    }

    .message {
        padding: 16px 24px;
        border-radius: 16px;
        margin-bottom: 30px;
        font-weight: 600;
    }

    .success {
        background: rgba(34, 197, 94, 0.25);
        border: 1px solid #4ade80;
        color: #86efac;
    }

    .error {
        background: rgba(239, 68, 68, 0.25);
        border: 1px solid #f87171;
        color: #fca5a5;
    }

    .form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 24px;
        margin-bottom: 40px;
    }

    label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #e0e7ff;
    }

    input,
    select,
    textarea {
        width: 100%;
        padding: 16px 20px;
        background: rgba(255, 255, 255, 0.09);
        border: 1px solid rgba(255, 255, 255, 0.25);
        border-radius: 16px;
        color: white;
    }

    input:focus,
    select:focus,
    textarea:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 4px rgba(168, 85, 247, 0.25);
    }
    option{
        color: black;
    }
    .items-table {
        width: 100%;
        border-collapse: collapse;
        background: rgba(255, 255, 255, 0.04);
        border-radius: 20px;
        overflow: hidden;
    }

    .items-table th {
        background: rgba(168, 85, 247, 0.35);
        padding: 18px;
        color: #e0e7ff;
        text-align: left;
    }

    .items-table td {
        padding: 14px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }

    .suggestions {
        position: absolute;
        z-index: 1000;
        background: #1f2937;
        border: 1px solid var(--primary);
        border-radius: 12px;
        max-height: 280px;
        overflow-y: auto;
        width: 100%;
        margin-top: 4px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.6);
    }

    .suggestion-item {
        padding: 12px 16px;
        cursor: pointer;
    }

    .suggestion-item:hover {
        background: rgba(168, 85, 247, 0.3);
    }

    .remove-row {
        color: #f87171;
        cursor: pointer;
        font-size: 1.5rem;
    }
    </style>
</head>

<body>

    <?php include '../config/header.php'; ?>

    <div class="container">
        <div class="glass-container">
            <div class="header">
                <div>
                    <a href="dc_list.php" style="color:#c4b5fd;text-decoration:none;">← Back to Delivery Challans</a>
                    <h1><i class="fas fa-truck"></i> Create New Delivery Challan</h1>
                </div>
            </div>

            <div class="content">
                <?php if ($success): ?><div class="message success"><?= $success ?></div><?php endif; ?>
                <?php if ($error): ?><div class="message error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

                <form method="POST">
                    <div class="form-grid">
                        <div><label>DC Code <span class="required">*</span></label><input type="text" name="dc_code"
                                value="<?= htmlspecialchars($generated_code) ?>" readonly></div>
                        <div><label>DC Date <span class="required">*</span></label><input type="date" name="dc_date"
                                value="<?= date('Y-m-d') ?>" required></div>
                        <div><label>Project <span class="required">*</span></label>
                            <select name="project_id" id="project_id" required onchange="autoFillProjectDetails()">
                                <option value="">-- Select Project --</option>
                                <?php while ($p = $projects->fetch_assoc()): ?>
                                <option value="<?= $p['id'] ?>"
                                    data-address="<?= htmlspecialchars($p['project_address']??'') ?>"
                                    data-gst="<?= htmlspecialchars($p['gst_number']??'') ?>">
                                    <?= htmlspecialchars($p['project_code']) ?> -
                                    <?= htmlspecialchars($p['project_name']) ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div><label>Delivery Address</label><input type="text" name="delivery_address"
                                id="delivery_address"></div>
                        <div><label>Client GST</label><input type="text" name="client_gst_number"
                                id="client_gst_number"></div>
                        <div><label>Receiver Name <span class="required">*</span></label><input type="text"
                                name="receiver_name" required></div>
                        <div><label>Receiver Mobile</label><input type="text" name="receiver_mobile"></div>
                        <div><label>Vehicle No.</label><input type="text" name="vehicle_no"></div>
                        <div><label>PO Number</label><input type="text" name="po_no"></div>
                        <div><label>PO Date</label><input type="date" name="po_date"></div>
                        <div><label>Eway Bill No.</label><input type="text" name="eway_bill_no"></div>
                    </div>

                    <h3 style="margin:30px 0 15px;color:#ddd6fe;"><i class="fas fa-boxes"></i> Items</h3>
                    <table class="items-table" id="itemsTable">
                        <thead>
                            <tr>
                                <th>Model No</th>
                                <th>Serial No</th>
                                <th>Item Name</th>
                                <th>Billing Type</th>
                                <th>Qty</th>
                                <th>Rate (₹)</th>
                                <th>Unit</th>
                                <th>Value (₹)</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody"></tbody>
                    </table>

                    <button type="button" onclick="addItemRow()"
                        style="margin:20px 0;padding:14px 32px;background:rgba(34,197,94,0.25);color:#86efac;border:1px solid #4ade80;border-radius:9999px;cursor:pointer;">
                        <i class="fas fa-plus"></i> Add Item
                    </button>

                    <div style="text-align:right;font-size:1.6rem;font-weight:700;margin:30px 0;">
                        Grand Total: <span id="grandTotal">₹ 0.00</span>
                    </div>

                    <div><label>Remarks</label><textarea name="remarks" rows="3"></textarea></div>

                    <button type="submit"
                        style="width:100%;padding:18px;background:linear-gradient(135deg,var(--primary),var(--accent));color:white;border:none;border-radius:9999px;font-size:1.2rem;font-weight:700;margin-top:20px;">
                        <i class="fas fa-truck"></i> Create Delivery Challan
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script>
    // Auto fill project
    function autoFillProjectDetails() {
        const sel = document.getElementById('project_id');
        const opt = sel.options[sel.selectedIndex];
        if (opt) {
            document.getElementById('delivery_address').value = opt.dataset.address || '';
            document.getElementById('client_gst_number').value = opt.dataset.gst || '';
        }
    }

    function addItemRow() {
        const tbody = document.getElementById('itemsBody');
        const row = tbody.insertRow();
        row.innerHTML = `
        <td>
            <input type="text" name="model_no[]" placeholder="Model No" onkeyup="searchByModel(this)">
            <div class="suggestions" style="display:none;"></div>
        </td>
        <td id="serial-cell">
            <select name="serial_no[]" style="width:100%;">
                <option value="">-- Select Serial --</option>
            </select>
        </td>
        <td>
            <select name="item_id[]" onchange="updateUnit(this)" required>
                <option value="">Select Item</option>
                <?php while ($item = $items_result->fetch_assoc()): ?>
                    <option value="<?= $item['id'] ?>" data-unit="<?= htmlspecialchars($item['uom']) ?>">
                        <?= htmlspecialchars($item['name']) ?> (<?= htmlspecialchars($item['model_no'] ?? '') ?>)
                    </option>
                <?php endwhile; ?>
            </select>
        </td>
        <td><select name="billing_type[]"><option value="Billable">Billable</option><option value="Non-Billable">Non-Billable</option></select></td>
        <td><input type="number" name="quantity[]" step="0.001" oninput="calcTotal(this)" required></td>
        <td><input type="number" name="rate[]" step="0.01" oninput="calcTotal(this)"></td>
        <td class="unit-cell">—</td>
        <td class="line-total">₹ 0.00</td>
        <td><span class="remove-row" onclick="this.closest('tr').remove();updateGrandTotal()">×</span></td>
    `;
    }

    function searchByModel(input) {
        const query = input.value.trim();
        const row = input.closest('tr');
        const sug = row.querySelector('.suggestions');

        if (query.length < 2) {
            sug.style.display = 'none';
            return;
        }

        fetch(`search_inventory.php?type=model&query=${encodeURIComponent(query)}`)
            .then(r => r.json())
            .then(data => {
                sug.innerHTML = '';
                if (data.success) {
                    data.items.forEach(item => {
                        const d = document.createElement('div');
                        d.className = 'suggestion-item';
                        d.innerHTML = `<strong>${item.model_no}</strong> — ${item.name}`;
                        d.onclick = () => {
                            selectModelItem(row, item);
                            sug.style.display = 'none';
                        };
                        sug.appendChild(d);
                    });
                    sug.style.display = 'block';
                }
            });
    }

    function selectModelItem(row, item) {
        row.querySelector('input[name="model_no[]"]').value = item.model_no;
        row.querySelector('select[name="item_id[]"]').value = item.id;
        row.querySelector('select[name="item_id[]"]').dispatchEvent(new Event('change'));

        loadSerialDropdown(row, item.id);
    }

    function loadSerialDropdown(row, itemId) {
        const serialCell = row.querySelector('#serial-cell');

        fetch(`search_inventory.php?type=serials_by_item&item_id=${itemId}`)
            .then(r => r.json())
            .then(data => {
                if (data.success && data.serials && data.serials.length > 0) {
                    let html = `<select name="serial_no[]" style="width:100%;">`;
                    html += `<option value="">-- Select Serial --</option>`;
                    data.serials.forEach(s => {
                        html += `<option value="${s}">${s}</option>`;
                    });
                    html += `</select>`;
                    serialCell.innerHTML = html;
                } else {
                    serialCell.innerHTML = `<input type="text" name="serial_no[]" placeholder="Enter Serial No">`;
                }
            });
    }

    function searchBySerial(input) {
        const query = input.value.trim();
        const row = input.closest('tr');
        const sug = row.querySelectorAll('.suggestions')[1];

        if (query.length < 2) {
            sug.style.display = 'none';
            return;
        }

        fetch(`search_inventory.php?type=serial&query=${encodeURIComponent(query)}`)
            .then(r => r.json())
            .then(data => {
                sug.innerHTML = '';
                if (data.success) {
                    data.items.forEach(item => {
                        const d = document.createElement('div');
                        d.className = 'suggestion-item';
                        d.innerHTML = `<strong>${item.serial_number}</strong> — ${item.name}`;
                        d.onclick = () => {
                            input.value = item.serial_number;
                            sug.style.display = 'none';
                        };
                        sug.appendChild(d);
                    });
                    sug.style.display = 'block';
                }
            });
    }

    function updateUnit(select) {
        const row = select.closest('tr');
        row.querySelector('.unit-cell').textContent = select.options[select.selectedIndex].dataset.unit || '—';
    }

    function calcTotal(el) {
        const row = el.closest('tr');
        const qty = parseFloat(row.querySelector('input[name="quantity[]"]').value) || 0;
        const rate = parseFloat(row.querySelector('input[name="rate[]"]').value) || 0;
        row.querySelector('.line-total').textContent = `₹ ${(qty*rate).toFixed(2)}`;
        updateGrandTotal();
    }

    function updateGrandTotal() {
        let total = 0;
        document.querySelectorAll('.line-total').forEach(td => {
            total += parseFloat(td.textContent.replace('₹ ', '')) || 0;
        });
        document.getElementById('grandTotal').textContent = `₹ ${total.toFixed(2)}`;
    }

    window.onload = () => addItemRow();
    </script>
</body>

</html>

<?php $conn->close(); ?>