<?php
require_once 'includes/auth.php';
require_role(['admin', 'inspector']);

require_once 'db.php';

$message = '';

// Handle Save/Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_item'])) {
    require_csrf();

    $id        = $_POST['id'] ?? null;
    $itemName  = $_POST['item_name'];
    $category  = $_POST['category'];
    $period    = $_POST['certificate_period_months'];
    $standards = $_POST['reference_standards'];
    $procedure = $_POST['inspection_procedure'];
    $desc      = $_POST['description_template'];
    $currentUserId = current_user()['id'] ?? null;

    if ($id) {
        $stmt = $pdo->prepare("UPDATE tbl_master_items SET item_name=?, category=?, certificate_period_months=?, reference_standards=?, inspection_procedure=?, description_template=?, updated_by=? WHERE id=?");
        $stmt->execute([$itemName, $category, $period, $standards, $procedure, $desc, $currentUserId, $id]);
        $message = "Item updated successfully!";
    } else {
        $stmt = $pdo->prepare("INSERT INTO tbl_master_items (item_name, category, certificate_period_months, reference_standards, inspection_procedure, description_template, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$itemName, $category, $period, $standards, $procedure, $desc, $currentUserId]);
        $message = "New item added to Master Bank!";
    }
}

// Pagination & Search Setup
$limit = 25; // Items per page
$page  = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$search = $_GET['search'] ?? '';

// Count Total Records
$countSql = "SELECT COUNT(*) FROM tbl_master_items WHERE item_name LIKE ? OR category LIKE ?";
$stmtCount = $pdo->prepare($countSql);
$stmtCount->execute(["%$search%", "%$search%"]);
$totalItems = $stmtCount->fetchColumn();
$totalPages = ceil($totalItems / $limit);

