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

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

// Query dengan perhitungan kapasitas terpakai
 $stmt = $pdo->query("
    SELECT l.*, 
           COALESCE(SUM(s.stock), 0) as used_capacity,
           (l.max_capacity - COALESCE(SUM(s.stock), 0)) as remaining_capacity
    FROM locations l
    LEFT JOIN spareparts s ON l.id = s.location_id
    GROUP BY l.id
    ORDER BY l.name ASC
");
 $locations = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!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 Links -->
    <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">
    
    <style>
        /* Custom Progress Bar Styling for Dark Theme */
        .progress {
            background-color: var(--input-bg);
            border-radius: 8px;
            height: 10px;
            overflow: hidden;
        }
        .progress-bar {
            transition: width 0.6s ease;
        }
        .progress-low { background: linear-gradient(90deg, #00d26a, #00a854); }
        .progress-mid { background: linear-gradient(90deg, #ffc107, #ff9800); }
        .progress-high { background: linear-gradient(90deg, #ff5252, #e94560); }

        /* ==========================================
           FIX: TOMBOL AKSI ANTI-MENUMPUK
           ========================================== */
        .action-buttons {
            display: flex !important;
            flex-wrap: nowrap !important; /* Memaksa tombol tetap di 1 baris */
            gap: 4px;
            align-items: center;
            justify-content: center;
        }
        
        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
            line-height: 1.2;
            white-space: nowrap; /* Mencegah teks dalam tombol patah */
        }

        /* FIX: Konten Tabel Tidak Menumpuk */
        .table td {
            vertical-align: middle; /* Konten selalu di tengah vertikal */
        }
        
        /* Mencegah teks di kolom lain patah/stacking aneh */
        .table td, .table th {
            white-space: nowrap;
        }
        
        /* Khusus kolom Capacity Status, izinkan wrap karena isinya kompleks */
        .table td.capacity-col {
            white-space: normal;
            min-width: 200px; /* Lebar minimal agar progress bar bagus */
        }
    </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>
        
        <!-- Include Sidebar -->
        <?php include 'includes/sidebar.php'; ?>
        
        <main class="main-content">
            <!-- Include Header -->
            <?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]['locations'] ?></p>
                    </div>
                    
                    <?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 class="card fade-in">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table data-table">
                                <thead>
                                    <tr>
                                        <th width="50">No</th>
                                        <th><?= $lang[$current_lang]['location_code'] ?></th>
                                        <th><?= $lang[$current_lang]['name'] ?></th>
                                        <th><?= $lang[$current_lang]['building'] ?></th>
                                        <th><?= $lang[$current_lang]['area'] ?></th>
                                        <th class="capacity-col"><?= $lang[$current_lang]['capacity_status'] ?></th>
                                        <th width="100" class="text-center"><?= $lang[$current_lang]['action'] ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $no=1; foreach($locations as $row): 
                                        $used = $row['used_capacity'];
                                        $max = $row['max_capacity'];
                                        $percent = ($max > 0) ? round(($used / $max) * 100) : 0;
                                        
                                        // Tentukan warna progress bar
                                        $progress_class = 'progress-low';
                                        if($percent > 50 && $percent <= 80) $progress_class = 'progress-mid';
                                        if($percent > 80) $progress_class = 'progress-high';
                                    ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><strong><?= htmlspecialchars($row['code']) ?></strong></td>
                                        <td><?= htmlspecialchars($row['name']) ?></td>
                                        <td><?= htmlspecialchars($row['building']) ?></td>
                                        <td><?= htmlspecialchars($row['area']) ?></td>
                                        <td class="capacity-col">
                                            <div class="d-flex justify-content-between mb-1 small">
                                                <span><?= $lang[$current_lang]['used_capacity'] ?>: <strong><?= number_format($used) ?></strong></span>
                                                <span class="text-muted"><?= $lang[$current_lang]['max_capacity'] ?>: <?= number_format($max) ?></span>
                                            </div>
                                            <div class="progress" title="<?= $percent ?>% Filled">
                                                <div class="progress-bar <?= $progress_class ?>" role="progressbar" style="width: <?= $percent ?>%" aria-valuenow="<?= $percent ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                            </div>
                                            <div class="text-end small mt-1">
                                                <?php if($percent >= 100): ?>
                                                    <span class="text-danger fw-bold"><?= $lang[$current_lang]['full'] ?></span>
                                                <?php else: ?>
                                                    <span class="text-success"><?= $lang[$current_lang]['remaining_capacity'] ?>: <strong><?= number_format($row['remaining_capacity']) ?></strong></span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ($_SESSION['role'] == 'admin'): ?>
                                            <!-- Tambahkan wrapper action-buttons di sini -->
                                            <div class="action-buttons">
                                                <button class="btn btn-sm btn-secondary" onclick="editData(<?= htmlspecialchars(json_encode($row)) ?>)" title="Edit">
                                                    <i class="mdi mdi-pencil"></i>
                                                </button>
                                                <form action="../post/material_location_action.php" method="POST" class="d-inline" onsubmit="return confirmDelete(this)">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger btn-delete" title="Delete">
                                                        <i class="mdi mdi-trash-can"></i>
                                                    </button>
                                                </form>
                                            </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Modal Add/Edit -->
            <div class="modal fade" id="modalForm" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="modalTitle"><?= $lang[$current_lang]['add_location'] ?></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <form action="../post/material_location_action.php" method="POST">
                            <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]['location_code'] ?></label>
                                        <input type="text" name="code" id="formCode" class="form-control" required placeholder="e.g: WH-A1">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label"><?= $lang[$current_lang]['name'] ?></label>
                                        <input type="text" name="name" id="formName" class="form-control" required placeholder="e.g: Rak A1">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label"><?= $lang[$current_lang]['building'] ?></label>
                                        <input type="text" name="building" id="formBuilding" class="form-control" placeholder="Building A">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label"><?= $lang[$current_lang]['floor'] ?></label>
                                        <input type="text" name="floor" id="formFloor" class="form-control" placeholder="1">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label"><?= $lang[$current_lang]['area'] ?></label>
                                        <input type="text" name="area" id="formArea" class="form-control" placeholder="North">
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label"><?= $lang[$current_lang]['max_capacity'] ?></label>
                                    <input type="number" name="max_capacity" id="formCapacity" class="form-control" required placeholder="100" min="1">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label"><?= $lang[$current_lang]['status'] ?></label>
                                    <select name="status" id="formStatus" class="form-select">
                                        <option value="active"><?= $lang[$current_lang]['active'] ?></option>
                                        <option value="inactive"><?= $lang[$current_lang]['inactive'] ?></option>
                                    </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>
            
            <?php include 'includes/footer.php'; ?>
        </main>
    </div>
    
    <script>
        function editData(data) {
            document.getElementById('modalTitle').innerText = '<?= $lang[$current_lang]['edit_location'] ?>';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('formId').value = data.id;
            document.getElementById('formCode').value = data.code;
            document.getElementById('formName').value = data.name;
            document.getElementById('formBuilding').value = data.building;
            document.getElementById('formFloor').value = data.floor;
            document.getElementById('formArea').value = data.area;
            document.getElementById('formCapacity').value = data.max_capacity;
            document.getElementById('formStatus').value = data.status;
            
            var modal = new bootstrap.Modal(document.getElementById('modalForm'));
            modal.show();
        }
        
        document.getElementById('modalForm').addEventListener('hidden.bs.modal', function () {
            document.getElementById('modalTitle').innerText = '<?= $lang[$current_lang]['add_location'] ?>';
            document.getElementById('formAction').value = 'add';
            document.getElementById('formId').value = '';
            document.getElementById('formCode').value = '';
            document.getElementById('formName').value = '';
            document.getElementById('formBuilding').value = '';
            document.getElementById('formFloor').value = '';
            document.getElementById('formArea').value = '';
            document.getElementById('formCapacity').value = '';
            document.getElementById('formStatus').value = 'active';
        });

        function confirmDelete(form) {
            event.preventDefault();
            Swal.fire({
                title: '<?= $lang[$current_lang]['confirm_delete'] ?>',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel',
                customClass: { confirmButton: 'btn btn-danger me-2', cancelButton: 'btn btn-secondary' },
                buttonsStyling: false
            }).then((result) => {
                if (result.isConfirmed) { form.submit(); }
            });
            return false;
        }
    </script>
</body>
</html>