<?php
require_once '../config/config.php';
if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

 $activePage = 'line';
 $pageTitle = $lang[$current_lang]['lines'];

try {
    // PERBAIKAN: Gunakan backtick (`) pada nama tabel 'lines'
    $stmt = $pdo->query("SELECT l.*, m.nama_mesin FROM `lines` l LEFT JOIN mesin m ON l.mesin_id = m.id ORDER BY l.created_at DESC");
    $lines = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt_mesin = $pdo->query("SELECT id, nama_mesin FROM mesin ORDER BY nama_mesin ASC");
    $mesins = $stmt_mesin->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error Query: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="<?= $current_lang ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= APP_NAME ?> - <?= $pageTitle ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.2.96/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../assets/css/dinar.css" rel="stylesheet">
</head>
<body data-theme="<?= $current_theme ?>" class="text-size-<?= $current_text_size ?> btn-size-<?= $current_btn_size ?> icon-size-<?= $current_icon_size ?>">
    <div class="app-wrapper">
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        <?php include 'includes/sidebar.php'; ?>
        
        <main class="main-content">
            <?php include 'includes/header.php'; ?>
            
            <div class="page-content">
                <div class="page-header fade-in">
                    <div>
                        <h1 class="page-title"><?= $pageTitle ?></h1>
                        <p class="page-subtitle">Kelola data Line dan Produk yang dihasilkan</p>
                    </div>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalLine" onclick="resetForm()">
                        <i class="mdi mdi-plus"></i> <?= $lang[$current_lang]['add_line'] ?>
                    </button>
                </div>
                
                <div class="card fade-in">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover data-table">
                                <thead>
                                    <tr>
                                        <th width="50">#</th>
                                        <th><?= $lang[$current_lang]['line_name'] ?></th>
                                        <th><?= $lang[$current_lang]['product_name'] ?></th>
                                        <th><?= $lang[$current_lang]['machine_used'] ?></th>
                                        <th width="150" class="text-center"><?= $lang[$current_lang]['action'] ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $no=1; foreach($lines as $ln): ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= htmlspecialchars($ln['nama_line']) ?></td>
                                        <td><?= htmlspecialchars($ln['nama_product']) ?></td>
                                        <td>
                                            <?= $ln['nama_mesin'] ? '<span class="badge bg-info text-dark"><i class="mdi mdi-cog"></i> '.htmlspecialchars($ln['nama_mesin']).'</span>' : '<span class="text-muted">-</span>' ?>
                                        </td>
                                        <td class="text-center">
                                            <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#modalDetail" 
                                                onclick="viewDetail('<?= htmlspecialchars($ln['nama_line']) ?>', '<?= htmlspecialchars($ln['nama_product']) ?>', '<?= htmlspecialchars($ln['nama_mesin'] ?? '-') ?>')">
                                                <i class="mdi mdi-eye-outline"></i>
                                            </button>
                                            <button class="btn btn-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#modalLine" 
                                                onclick="editLine(<?= $ln['id'] ?>, '<?= htmlspecialchars($ln['nama_line']) ?>', '<?= htmlspecialchars($ln['nama_product']) ?>', <?= $ln['mesin_id'] ?? 'null' ?>)">
                                                <i class="mdi mdi-pencil"></i>
                                            </button>
                                            <form action="../post/line_action.php" method="POST" class="d-inline">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="id" value="<?= $ln['id'] ?>">
                                                <button type="submit" class="btn btn-danger btn-sm btn-delete" data-name="<?= htmlspecialchars($ln['nama_line']) ?>">
                                                    <i class="mdi mdi-trash-can"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'includes/footer.php'; ?>
        </main>
    </div>

    <!-- Modal Tambah/Edit Line -->
    <div class="modal fade" id="modalLine" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalLineTitle"><?= $lang[$current_lang]['add_line'] ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="../post/line_action.php" method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add">
                        <input type="hidden" name="id" id="line_id">
                        
                        <div class="mb-3">
                            <label class="form-label"><?= $lang[$current_lang]['line_name'] ?></label>
                            <input type="text" name="nama_line" id="line_name" class="form-control" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label"><?= $lang[$current_lang]['product_name'] ?></label>
                            <input type="text" name="nama_product" id="product_name" class="form-control" required>
                        </div>
                        
                        <!-- Select2 dengan ID khusus -->
                        <div class="mb-3">
                            <label class="form-label"><?= $lang[$current_lang]['machine_used'] ?></label>
                            <select name="mesin_id" id="select_mesin" class="form-select select2-modal">
                                <option value="">-- <?= $lang[$current_lang]['select_machine'] ?> --</option>
                                <?php foreach($mesins as $m): ?>
                                    <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['nama_mesin']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= $lang[$current_lang]['cancel'] ?></button>
                        <button type="submit" class="btn btn-primary"><?= $lang[$current_lang]['save'] ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Detail Line -->
    <div class="modal fade" id="modalDetail" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="mdi mdi-information-outline me-2"></i><?= $lang[$current_lang]['line_detail'] ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <table class="table table-borderless">
                        <tr>
                            <td class="text-muted" width="120"><?= $lang[$current_lang]['line_name'] ?></td>
                            <td><strong id="detail_nama_line">-</strong></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><?= $lang[$current_lang]['product_name'] ?></td>
                            <td><strong id="detail_nama_product">-</strong></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><?= $lang[$current_lang]['machine_used'] ?></td>
                            <td id="detail_nama_mesin">-</td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- PAGE SPECIFIC SCRIPTS (Hanya logic, tidak load library ulang) -->
    <script>
        // Script ini berjalan setelah footer (library) dimuat
        
        // 1. Inisialisasi Select2 KHUSUS untuk modal ini
        // Kita gunakan class berbeda 'select2-modal' agar bisa diinisialisasi ulang jika perlu
        if (typeof $.fn.select2 !== 'undefined') {
            $('#select_mesin').select2({
                theme: 'default',
                width: '100%',
                dropdownParent: $('#modalLine') // Penting!
            });
        }

        // Reset Form
        function resetForm() {
            document.getElementById('modalLineTitle').innerText = "<?= $lang[$current_lang]['add_line'] ?>";
            document.getElementById('line_id').value = "";
            document.getElementById('line_name').value = "";
            document.getElementById('product_name').value = "";
            document.querySelector('#modalLine input[name="action"]').value = "add";
            
            // Reset Select2 dengan aman
            if (typeof $('#select_mesin').val === 'function') {
                $('#select_mesin').val('').trigger('change');
            }
        }

        // Edit Line
        function editLine(id, nama_line, nama_product, mesin_id) {
            document.getElementById('modalLineTitle').innerText = "<?= $lang[$current_lang]['edit_line'] ?>";
            document.getElementById('line_id').value = id;
            document.getElementById('line_name').value = nama_line;
            document.getElementById('product_name').value = nama_product;
            document.querySelector('#modalLine input[name="action"]').value = "edit";
            
            // Set nilai Select2
            if(mesin_id) {
                $('#select_mesin').val(mesin_id).trigger('change');
            } else {
                $('#select_mesin').val('').trigger('change');
            }
        }

        // View Detail
        function viewDetail(nama_line, nama_product, nama_mesin) {
            document.getElementById('detail_nama_line').innerText = nama_line;
            document.getElementById('detail_nama_product').innerText = nama_product;
            document.getElementById('detail_nama_mesin').innerText = nama_mesin ? nama_mesin : 'Tidak ada mesin';
        }
    </script>
</body>
</html>