// Fetch Paginated Records
// HARDENING: $limit/$offset were confirmed integer-safe already (not
// exploitable), but string-interpolating them into SQL is a pattern that
// invites a real vulnerability the next time this code is edited. Bound
// as real parameters instead, with explicit PARAM_INT typing.
$sql = "SELECT * FROM tbl_master_items WHERE item_name LIKE ? OR category LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, "%$search%", PDO::PARAM_STR);
$stmt->bindValue(2, "%$search%", PDO::PARAM_STR);
$stmt->bindValue(3, $limit, PDO::PARAM_INT);
$stmt->bindValue(4, $offset, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Master Item Bank - Liftek</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container-fluid py-4 px-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold text-primary"><i class="fa-solid fa-database me-2"></i> Master Item Bank Management</h3>
        <a href="index.php" class="btn btn-outline-secondary"><i class="fa-solid fa-arrow-left me-1"></i> Dashboard</a>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($message); ?></div>
    <?php endif; ?>

    <div class="row">
        <!-- Search & Table Column -->
        <div class="col-md-7">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-body">
                    <form method="GET" action="manage_items.php" class="d-flex mb-3">
                        <input type="text" name="search" class="form-control me-2" placeholder="Search Item or Category..." value="<?= htmlspecialchars($search); ?>">
                        <button class="btn btn-primary"><i class="fa-solid fa-search"></i></button>
                    </form>

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <small class="text-muted fw-bold">Total Items Found: <?= number_format($totalItems); ?></small>
                        <small class="text-muted">Page <?= $page; ?> of <?= max(1, $totalPages); ?></small>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle small">
                            <thead class="table-dark">
                                <tr>
                                    <th>Item Name</th>
                                    <th>Category</th>
                                    <th>Period</th>
                                    <th>Standards</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (count($items) > 0): ?>
                                    <?php foreach ($items as $item): ?>
                                        <tr>
                                            <td class="fw-bold"><?= htmlspecialchars($item['item_name']); ?></td>
                                            <td><span class="badge bg-info text-dark"><?= htmlspecialchars($item['category']); ?></span></td>
                                            <td><?= $item['certificate_period_months']; ?> Months</td>
                                            <td><?= htmlspecialchars($item['reference_standards'] ?? '-'); ?></td>
                                            <td>
                                                <button onclick='editItem(<?= json_encode($item); ?>)' class="btn btn-sm btn-outline-primary"><i class="fa-solid fa-pen"></i> Edit</button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="text-center text-muted py-3">No master items found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination Links -->
                    <?php if ($totalPages > 1): ?>
                        <nav class="mt-3">
                            <ul class="pagination pagination-sm justify-content-center m-0">
                                <li class="page-item <?= ($page <= 1) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?search=<?= urlencode($search); ?>&amp;page=<?= $page - 1; ?>">Previous</a>
                                </li>

                                <?php
                                $startPage = max(1, $page - 2);
                                $endPage   = min($totalPages, $page + 2);
                                for ($i = $startPage; $i <= $endPage; $i++):
                                ?>
                                    <li class="page-item <?= ($page == $i) ? 'active' : ''; ?>">
                                        <a class="page-link" href="?search=<?= urlencode($search); ?>&amp;page=<?= $i; ?>"><?= $i; ?></a>
                                    </li>
                                <?php endfor; ?>

                                <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?search=<?= urlencode($search); ?>&amp;page=<?= $page + 1; ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>

                </div>
            </div>
        </div>

        <!-- Add / Edit Form Column -->
        <div class="col-md-5">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-primary text-white fw-bold" id="formTitle">Add New Master Item</div>
                <div class="card-body">
                    <form method="POST" action="manage_items.php">
                        <input type="hidden" name="save_item" value="1">
                        <input type="hidden" name="id" id="itemId">
                        <?php csrf_field(); ?>

                        <div class="mb-2">
                            <label class="form-label small fw-bold">Item Name</label>
                            <input type="text" name="item_name" id="itemName" class="form-control" required>
                        </div>

                        <div class="row">
                            <div class="col-6 mb-2">
                                <label class="form-label small fw-bold">Category</label>
                                <select name="category" id="itemCategory" class="form-select">
                                    <option value="LLG">LLG</option>
                                    <option value="Appliance">Appliance</option>
                                    <option value="Training">Training</option>
                                    <option value="Misc">Misc</option>
                                </select>
                            </div>
                            <div class="col-6 mb-2">
                                <label class="form-label small fw-bold">Validity Period</label>
                                <select name="certificate_period_months" id="itemPeriod" class="form-select">
                                    <option value="6">6 Months</option>
                                    <option value="12">12 Months</option>
                                    <option value="24">24 Months</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold">Reference Standard</label>
                            <textarea name="reference_standards" id="itemStandards" class="form-control" rows="2"></textarea>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold">Inspection Procedure</label>
                            <input type="text" name="inspection_procedure" id="itemProcedure" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label class="form-label small fw-bold" id="descLabel">Required Details / Training Content</label>
                            <textarea name="description_template" id="itemDesc" class="form-control" rows="5" placeholder="For Training: Course Topics&#10;For Others: Required Certificate Fields"></textarea>
                        </div>

                        <div class="d-flex justify-content-between">
                            <button type="button" onclick="resetForm()" class="btn btn-secondary">Reset</button>
                            <button type="submit" class="btn btn-primary fw-bold">Save Master Item</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function editItem(item) {
    document.getElementById('formTitle').innerText = 'Edit Master Item: ' + item.item_name;
    document.getElementById('itemId').value = item.id;
    document.getElementById('itemName').value = item.item_name;
    document.getElementById('itemCategory').value = item.category;
    document.getElementById('itemPeriod').value = item.certificate_period_months;
    document.getElementById('itemStandards').value = item.reference_standards || '';
    document.getElementById('itemProcedure').value = item.inspection_procedure || '';
    document.getElementById('itemDesc').value = item.description_template || '';
    updateLabel(item.category);
}

function resetForm() {
    document.getElementById('formTitle').innerText = 'Add New Master Item';
    document.getElementById('itemId').value = '';
    document.getElementById('itemName').value = '';
    document.getElementById('itemStandards').value = '';
    document.getElementById('itemProcedure').value = '';
    document.getElementById('itemDesc').value = '';
}

document.getElementById('itemCategory').addEventListener('change', function() {
    updateLabel(this.value);
});

function updateLabel(category) {
    const label = document.getElementById('descLabel');
    if (category === 'Training') {
        label.innerText = "Course Topics & Content (Training Module)";
    } else {
        label.innerText = "Required Details on Certificate";
    }
}
</script>
</body>
</html>
