<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$page_title = 'Tambah Jadwal Produksi';
require_once('includes/load.php');
page_require_level(3);

// --- Bagian Logika untuk Autosuggestion (AJAX) ---
if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    // Ini adalah permintaan AJAX, proses pencarian Part Number
    header('Content-Type: application/json');

    if (isset($_GET['q']) && !empty($_GET['q'])) {
        $search_query = $db->escape($_GET['q']);
        // Query mencari berdasarkan part_number ATAU name
        $sql = "SELECT part_number, name FROM products WHERE part_number LIKE '%{$search_query}%' OR name LIKE '%{$search_query}%' LIMIT 10";
        $result = $db->query($sql);
        $data = [];
        if ($result) {
            while ($row = $db->fetch_assoc($result)) {
                $data[] = $row; // Mengembalikan array asosiatif
            }
        }
        echo json_encode($data);
    } else {
        echo json_encode([]);
    }
    exit;
}
// --- Akhir Bagian Logika AJAX ---

// --- Bagian Logika untuk Pemrosesan Formulir (POST) ---
if(isset($_POST['add_schedule'])){
    $req_fields = array('no-order', 'client', 'part-number', 'quantity-order', 'delivery-date');
    validate_fields($req_fields);

    if(empty($errors)){
        $no_order = $db->escape($_POST['no-order']);
        $client = $db->escape($_POST['client']);
        $part_number = $db->escape($_POST['part-number']);
        $quantity_order = (int)$db->escape($_POST['quantity-order']);
        $delivery_date = $db->escape($_POST['delivery-date']);

        $query = "INSERT INTO production_schedule (no_order, client, part_number, quantity_order, delivery_date, input_date) 
                  VALUES ('{$no_order}', '{$client}', '{$part_number}', {$quantity_order}, '{$delivery_date}', NOW())";

        if($db->query($query)){
            $session->msg('s', "Jadwal produksi berhasil ditambahkan!");
            redirect('production_schedule', false);
        } else {
            $session->msg('d', 'Maaf, gagal menambahkan jadwal produksi. Silakan coba lagi.');
            redirect('add_schedule.php', false);
        }
    } else {
        $session->msg('d', $errors);
        redirect('add_schedule.php', false);
    }
}
// --- Akhir Bagian Logika POST ---

// --- Bagian Tampilan HTML dan Formulir ---
include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Tambah Jadwal Produksi Baru</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="add_schedule.php">
                    <div class="form-group">
                        <label for="no-order">Nomor Order</label>
                        <input type="text" class="form-control" name="no-order" placeholder="Nomor Order" required>
                    </div>
                    <div class="form-group">
                        <label for="client">Klien</label>
                        <input type="text" class="form-control" name="client" placeholder="Nama Klien" required>
                    </div>
                    <div class="form-group">
                        <label for="part-number">Part Number</label>
                        <input type="text" class="form-control" name="part-number" id="part-number-input" placeholder="Part Number" autocomplete="off" required>
                        <div id="part-number-suggestions" class="list-group"></div>
                    </div>
                    <div class="form-group">
                        <label for="quantity-order">Quantity Order</label>
                        <input type="number" class="form-control" name="quantity-order" placeholder="Jumlah Order" required>
                    </div>
                    <div class="form-group">
                        <label for="delivery-date">Tanggal Pengiriman</label>
                        <input type="date" class="form-control" name="delivery-date" required>
                    </div>
                    <button type="submit" name="add_schedule" class="btn btn-primary">Tambah Jadwal</button>
                    <a href="production_schedule.php" class="btn btn-default">Batal</a>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    const partNumberInput = document.getElementById('part-number-input');
    const suggestionsBox = document.getElementById('part-number-suggestions');

    partNumberInput.addEventListener('keyup', function() {
        const query = this.value;
        if (query.length > 2) {
            fetch('add_schedule.php?ajax=1&q=' + query)
            .then(response => response.json())
            .then(data => {
                suggestionsBox.innerHTML = '';
                if (data.length > 0) {
                    data.forEach(item => {
                        const suggestionItem = document.createElement('a');
                        suggestionItem.classList.add('list-group-item', 'list-group-item-action');
                        suggestionItem.href = '#';
                        suggestionItem.textContent = `${item.part_number} - ${item.name}`;
                        suggestionItem.dataset.partNumber = item.part_number; 
                        suggestionItem.addEventListener('click', function(e) {
                            e.preventDefault();
                            partNumberInput.value = this.dataset.partNumber;
                            suggestionsBox.innerHTML = '';
                            suggestionsBox.style.display = 'none';
                        });
                        suggestionsBox.appendChild(suggestionItem);
                    });
                    suggestionsBox.style.display = 'block';
                } else {
                    suggestionsBox.style.display = 'none';
                }
            })
            .catch(error => console.error('Error fetching data:', error));
        } else {
            suggestionsBox.innerHTML = '';
            suggestionsBox.style.display = 'none';
        }
    });

    // Sembunyikan saran saat klik di luar kotak saran
    document.addEventListener('click', function(e) {
        if (!partNumberInput.contains(e.target) && !suggestionsBox.contains(e.target)) {
            suggestionsBox.style.display = 'none';
        }
    });
</script>

<?php include_once('layouts/footer.php'); ?>