<?php
require 'db.php';

// --- AJAX HANDLER: ADD NEW MATERIAL ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action']) && $_POST['ajax_action'] === 'add_material') {
    header('Content-Type: application/json');
    try {
        $name = trim($_POST['name'] ?? '');
        $unit = $_POST['unit_type'] ?? 'ea';
        $inv  = trim($_POST['inventory_number'] ?? '');
        if (!$name) throw new Exception("Material name is required.");
        $stmt = $pdo->prepare("INSERT INTO materials (name, unit_type, inventory_number) VALUES (?, ?, ?)");
        $stmt->execute([$name, $unit, $inv]);
        $new_id = $pdo->lastInsertId();
        echo json_encode(['success' => true, 'id' => $new_id, 'name' => $name, 'unit_type' => $unit, 'inventory_number' => $inv]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
// ---------------------------------------

// --- AJAX HANDLER: ADD NEW CUSTOMER ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action']) && $_POST['ajax_action'] === 'add_customer') {
    header('Content-Type: application/json');
    try {
        $name = trim($_POST['name'] ?? '');
        $loc_id = $_POST['location_id'] ?? null;
        if (!$name || !$loc_id) throw new Exception("Name and Location are required.");
        
        $stmt = $pdo->prepare("INSERT INTO customers (name, location_id) VALUES (?, ?)");
        $stmt->execute([$name, $loc_id]);
        $new_id = $pdo->lastInsertId();
        
        $stmtLoc = $pdo->prepare("SELECT name FROM locations WHERE id = ?");
        $stmtLoc->execute([$loc_id]);
        $loc_name = $stmtLoc->fetchColumn();
        
        echo json_encode(['success' => true, 'id' => $new_id, 'name' => $name, 'location_name' => $loc_name]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
// --------------------------------------

require_once 'helpers.php';

// 1. Fetch Data
$customers = [];
$materials = [];
$kits = [];
$locations = [];
$networks = [];
$kitJson = '[]';
$custPlantJson = '{}';

try {
    $networks = $pdo->query("SELECT * FROM networks ORDER BY name ASC")->fetchAll();
    $customers = $pdo->query("SELECT c.*, l.name as location_name FROM customers c LEFT JOIN locations l ON c.location_id = l.id ORDER BY c.name ASC")->fetchAll();
    $locations = $pdo->query("SELECT * FROM locations ORDER BY name ASC")->fetchAll();
    
    // Bundle Customer Plant Data for Javascript
    $customerPlantData = [];
    foreach ($customers as $c) {
        $customerPlantData[$c['id']] = [
            'network_id' => $c['network_id'] ?? '',
            'calix' => $c['calix_position'] ?? '',
            'splitter' => $c['splitter_position'] ?? '',
            'light_level' => $c['light_level'] ?? ''
        ];
    }
    $custPlantJson = json_encode($customerPlantData);

    $materials = $pdo->query("SELECT * FROM materials ORDER BY name ASC")->fetchAll();
    $kits = $pdo->query("SELECT * FROM kits ORDER BY name ASC")->fetchAll();
    
    $stmtKitData = $pdo->query("SELECT km.kit_id, km.material_id, km.quantity, m.name, m.unit_type, m.inventory_number FROM kit_materials km JOIN materials m ON km.material_id = m.id");
    $kitMaterialsAll = $stmtKitData->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_ASSOC);
    $kitJson = json_encode($kitMaterialsAll);
} catch (Exception $e) {
    // Silent fail
}

// 2. Clone Logic
$cloned_job = null;
$cloned_materials = [];
if (isset($_GET['clone_id'])) {
    $stmtClone = $pdo->prepare("SELECT * FROM jobs WHERE id = ?");
    $stmtClone->execute([$_GET['clone_id']]);
    $cloned_job = $stmtClone->fetch();
    if ($cloned_job) {
        $stmtCloneMat = $pdo->prepare("SELECT * FROM job_materials WHERE job_id = ?");
        $stmtCloneMat->execute([$_GET['clone_id']]);
        $cloned_materials = $stmtCloneMat->fetchAll(PDO::FETCH_ASSOC);
    }
}

// 3. Handle Form Submit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['ajax_action'])) {
    try {
        $pdo->beginTransaction();

        $final_customer_id = $_POST['customer_id'];
        $job_type = isset($_POST['is_fiber_burial']) ? 'Fiber Burial' : null;
        $location = isset($_POST['is_fiber_burial']) ? ($_POST['location'] ?? null) : null;

        // Process Plant Info
        $network_id = !empty($_POST['network_id']) ? $_POST['network_id'] : null;
        $calix_pos = trim($_POST['calix_position'] ?? '');
        $splitter_pos = trim($_POST['splitter_position'] ?? '');
        $light_level = trim($_POST['light_level'] ?? '');
        $plant_change = (!empty($network_id) || !empty($calix_pos) || !empty($splitter_pos)) ? 1 : 0;

        // OVERWRITE Customer's Permanent Record with this new Plant Info
        $stmtCust = $pdo->prepare("UPDATE customers SET network_id = ?, calix_position = ?, splitter_position = ?, light_level = ? WHERE id = ?");
        $stmtCust->execute([$network_id, $calix_pos, $splitter_pos, $light_level, $final_customer_id]);

        // Insert Job
        $stmt = $pdo->prepare("INSERT INTO jobs (customer_id, job_type, location, time_spent, mileage, service_order_number, trouble_ticket_number, job_date, notes, plant_change, network_id, calix_position, splitter_position, light_level, is_billable, is_smx, is_cobalt) VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $final_customer_id,
            $job_type,
            $location,
            !empty($_POST['time_spent']) ? $_POST['time_spent'] : null,
            !empty($_POST['mileage']) ? $_POST['mileage'] : null, 
            $_POST['job_date'],
            $_POST['notes'] ?? '',
            $plant_change,
            $network_id,
            $calix_pos,
            $splitter_pos,
            $light_level,
            isset($_POST['is_billable']) ? 1 : 0,
            isset($_POST['is_smx']) ? 1 : 0,
            isset($_POST['is_cobalt']) ? 1 : 0
        ]);
        $job_id = $pdo->lastInsertId();

        // Insert Materials
        if (isset($_POST['material_id']) && is_array($_POST['material_id'])) {
            $stmtMat = $pdo->prepare("INSERT INTO job_materials (job_id, material_id, quantity, serial_number, cxnk_number) VALUES (?, ?, ?, ?, ?)");
            for ($i = 0; $i < count($_POST['material_id']); $i++) {
                if (!empty($_POST['material_id'][$i]) && !empty($_POST['quantity'][$i])) {
                    $stmtMat->execute([
                        $job_id, 
                        $_POST['material_id'][$i], 
                        $_POST['quantity'][$i], 
                        $_POST['serial_number'][$i] ?? null, 
                        $_POST['cxnk_number'][$i] ?? null
                    ]);
                }
            }
        }

        $pdo->commit();
        require_once 'job_sync.php';
        syncJobTime($pdo, $job_id);
        header("Location: job_view.php?id=$job_id&success=1");
        exit;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        die("Save Error: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Job Ticket</title>
    <link rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
    <link href="/assets/css/tom-select.min.css" rel="stylesheet">
    <script src="/assets/js/tom-select.min.js"></script>
    <script>
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            document.documentElement.style.backgroundColor = '#111827';
        } else {
            document.documentElement.classList.remove('dark');
            document.documentElement.style.backgroundColor = '#f3f4f6';
        }
    </script>
    <style>
        input, select, textarea, button { font-size: 13px !important; box-sizing: border-box !important; }
        .ts-control { height: 34px !important; min-height: 34px !important; padding-top: 0 !important; padding-bottom: 0 !important; display: flex !important; align-items: center !important; }
        .ts-wrapper.single .ts-control { box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); }
        .dark .ts-control, .dark .ts-dropdown { background-color: #374151 !important; color: #e5e7eb !important; border-color: #4b5563 !important; }
        .dark .ts-control > input { background-color: transparent !important; color: #e5e7eb !important; }
        .dark .ts-dropdown .active { background-color: #3b82f6 !important; color: #fff !important; }
        .ts-dropdown .active, .dark .ts-dropdown .active { background-color: #3b82f6 !important; color: #ffffff !important; }
        .ts-dropdown { z-index: 9999 !important; }
        .dark select option { background-color: #374151; color: #e5e7eb; }
        select option { background-color: #ffffff; color: #000000; }
        input[type=number] { -moz-appearance: textfield; appearance: textfield; }
        input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
        /* Hide raw selects until TomSelect initialises them to prevent flash */
        #customer-select:not(.tomselected),
        #time_select:not(.tomselected),
        select.material-select:not(.tomselected) { opacity: 0; }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 h-full flex overflow-hidden text-sm"
      x-data="{ custOpen: false, matOpen: false, fiberBurial: <?= (isset($cloned_job) && $cloned_job['job_type'] === 'Fiber Burial') ? 'true' : 'false' ?> }"
      @open-cust.window="custOpen = true; $nextTick(() => document.getElementById('newCustName').focus())"
      @close-cust.window="custOpen = false"
      @open-mat.window="matOpen = true; $nextTick(() => document.getElementById('newMatName').focus())"
      @close-mat.window="matOpen = false">

    <?php include 'sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-full overflow-hidden relative">
        <header class="h-12 bg-white dark:bg-gray-800 shadow-sm flex items-center px-4 justify-between shrink-0">
            <button class="open-sidebar-btn md:hidden mr-3 text-gray-500 hover:text-blue-600 transition">
                <i class="fas fa-bars text-xl"></i>
            </button>
            <h2 class="font-bold text-gray-700 dark:text-gray-200 uppercase tracking-wide text-xs">
                <?= $cloned_job ? "Clone Job #{$cloned_job['id']}" : "New Job Entry" ?>
            </h2>
        </header>

        <div class="flex-1 overflow-auto p-4 flex justify-center">
            <div class="w-full max-w-5xl bg-white dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 p-5 shadow-sm">
                
                <form method="POST" id="jobForm" novalidate onsubmit="return validateMaterials()">
                    
                    <div class="grid grid-cols-12 gap-3 mb-4">
                        <div class="col-span-12 md:col-span-4">
                            <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Customer</label>
                            <select name="customer_id" id="customer-select" required class="w-full">
                                <option value="">Select...</option>
                                <option value="NEW_CUSTOMER">+ Add New</option>
                                <?php foreach ($customers as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= ($cloned_job && $cloned_job['customer_id'] == $c['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($c['name']) ?> - <?= htmlspecialchars($c['location_name'] ?? 'Unknown') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-span-4 md:col-span-2">
                            <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Date</label>
                            <input type="date" name="job_date" value="<?= date('Y-m-d') ?>" required class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                        </div>
                        
                        <div class="col-span-4 md:col-span-2">
                            <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Time</label>
                            <select name="time_spent" id="time_select" class="w-full">
                                <option value="">-</option>
                                <?= generateTimeOptions($cloned_job['time_spent'] ?? null) ?>
                            </select>
                        </div>

                        <div class="col-span-4 md:col-span-1">
                            <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Miles</label>
                            <input type="number" step="0.1" name="mileage" value="<?= $cloned_job['mileage'] ?? '' ?>" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 text-center focus:border-blue-500 outline-none">
                        </div>

                        <div class="col-span-12 md:col-span-3 flex items-end gap-1">
                            <label class="flex items-center justify-center gap-0.5 cursor-pointer select-none h-[34px] px-0.5 flex-1 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 rounded transition hover:bg-emerald-100 dark:hover:bg-emerald-900/40">
                                <input type="checkbox" name="is_billable" value="1" class="rounded text-emerald-600 focus:ring-0 w-2.5 h-2.5" <?= (!empty($cloned_job['is_billable'])) ? 'checked' : '' ?>>
                                <span class="text-[8px] font-bold text-emerald-700 dark:text-emerald-400 uppercase tracking-tighter">Bill</span>
                            </label>
                            <label class="flex items-center justify-center gap-0.5 cursor-pointer select-none h-[34px] px-0.5 flex-1 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded transition hover:bg-blue-100 dark:hover:bg-blue-900/40">
                                <input type="checkbox" name="is_cobalt" value="1" class="rounded text-blue-600 focus:ring-0 w-2.5 h-2.5" <?= (!empty($cloned_job['is_cobalt'])) ? 'checked' : '' ?>>
                                <span class="text-[8px] font-bold text-blue-700 dark:text-blue-400 uppercase tracking-tighter">Cobalt</span>
                            </label>
                            <label class="flex items-center justify-center gap-0.5 cursor-pointer select-none h-[34px] px-0.5 flex-1 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded transition hover:bg-purple-100 dark:hover:bg-purple-900/40">
                                <input type="checkbox" name="is_smx" id="is_smx" value="1" class="rounded text-purple-600 focus:ring-0 w-2.5 h-2.5" <?= (!empty($cloned_job['is_smx'])) ? 'checked' : '' ?>>
                                <span class="text-[8px] font-bold text-purple-700 dark:text-purple-400 uppercase tracking-tighter">SMx</span>
                            </label>
                            <label class="flex items-center justify-center gap-0.5 cursor-pointer select-none h-[34px] px-0.5 flex-1 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded transition hover:bg-orange-100 dark:hover:bg-orange-900/40">
                                <input type="checkbox" id="fiber_burial_check" name="is_fiber_burial" value="1" @change="fiberBurial = $event.target.checked" class="rounded text-orange-500 focus:ring-0 w-2.5 h-2.5" <?= (isset($cloned_job) && $cloned_job['job_type'] === 'Fiber Burial') ? 'checked' : '' ?>>
                                <span class="text-[8px] font-bold text-orange-700 dark:text-orange-400 uppercase tracking-tighter">Burial</span>
                            </label>
                        </div>
                    </div>

                    <div id="dynamic-container" x-show="fiberBurial" x-cloak class="mb-4 bg-gray-50 dark:bg-gray-800/50 p-3 rounded border border-gray-200 dark:border-gray-700 w-full md:w-1/2">
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Location / Coordinates</label>
                        <input type="text" name="location" value="<?= $cloned_job['location'] ?? '' ?>" class="w-full h-[34px] bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                    </div>

                    <div class="mb-4 bg-blue-50 dark:bg-gray-800/60 border border-blue-100 dark:border-gray-700 rounded p-3">
                        <div class="flex items-center justify-between mb-2">
                            <h3 class="font-bold text-blue-800 dark:text-gray-300 uppercase text-[10px] tracking-wide">Plant Information</h3>
                            <span class="text-[9px] text-blue-500 dark:text-gray-500 italic">Auto-fills based on customer</span>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-12 gap-3">
                            <div class="md:col-span-3">
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Network</label>
                                <select id="network_input" name="network_id" class="w-full h-[34px] bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none text-xs">
                                    <option value="">-- None --</option>
                                    <?php foreach ($networks as $net): ?>
                                        <option value="<?= $net['id'] ?>" <?= (($cloned_job['network_id'] ?? '') == $net['id']) ? 'selected' : '' ?>><?= htmlspecialchars($net['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="md:col-span-3">
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Calix Pos</label>
                                <input type="text" id="calix_input" name="calix_position" value="<?= htmlspecialchars($cloned_job['calix_position'] ?? '') ?>" class="w-full h-[34px] bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                            </div>
                            <div class="md:col-span-3">
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Splitter Pos</label>
                                <input type="text" id="splitter_input" name="splitter_position" value="<?= htmlspecialchars($cloned_job['splitter_position'] ?? '') ?>" class="w-full h-[34px] bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                            </div>
                            <div class="md:col-span-3">
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Light (dBm)</label>
                                <input type="text" id="light_level_input" name="light_level" value="<?= htmlspecialchars($cloned_job['light_level'] ?? '') ?>" placeholder="e.g. -24.5" class="w-full h-[34px] bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Notes</label>
                        <textarea name="notes" rows="2" class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 py-1.5 focus:border-blue-500 outline-none resize-none"><?= $cloned_job['notes'] ?? '' ?></textarea>
                    </div>

                    <div class="border-t border-gray-200 dark:border-gray-700 my-4"></div>

                    <div class="flex justify-between items-center mb-2">
                        <h3 class="font-bold text-gray-500 dark:text-gray-400 uppercase text-xs">Materials</h3>
                        <div class="flex gap-2">
                            <select id="kit-loader" onchange="loadKit(this.value)" class="h-[34px] text-[10px] bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:outline-none">
                                <option value="">Load Kit...</option>
                                <?php if(isset($kits)) foreach ($kits as $k): ?>
                                    <option value="<?= $k['id'] ?>"><?= htmlspecialchars($k['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button type="button" onclick="openNewMaterialModal()" class="h-[34px] px-3 bg-emerald-100 dark:bg-emerald-900/30 hover:bg-emerald-200 dark:hover:bg-emerald-900/60 text-emerald-700 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-800 rounded text-[10px] font-bold uppercase transition flex items-center justify-center">
                                <i class="fas fa-box-open mr-1"></i> New Item
                            </button>
                            <button type="button" onclick="addMaterialRow()" class="h-[34px] px-3 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded text-[10px] font-bold uppercase transition flex items-center justify-center">
                                <i class="fas fa-plus"></i> &nbsp;Add
                            </button>
                        </div>
                    </div>

                    <div class="bg-gray-50 dark:bg-gray-900/30 border border-gray-200 dark:border-gray-700 rounded mb-5">
                        <table class="w-full">
                            <tbody id="material-rows">
                                <?php 
                                $initial_rows = !empty($cloned_materials) ? $cloned_materials : [['material_id' => '', 'quantity' => '']];
                                foreach ($initial_rows as $row): 
                                ?>
                                <tr class="material-row group border-b border-gray-100 dark:border-gray-700 last:border-0">
                                    <td class="p-2 w-1/2 align-top">
                                        <select name="material_id[]" class="material-select w-full">
                                            <option value="">Select Material...</option>
                                            <?php foreach ($materials as $m): ?>
                                                <option value="<?= $m['id'] ?>" data-inventory="<?= htmlspecialchars($m['inventory_number'] ?? '') ?>" <?= $m['id'] == $row['material_id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($m['name']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="giga-fields mt-2 flex gap-2 <?= (isset($row['material_id']) && $row['material_id']) ? '' : 'hidden' ?>">
                                            <input type="text" name="cxnk_number[]" value="<?= $row['cxnk_number'] ?? '' ?>" placeholder="CXNK #" class="w-1/2 h-[34px] bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                                            <input type="text" name="serial_number[]" value="<?= $row['serial_number'] ?? '' ?>" placeholder="Serial #" class="w-1/2 h-[34px] bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                                        </div>
                                    </td>
                                    <td class="p-2 w-24 align-top">
                                        <input type="text" readonly class="inventory-display w-full h-[34px] bg-transparent border-none text-gray-400 text-xs text-center flex items-center justify-center" placeholder="-">
                                    </td>
                                    <td class="p-2 w-20 align-top">
                                        <input type="number" step="1" name="quantity[]" value="<?= $row['quantity'] ?>" placeholder="Qty" class="w-full h-[34px] bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded px-2 text-center focus:border-blue-500 outline-none">
                                    </td>
                                    <td class="p-2 w-8 text-center align-top">
                                        <button type="button" onclick="removeRow(this)" class="h-[34px] w-full flex items-center justify-center text-gray-400 hover:text-red-500 transition">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="flex justify-end">
                        <button type="submit" class="bg-blue-600 hover:bg-blue-500 text-white px-8 h-[34px] rounded shadow text-xs font-bold uppercase tracking-wide transition flex items-center justify-center">
                            Save Job Ticket
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div id="customerModal" x-show="custOpen" x-cloak @click.self="custOpen = false" @keydown.escape.window="custOpen = false" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center backdrop-blur-sm">
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-sm p-5 border border-gray-200 dark:border-gray-700">
                <h3 class="font-bold text-gray-800 dark:text-gray-200 mb-4 uppercase tracking-wide text-sm">Add New Customer</h3>
                <div class="space-y-3">
                    <div>
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Customer Name</label>
                        <input type="text" id="newCustName" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Location / Exchange</label>
                        <select id="newCustLoc" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                            <option value="">Select Location...</option>
                            <?php foreach ($locations as $l): ?>
                                <option value="<?= $l['id'] ?>"><?= htmlspecialchars($l['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="flex justify-end gap-2 mt-5">
                    <button type="button" @click="closeCustomerModal()" class="px-4 py-1.5 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded text-xs font-bold uppercase transition hover:bg-gray-300 dark:hover:bg-gray-600">Cancel</button>
                    <button type="button" @click="saveNewCustomer()" class="px-4 py-1.5 bg-blue-600 text-white rounded text-xs font-bold uppercase transition hover:bg-blue-500 shadow">Save</button>
                </div>
            </div>
        </div>
        </main>

    <table class="hidden">
        <tbody id="template-body">
            <tr id="template-row" class="material-row border-b border-gray-100 dark:border-gray-700 last:border-0 hidden">
                <td class="p-2 w-1/2 align-top">
                    <select class="material-select w-full"><option value="">Select Material...</option><?php foreach ($materials as $m): ?><option value="<?= $m['id'] ?>" data-inventory="<?= htmlspecialchars($m['inventory_number'] ?? '') ?>"><?= htmlspecialchars($m['name']) ?></option><?php endforeach; ?></select>
                    <div class="giga-fields hidden mt-2 flex gap-2">
                        <input type="text" placeholder="CXNK #" class="field-cxnk w-1/2 h-[34px] bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                        <input type="text" placeholder="Serial #" class="field-serial w-1/2 h-[34px] bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                    </div>
                </td>
                <td class="p-2 w-24 align-top"><input type="text" readonly class="inventory-display w-full h-[34px] bg-transparent border-none text-gray-400 text-xs text-center flex items-center justify-center" placeholder="-"></td>
                <td class="p-2 w-20 align-top"><input type="number" step="1" placeholder="Qty" class="field-qty w-full h-[34px] bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded px-2 text-center focus:border-blue-500 outline-none"></td>
                <td class="p-2 w-8 text-center align-top">
                    <button type="button" onclick="removeRow(this)" class="h-[34px] w-full flex items-center justify-center text-gray-400 hover:text-red-500 transition"><i class="fas fa-times"></i></button>
                </td>
            </tr>
        </tbody>
    </table>

    <script>
        const kitData = <?= $kitJson ?>;
        const custPlantData = <?= $custPlantJson ?>;

        // Initialize Customer Dropdown
        const custSelect = document.getElementById('customer-select');
        if (custSelect) {
            new TomSelect(custSelect, {
                create: false,
                maxOptions: false,
                onChange: function(value) {
                    if (value === 'NEW_CUSTOMER') {
                        this.clear(true);
                        this.blur();
                        openCustomerModal();
                    } else if (value && custPlantData[value]) {
                        document.getElementById('network_input').value = custPlantData[value].network_id || '';
                        document.getElementById('calix_input').value = custPlantData[value].calix || '';
                        document.getElementById('splitter_input').value = custPlantData[value].splitter || '';
                        document.getElementById('light_level_input').value = custPlantData[value].light_level || '';
                    } else {
                        document.getElementById('network_input').value = '';
                        document.getElementById('calix_input').value = '';
                        document.getElementById('splitter_input').value = '';
                        document.getElementById('light_level_input').value = '';
                    }
                }
            });
        }

        // Initialize Time Dropdown
        const timeSelect = document.getElementById('time_select');
        if (timeSelect) {
            new TomSelect(timeSelect, {
                create: false,
                sortField: null,
                controlInput: null,
                onChange: function() { this.blur(); }
            });
        }

        // Initialize Existing Material Dropdowns
        document.querySelectorAll('#material-rows .material-row select.material-select').forEach(s => {
            const ts = new TomSelect(s, {
                create: false,
                sortField: "text",
                onChange: function(value) { handleMatChange(this.wrapper, value); }
            });
            if(s.value) handleMatChange(ts.wrapper, s.value);
        });


        // --- UI & Helper Functions ---
        function openCustomerModal() {
            window.dispatchEvent(new CustomEvent('open-cust'));
        }

        function closeCustomerModal() {
            window.dispatchEvent(new CustomEvent('close-cust'));
            document.getElementById('newCustName').value = '';
            document.getElementById('newCustLoc').value = '';
        }

        function saveNewCustomer() {
            const name = document.getElementById('newCustName').value.trim();
            const loc_id = document.getElementById('newCustLoc').value;
            
            if (!name || !loc_id) {
                alert("Please enter a name and select a location.");
                return;
            }
            
            const formData = new FormData();
            formData.append('ajax_action', 'add_customer');
            formData.append('name', name);
            formData.append('location_id', loc_id);
            
            fetch('', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    custPlantData[data.id] = { network_id: '', calix: '', splitter: '', light_level: '' };
                    const ts = document.getElementById('customer-select').tomselect;
                    ts.addOption({value: data.id, text: data.name + ' - ' + data.location_name});
                    ts.addItem(data.id);
                    closeCustomerModal();
                } else {
                    alert("Error: " + data.error);
                }
            })
            .catch(err => { alert("Network error occurred."); console.error(err); });
        }

        function loadKit(id) {
            if(!id || !kitData[id]) return;
            document.getElementById('material-rows').innerHTML = '';
            kitData[id].forEach(item => addMaterialRow(item.material_id, item.quantity));
            document.getElementById('kit-loader').value = "";
        }

        function addMaterialRow(matId=null, qty=null) {
            const row = document.getElementById('template-row').cloneNode(true);
            row.classList.remove('hidden'); row.removeAttribute('id');
            const sel = row.querySelector('select'); sel.name = 'material_id[]'; if(matId) sel.value = matId;
            const q = row.querySelector('.field-qty'); q.name = 'quantity[]'; if(qty) q.value = qty;
            row.querySelector('.field-serial').name = 'serial_number[]';
            row.querySelector('.field-cxnk').name = 'cxnk_number[]';
            document.getElementById('material-rows').appendChild(row);
            
            const ts = new TomSelect(sel, { 
                create: false, sortField: "text", 
                onChange: function(value) { handleMatChange(this.wrapper, value); } 
            });
            
            if(matId) setTimeout(() => handleMatChange(ts.wrapper, matId), 10);
        }

        function handleMatChange(wrap, val) {
            const row = wrap.closest('tr');
            const originalSelect = row.querySelector('select.material-select'); 
            const opt = originalSelect.querySelector(`option[value="${val}"]`);
            const gf = row.querySelector('.giga-fields');
            const inv = row.querySelector('.inventory-display');
            
            if(!val || !opt) { gf.classList.add('hidden'); inv.value = ''; row.removeAttribute('data-giga'); return; }
            
            inv.value = opt.getAttribute('data-inventory') || '-';
            if(opt.text.toLowerCase().includes('giga')) { gf.classList.remove('hidden'); row.setAttribute('data-giga','true'); }
            else { gf.classList.add('hidden'); gf.querySelectorAll('input').forEach(i=>i.value=''); row.removeAttribute('data-giga'); }
        }

        function removeRow(btn) { btn.closest('tr').remove(); }

        function validateMaterials() {
            const custId = document.getElementById('customer-select').value;
            if (!custId || custId === 'NEW_CUSTOMER') {
                alert("Please select a customer.");
                document.getElementById('customer-select').tomselect?.focus();
                return false;
            }
            const dateVal = document.querySelector('input[name="job_date"]').value;
            if (!dateVal) {
                alert("Please enter a date.");
                document.querySelector('input[name="job_date"]').focus();
                return false;
            }
            let valid = true;
            document.querySelectorAll('.material-row[data-giga="true"]').forEach(row => {
                const s = row.querySelector('input[name="serial_number[]"]').value.trim();
                const c = row.querySelector('input[name="cxnk_number[]"]').value.trim();
                if(!s && !c) { alert("Giga items need Serial or CXNK."); row.querySelector('input[name="cxnk_number[]"]').focus(); valid=false; }
            });
            return valid;
        }

        // --- NEW MATERIAL MODAL ---
        function openNewMaterialModal() {
            document.getElementById('newMatName').value = '';
            document.getElementById('newMatInv').value = '';
            document.getElementById('newMatUnit').value = 'ea';
            window.dispatchEvent(new CustomEvent('open-mat'));
        }

        function closeNewMaterialModal() {
            window.dispatchEvent(new CustomEvent('close-mat'));
        }

        function saveNewMaterial() {
            const name = document.getElementById('newMatName').value.trim();
            const inv  = document.getElementById('newMatInv').value.trim();
            const unit = document.getElementById('newMatUnit').value;
            if (!name) { alert("Please enter a material name."); return; }

            const formData = new FormData();
            formData.append('ajax_action', 'add_material');
            formData.append('name', name);
            formData.append('inventory_number', inv);
            formData.append('unit_type', unit);

            fetch('', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    // Add the new option to every existing material TomSelect dropdown
                    document.querySelectorAll('.material-select').forEach(sel => {
                        if (sel.tomselect) {
                            sel.tomselect.addOption({ value: data.id, text: data.name, 'data-inventory': data.inventory_number });
                        }
                    });
                    closeNewMaterialModal();
                } else {
                    alert("Error: " + data.error);
                }
            })
            .catch(() => alert("Network error."));
        }

    </script>

    <!-- New Material Modal -->
    <div id="newMaterialModal" x-show="matOpen" x-cloak @click.self="matOpen = false" @keydown.escape.window="matOpen = false" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-sm p-5 border border-gray-200 dark:border-gray-700">
            <h3 class="font-bold text-gray-800 dark:text-gray-200 mb-4 uppercase tracking-wide text-sm">Add New Inventory Item</h3>
            <div class="space-y-3">
                <div>
                    <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Material Name *</label>
                    <input type="text" id="newMatName" placeholder="e.g. Fiber Drop Cable" @keydown.enter="saveNewMaterial()" @keydown.escape="closeNewMaterialModal()" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                </div>
                <div class="flex gap-2">
                    <div class="flex-1">
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Inventory #</label>
                        <input type="text" id="newMatInv" placeholder="Inv #" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                    </div>
                    <div class="w-28">
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Unit Type</label>
                        <select id="newMatUnit" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:border-blue-500 outline-none">
                            <option value="ea">Each</option>
                            <option value="ft">Feet</option>
                            <option value="m">Meters</option>
                            <option value="box">Box</option>
                            <option value="roll">Roll</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="flex gap-2 justify-end mt-5">
                <button type="button" @click="closeNewMaterialModal()" class="px-4 py-2 text-xs font-bold uppercase rounded bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition">Cancel</button>
                <button type="button" @click="saveNewMaterial()" class="px-4 py-2 text-xs font-bold uppercase rounded bg-emerald-600 hover:bg-emerald-500 text-white shadow transition"><i class="fas fa-plus mr-1"></i> Add Item</button>
            </div>
        </div>
    </div>
</body>
</html>