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

 $activePage = 'spareparts';
 $pageTitle = $lang[$current_lang]['spareparts'];

// --- QUERY DATA UTAMA ---
try {
    $query = "
        SELECT s.*, 
               c.name as category_name, 
               l.name as location_name,
               m.name as material_group_name
        FROM spareparts s
        LEFT JOIN category c ON s.category_id = c.id
        LEFT JOIN locations l ON s.location_id = l.id
        LEFT JOIN material_group m ON s.material_group_id = m.id
        ORDER BY s.name ASC
    ";
    $stmt = $pdo->query($query);
    $spareparts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("SQL Error (Main): " . $e->getMessage());
}

// --- QUERY DATA DROPDOWN ---
try {
    $categories = $pdo->query("SELECT id, name FROM category WHERE status='active' ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $categories = []; }

try {
    $locations = $pdo->query("SELECT id, name FROM locations WHERE status='active' ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $locations = []; }

try {
    $material_groups = $pdo->query("SELECT id, name FROM material_group WHERE status='active' ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $material_groups = []; }
?>
<!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>
    
    <!-- CSS -->
    <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">
    
    <!-- JS LIBRARIES FOR PDF EXPORT -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.31/jspdf.plugin.autotable.min.js"></script>

    <style>
        /* Styling for scroll layout */
        .dataTables_wrapper .dataTables_scrollBody {
            overflow-x: auto; 
            overflow-y: visible;
            width: 100% !important;
        }
        
        /* Tombol Aksi Anti-Menumpuk */
        .action-buttons {
            display: flex !important;
            flex-wrap: nowrap !important; 
            gap: 4px;
            align-items: center;
            justify-content: center;
            min-width: 120px; 
        }
        
        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
            line-height: 1.2;
        }

        /* Modal Detail Responsive */
        .viewer-container {
            position: relative;
            width: 100%;
            height: 550px;
            background: var(--secondary); 
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 12px;
            border: 1px solid var(--card-border);
            cursor: grab;
            user-select: none;
        }
        
        @media (max-width: 768px) {
            .viewer-container { height: 300px; }
            .detail-info-title { margin-top: 15px; }
            .modal-xl { margin: 0.5rem; }
        }

        .viewer-container:active { cursor: grabbing; }
        .viewer-image {
            max-width: 100%;
            max-height: 100%;
            transition: transform 0.15s ease-out;
            pointer-events: none;
            will-change: transform;
        }
        
        .viewer-controls {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(5px);
            padding: 8px 15px;
            border-radius: 30px;
            display: flex;
            gap: 10px;
            z-index: 10;
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        .viewer-controls button {
            background: transparent;
            border: none;
            color: #fff;
            font-size: 20px;
            cursor: pointer;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        
        .viewer-controls button:hover {
            color: var(--accent);
            background: rgba(255,255,255,0.15);
        }
        
        .thumbnail-gallery {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            overflow-x: auto;
            padding-bottom: 10px;
        }
        
        .thumb-img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            cursor: pointer;
            border: 2px solid var(--card-border);
            transition: all 0.2s;
            flex-shrink: 0;
            opacity: 0.8;
        }
        
        .thumb-img:hover, .thumb-img.active {
            border-color: var(--accent);
            box-shadow: 0 0 10px var(--glow);
            opacity: 1;
            transform: scale(1.05);
        }
        
        .detail-info-table td { color: var(--text); border: none; }
        .detail-info-table td:first-child { color: var(--text-muted); font-weight: 500; width: 140px; }
        .detail-info-title {
            color: var(--accent);
            font-weight: 700;
            border-bottom: 2px solid var(--card-border);
            padding-bottom: 10px;
            margin-bottom: 15px;
        }

        .no-image-placeholder {
            color: var(--text-muted);
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
        }
        .no-image-placeholder i { font-size: 48px; margin-bottom: 10px; opacity: 0.5; }

        /* SELECT2 FIX */
        .select2-container--open .select2-dropdown {
            z-index: 9999 !important;
            background: var(--secondary) !important;
            border: 1px solid var(--card-border) !important;
        }
        .select2-results__option { color: var(--text) !important; }
        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: var(--accent) !important;
            color: #fff !important;
        }
        .select2-container--default .select2-selection--single {
            background-color: var(--input-bg) !important;
            border: 1px solid var(--input-border) !important;
            color: var(--text) !important;
            height: 42px;
            display: flex;
            align-items: center;
            border-radius: 10px;
        }
        .select2-container--default .select2-selection__rendered {
            color: var(--text) !important;
            line-height: 40px !important;
            padding-left: 16px !important;
        }
        .select2-container { width: 100% !important; }

        /* Style untuk hasil scan */
        .scan-result-item {
            background: var(--input-bg);
            border: 1px solid var(--card-border);
            border-radius: 10px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: var(--transition);
        }
        .scan-result-item:hover {
            background: var(--hover);
            border-color: var(--accent);
        }
    </style>
</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"><?= $lang[$current_lang]['manage_spareparts'] ?></p>
                    </div>
                    <div class="d-flex gap-2 flex-wrap">
                        <!-- TOMBOL SCAN IMAGE -->
                        <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#modalScanImage" title="Search by Image">
                            <i class="mdi mdi-camera"></i> Scan Image
                        </button>
                        
                        <!-- TOMBOL EXPORT PDF -->
                        <button class="btn btn-success" onclick="exportPDF()">
                            <i class="mdi mdi-file-pdf-box"></i> Export PDF
                        </button>
                        
                        <?php if ($_SESSION['role'] !== 'guest'): ?>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalForm">
                            <i class="mdi mdi-plus"></i> <?= $lang[$current_lang]['add_new'] ?>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="card fade-in">
                    <div class="card-body">
                        <table class="table data-table" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th width="50">No</th>
                                    <th><?= $lang[$current_lang]['part_number'] ?></th>
                                    <th><?= $lang[$current_lang]['part_name'] ?></th>
                                    <th>Category</th>
                                    <th>Location</th>
                                    <th>Material Group</th>
                                    <th><?= $lang[$current_lang]['stock'] ?></th>
                                    <th><?= $lang[$current_lang]['unit'] ?></th>
                                    <th><?= $lang[$current_lang]['price'] ?></th>
                                    <th><?= $lang[$current_lang]['status'] ?></th>
                                    <th width="120"><?= $lang[$current_lang]['action'] ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $no=1; foreach($spareparts as $row): ?>
                                <tr>
                                    <td><?= $no++ ?></td>
                                    <td><strong><?= htmlspecialchars($row['part_number']) ?></strong></td>
                                    <td><?= htmlspecialchars($row['name']) ?></td>
                                    <td><?= htmlspecialchars($row['category_name']) ?></td>
                                    <td><?= htmlspecialchars($row['location_name']) ?></td>
                                    <td><?= htmlspecialchars($row['material_group_name']) ?></td>
                                    <td>
                                        <?php 
                                        $stock_class = '';
                                        if($row['stock'] <= 0) $stock_class = 'text-danger fw-bold';
                                        elseif($row['stock'] < $row['min_stock']) $stock_class = 'text-warning fw-bold';
                                        ?>
                                        <span class="<?= $stock_class ?>"><?= $row['stock'] ?></span>
                                    </td>
                                    <td><?= htmlspecialchars($row['unit']) ?></td>
                                    <td><?= number_format($row['price'], 0, ',', '.') ?></td>
                                    <td>
                                        <?php if($row['status'] == 'active'): ?>
                                            <span class="badge bg-success"><?= $lang[$current_lang]['active'] ?></span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary"><?= $lang[$current_lang]['inactive'] ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="btn btn-sm btn-info" onclick="viewDetail(<?= $row['id'] ?>)" title="Detail">
                                                <i class="mdi mdi-eye"></i>
                                            </button>
                                            <?php if ($_SESSION['role'] == 'admin'): ?>
                                            <button class="btn btn-sm btn-secondary" onclick='editData(<?= json_encode($row) ?>)' title="Edit">
                                                <i class="mdi mdi-pencil"></i>
                                            </button>
                                            <form action="../post/spareparts_action.php" method="POST" class="d-inline" id="formDelSp_<?= $row['id'] ?>">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                                <button type="button" class="btn btn-sm btn-danger" onclick="confirmDeleteSparepart('formDelSp_<?= $row['id'] ?>', '<?= htmlspecialchars($row['name']) ?>')">
                                                    <i class="mdi mdi-trash-can"></i>
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- MODAL SCAN IMAGE -->
            <div class="modal fade" id="modalScanImage" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title"><i class="mdi mdi-camera mdi-18px me-2"></i>Visual Search</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <p class="text-muted small mb-3">Upload foto suku cadang untuk mencari data di sistem berdasarkan bentuk visual.</p>
                            
                            <form id="formScanImage" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label class="form-label">Pilih / Ambil Foto</label>
                                    <input type="file" name="search_image" class="form-control" accept="image/*" capture="environment" required>
                                </div>
                                <button type="submit" class="btn btn-info w-100">
                                    <i class="mdi mdi-magnify"></i> Cari Barang
                                </button>
                            </form>
                            
                            <div id="scanResults" class="mt-4"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- MODAL FORM (ADD/EDIT) -->
            <div class="modal fade" id="modalForm" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="modalTitle"><?= $lang[$current_lang]['add_new'] ?></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <form action="../post/spareparts_action.php" method="POST" enctype="multipart/form-data">
                            <div class="modal-body">
                                <input type="hidden" name="action" value="add" id="formAction">
                                <input type="hidden" name="id" id="formId">
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label"><?= $lang[$current_lang]['part_number'] ?></label>
                                        <input type="text" name="part_number" id="formPartNumber" class="form-control" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label"><?= $lang[$current_lang]['part_name'] ?></label>
                                        <input type="text" name="name" id="formName" class="form-control" required>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Category</label>
                                        <select name="category_id" id="formCategory" class="form-select select2-modal" required>
                                            <option value="">Select Category</option>
                                            <?php foreach($categories as $c): ?>
                                                <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Location</label>
                                        <select name="location_id" id="formLocation" class="form-select select2-modal" required>
                                            <option value="">Select Location</option>
                                            <?php foreach($locations as $l): ?>
                                                <option value="<?= $l['id'] ?>"><?= htmlspecialchars($l['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Material Group</label>
                                        <select name="material_group_id" id="formMaterialGroup" class="form-select select2-modal" required>
                                            <option value="">Select Group</option>
                                            <?php foreach($material_groups as $m): ?>
                                                <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Stock</label>
                                        <input type="number" name="stock" id="formStock" class="form-control" value="0" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Min Stock</label>
                                        <input type="number" name="min_stock" id="formMinStock" class="form-control" value="0" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Material Group</label>
                                        <select name="unit" id="formUnit" class="form-select select2-modal" required>
                                             <option value="PC">PCS</option>
                                             <option value="KG">KG</option>
                                             <option value="EA">EACH</option>
                                             <option value="SET">SET</option>
                                             <option value="UNIT">UNIT</option>
                                             <option value="ROLL">ROLL</option>
                                             <option value="MTR">METER</option>
                                             <option value="LTR">LITTER</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Price</label>
                                        <input type="number" name="price" id="formPrice" class="form-control" value="0" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Status</label>
                                        <select name="status" id="formStatus" class="form-select">
                                            <option value="active">Active</option>
                                            <option value="inactive">Inactive</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Description</label>
                                    <textarea name="description" id="formDesc" class="form-control" rows="2"></textarea>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Upload Images (Multiple)</label>
                                    <input type="file" name="images[]" class="form-control" multiple accept="image/*">
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" class="btn btn-primary">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- MODAL DETAIL -->
            <div class="modal fade" id="modalDetail" tabindex="-1">
                <div class="modal-dialog modal-xl modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Detail Part</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body p-3 p-md-4">
                            <div class="row">
                                <div class="col-12 col-lg-7 mb-4 mb-lg-0">
                                    <div class="viewer-container" id="viewerContainer">
                                        <img src="" id="viewerImage" class="viewer-image" style="display:none;">
                                        <div id="noImagePlaceholder" class="no-image-placeholder">
                                            <i class="mdi mdi-image-off"></i>
                                            <span>No Image Available</span>
                                        </div>
                                        <div class="viewer-controls" id="viewerControls" style="display:none;">
                                            <button onclick="zoomIn()" title="Zoom In"><i class="mdi mdi-magnify-plus"></i></button>
                                            <button onclick="zoomOut()" title="Zoom Out"><i class="mdi mdi-magnify-minus"></i></button>
                                            <button onclick="rotateImage()" title="Rotate"><i class="mdi mdi-rotate-right"></i></button>
                                            <button onclick="resetView()" title="Reset"><i class="mdi mdi-fit-to-screen"></i></button>
                                        </div>
                                    </div>
                                    <div class="thumbnail-gallery" id="thumbGallery"></div>
                                </div>
                                
                                <div class="col-12 col-lg-5">
                                    <h4 id="detailName" class="detail-info-title"></h4>
                                    <table class="table table-sm table-borderless detail-info-table">
                                        <tr><td>Part Number</td><td>: <span id="detailCode"></span></td></tr>
                                        <tr><td>Category</td><td>: <span id="detailCategory"></span></td></tr>
                                        <tr><td>Location</td><td>: <span id="detailLocation"></span></td></tr>
                                        <tr><td>Material Group</td><td>: <span id="detailMaterialGroup"></span></td></tr>
                                        <tr><td>Stock</td><td>: <span id="detailStock"></span> <span id="detailUnit"></span></td></tr>
                                        <tr><td>Price</td><td>: Rp <span id="detailPrice"></span></td></tr>
                                        <tr><td>Status</td><td>: <span id="detailStatus"></span></td></tr>
                                        <tr><td valign="top">Desc</td><td>: <span id="detailDesc"></span></td></tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            
            <?php include 'includes/footer.php'; ?>
        </main>
    </div>
    
    <script>
        // ==========================================
        // 1. DATA UNTUK EXPORT (PHP -> JS)
        // ==========================================
        const sparepartsData = <?= json_encode($spareparts) ?>;

        // ==========================================
        // 2. FUNGSI EXPORT PDF
        // ==========================================
        function exportPDF() {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF('l', 'mm', 'a4'); // Landscape A4

            // 1. Judul Dokumen
            doc.setFontSize(18);
            doc.setTextColor(40);
            doc.text("Spareparts Inventory Report", 14, 15);
            
            // 2. Tanggal Cetak
            doc.setFontSize(10);
            doc.setTextColor(100);
            doc.text("Print Date: " + new Date().toLocaleDateString('id-ID'), 14, 22);

            // 3. Persiapan Data Tabel
            const tableColumn = ["No", "Part Number", "Name", "Category", "Location", "Material", "Stock", "Unit", "Price", "Status"];
            const tableRows = [];

            sparepartsData.forEach((row, index) => {
                const rowData = [
                    index + 1,
                    row.part_number,
                    row.name,
                    row.category_name || '-',
                    row.location_name || '-',
                    row.material_group_name || '-',
                    row.stock,
                    row.unit,
                    new Intl.NumberFormat('id-ID').format(row.price),
                    row.status
                ];
                tableRows.push(rowData);
            });

            // 4. Generate Tabel
            doc.autoTable({
                head: [tableColumn],
                body: tableRows,
                startY: 26,
                theme: 'grid',
                headStyles: { 
                    fillColor: [26, 26, 46], // Warna header (Dark Blue/Black)
                    textColor: [255, 255, 255],
                    fontSize: 9,
                    halign: 'center'
                },
                bodyStyles: {
                    fontSize: 8,
                    cellPadding: 2
                },
                alternateRowStyles: {
                    fillColor: [240, 240, 240] // Warna baris bergantian
                },
                columnStyles: {
                    0: { cellWidth: 8, halign: 'center' }, // No
                    1: { cellWidth: 25 }, // Part Num
                    2: { cellWidth: 40 }, // Name
                    8: { halign: 'right' } // Price
                }
            });

            // 5. Save
            doc.save('spareparts_report.pdf');
        }
        
        // ==========================================
        // 3. FUNGSI SCAN IMAGE (VISUAL SEARCH)
        // ==========================================
        $('#formScanImage').on('submit', function(e) {
            e.preventDefault();
            let formData = new FormData(this);
            
            // Loading state
            $('#scanResults').html('<div class="text-center p-4"><i class="mdi mdi-loading mdi-spin mdi-24px"></i><br>Mencari kemiripan...</div>');
            
            $.ajax({
                url: '../get/search_by_image.php',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function(res) {
                    if(res.status === 'success' && res.count > 0) {
                        let html = '<h6 class="mb-3 text-success"><i class="mdi mdi-check-circle me-1"></i>Hasil Pencarian ('+res.count+' ditemukan)</h6>';
                        
                        res.data.forEach(item => {
                            html += `
                            <div class="scan-result-item p-2 d-flex gap-3 align-items-center" onclick="viewDetail(${item.id}); $('#modalScanImage').modal('hide');">
                                <img src="../assets/img/product/${item.image_path}" width="50" height="50" style="object-fit:cover; border-radius:8px; border:1px solid var(--card-border)">
                                <div>
                                    <strong>${item.name}</strong><br>
                                    <small class="text-muted">${item.part_number} - ${item.category_name || '-'}</small><br>
                                    <small>Stock: ${item.stock} ${item.unit}</small>
                                </div>
                            </div>`;
                        });
                        
                        $('#scanResults').html(html);
                    } else {
                        $('#scanResults').html('<div class="alert alert-warning mt-3 mb-0"><i class="mdi mdi-alert-circle-outline me-2"></i>Tidak ada barang yang cocok dengan gambar tersebut.</div>');
                    }
                },
                error: function() {
                    $('#scanResults').html('<div class="alert alert-danger mt-3 mb-0">Gagal memproses gambar. Pastikan server sudah dikonfigurasi dengan benar.</div>');
                }
            });
        });

        // ==========================================
        // LOGIC DETAIL & EDIT (Sebelumnya)
        // ==========================================
        let currentZoom = 1; let currentRotation = 0; let currentX = 0; let currentY = 0;
        let isDragging = false; let startX, startY; let imagesList = [];

        function applyTransform() {
            const img = document.getElementById('viewerImage');
            img.style.transform = `translate(${currentX}px, ${currentY}px) scale(${currentZoom}) rotate(${currentRotation}deg)`;
        }
        function zoomIn() { currentZoom += 0.3; applyTransform(); }
        function zoomOut() { if(currentZoom > 0.5) currentZoom -= 0.3; applyTransform(); }
        function rotateImage() { currentRotation += 90; applyTransform(); }
        function resetView() { currentZoom = 1; currentRotation = 0; currentX = 0; currentY = 0; applyTransform(); }

        const viewer = document.getElementById('viewerContainer');
        viewer.addEventListener('mousedown', (e) => { isDragging = true; startX = e.clientX - currentX; startY = e.clientY - currentY; viewer.style.cursor = 'grabbing'; e.preventDefault(); });
        document.addEventListener('mousemove', (e) => { if (!isDragging) return; currentX = e.clientX - startX; currentY = e.clientY - startY; applyTransform(); });
        document.addEventListener('mouseup', () => { isDragging = false; viewer.style.cursor = 'grab'; });
        viewer.addEventListener('touchstart', (e) => { isDragging = true; startX = e.touches[0].clientX - currentX; startY = e.touches[0].clientY - currentY; }, { passive: false });
        viewer.addEventListener('touchmove', (e) => { if (!isDragging) return; e.preventDefault(); currentX = e.touches[0].clientX - startX; currentY = e.touches[0].clientY - startY; applyTransform(); }, { passive: false });
        viewer.addEventListener('touchend', () => { isDragging = false; });

        function loadMainImage(index) {
            $('#viewerImage').attr('src', '../assets/img/product/' + imagesList[index]).show();
            $('#noImagePlaceholder').hide(); $('#viewerControls').show();
            $('.thumb-img').removeClass('active');
            $('.thumb-img[data-index="'+index+'"]').addClass('active');
            resetView();
        }

        function viewDetail(id) {
            $.ajax({
                url: '../get/get_sparepart_detail.php',
                type: 'GET', data: { id: id }, dataType: 'json',
                success: function(res) {
                    if(res.status === 'success') {
                        const data = res.data; imagesList = res.images;
                        $('#viewerImage').hide(); $('#viewerControls').hide(); $('#noImagePlaceholder').show(); resetView();
                        $('#detailName').text(data.name);
                        $('#detailCode').text(data.part_number);
                        $('#detailCategory').text(data.category_name || '-');
                        $('#detailLocation').text(data.location_name || '-');
                        $('#detailMaterialGroup').text(data.material_group_name || '-');
                        $('#detailStock').text(data.stock); $('#detailUnit').text(data.unit);
                        $('#detailPrice').text(parseInt(data.price).toLocaleString('id-ID'));
                        $('#detailStatus').html(data.status === 'active' ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>');
                        $('#detailDesc').text(data.description || '-');
                        if(imagesList.length > 0) { loadMainImage(0); let thumbs = ''; imagesList.forEach((img, i) => { thumbs += `<img src="../assets/img/product/${img}" class="thumb-img ${i===0 ? 'active' : ''}" data-index="${i}" onclick="loadMainImage(${i})">`; }); $('#thumbGallery').html(thumbs); } else { $('#thumbGallery').html(''); }
                        new bootstrap.Modal(document.getElementById('modalDetail')).show();
                    } else { Swal.fire('Error', res.msg, 'error'); }
                }, error: function() { Swal.fire('Error', 'Server Error', 'error'); }
            });
        }

        function editData(data) {
            $('#modalTitle').text('Edit Sparepart'); $('#formAction').val('edit'); $('#formId').val(data.id);
            $('#formPartNumber').val(data.part_number); $('#formName').val(data.name);
            $('#formStock').val(data.stock); $('#formMinStock').val(data.min_stock); 
            $('#formPrice').val(data.price); $('#formStatus').val(data.status); $('#formDesc').val(data.description);
            
            // Trigger Select2
            $('#formUnit').val(data.unit ? String(data.unit) : '').trigger('change');
            $('#formCategory').val(data.category_id ? String(data.category_id) : '').trigger('change');
            $('#formLocation').val(data.location_id ? String(data.location_id) : '').trigger('change');
            $('#formMaterialGroup').val(data.material_group_id ? String(data.material_group_id) : '').trigger('change');
            
            new bootstrap.Modal(document.getElementById('modalForm')).show();
        }

        function confirmDeleteSparepart(formId, itemName) {
            Swal.fire({ title: 'Hapus Data?', text: "Data \""+itemName+"\" akan dihapus permanen!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Ya, Hapus!', cancelButtonText: 'Batal', customClass: { confirmButton: 'btn btn-danger me-2', cancelButton: 'btn btn-secondary' }, buttonsStyling: false }).then((result) => { if (result.isConfirmed) { document.getElementById(formId).submit(); } });
        }
        
        document.getElementById('modalForm').addEventListener('hidden.bs.modal', function () {
            document.getElementById('modalTitle').innerText = 'Add New'; document.getElementById('formAction').value = 'add';
            this.querySelector('form').reset(); 
            $('.select2-modal').val('').trigger('change');
        });

        // Initialize Select2
        $(document).ready(function() {
            $('.select2-modal').select2({
                width: '100%',
                dropdownParent: $('#modalForm'),
                theme: 'default'
            });
        });
    </script>
</body>
</html>