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

require_once 'db.php';

$message = '';
$error = '';

// Handle form submission for adding or updating a master item
// FIX (docx item 1): this handler used to run on EVERY POST with no field
// discriminator, so a CSV-import POST (handled separately below, and with
// no `item_name` field of its own) also fell through into this block, hit
// the empty-name `else`, and set "Item name cannot be empty." — which then
// displayed ALONGSIDE the real "Import complete" success message from the
// import handler, making a working import look broken. Scoped to its own
// hidden field, matching the pattern already used by the CSV-import block
// (`import_csv`) right below it.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_master_item'])) {
    require_csrf();

    $itemId           = $_POST['item_id'] ?? '';
    $itemName         = trim($_POST['item_name'] ?? '');
    $category         = trim($_POST['category'] ?? 'LLG');
    $certPeriod       = intval($_POST['certificate_period_months'] ?? 6);
    $refStandards     = trim($_POST['reference_standards'] ?? '');
    $inspectionProc   = trim($_POST['inspection_procedure'] ?? '');
    $descriptionTemp  = trim($_POST['description_template'] ?? '');
    $currentUserId    = current_user()['id'] ?? null;

    if (!empty($itemName)) {
        try {
            if (!empty($itemId)) {
                // Update existing item
                $sql = "UPDATE tbl_master_items
                        SET item_name = ?, category = ?, certificate_period_months = ?, reference_standards = ?, inspection_procedure = ?, description_template = ?, updated_by = ?
                        WHERE id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$itemName, $category, $certPeriod, $refStandards, $inspectionProc, $descriptionTemp, $currentUserId, $itemId]);
                $message = "Master item updated successfully!";
            } else {
                // Insert new item
                $sql = "INSERT INTO tbl_master_items (item_name, category, certificate_period_months, reference_standards, inspection_procedure, description_template, created_at, created_by)
                        VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$itemName, $category, $certPeriod, $refStandards, $inspectionProc, $descriptionTemp, $currentUserId]);
                $message = "New master item added successfully!";
            }
        } catch (\PDOException $e) {
            error_log('master_items.php error: ' . $e->getMessage());
            $error = "A database error occurred while saving.";
        }
    } else {
        $error = "Item name cannot be empty.";
    }
}

// Handle bulk import (CSV upload) — matches the export format exactly, so
// export → edit in Excel → re-import round-trips cleanly. Rows with an
// `id` present UPDATE that row; rows with no `id` (or an id that doesn't
// exist) INSERT a new one. Nothing outside the touched rows is affected.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    require_csrf();

    if (isset($_FILES['import_file']) && $_FILES['import_file']['error'] === UPLOAD_ERR_OK) {
        $handle = fopen($_FILES['import_file']['tmp_name'], 'r');
        $header = fgetcsv($handle); // skip header row
        $imported = 0;
        $updated = 0;

        $pdo->beginTransaction();
        $currentUserId = current_user()['id'] ?? null;
        try {
            while (($row = fgetcsv($handle)) !== false) {
                // Expected column order matches export_master_items.php exactly:
                // id, item_name, category, certificate_period_months, reference_standards, inspection_procedure, description_template
                $rowId = trim($row[0] ?? '');
                $rItemName = trim($row[1] ?? '');
                $rCategory = trim($row[2] ?? 'LLG');
                $rPeriod = (int) ($row[3] ?? 6);
                $rStandards = $row[4] ?? '';
                $rProcedure = $row[5] ?? '';
                $rDesc = $row[6] ?? '';

                if ($rItemName === '') continue;

                $exists = false;
                if ($rowId !== '') {
                    $chk = $pdo->prepare("SELECT id FROM tbl_master_items WHERE id = ?");
                    $chk->execute([$rowId]);
                    $exists = (bool) $chk->fetchColumn();
                }

                if ($exists) {
                    $upd = $pdo->prepare(
                        "UPDATE tbl_master_items SET item_name=?, category=?, certificate_period_months=?, reference_standards=?, inspection_procedure=?, description_template=?, updated_by=? WHERE id=?"
                    );
                    $upd->execute([$rItemName, $rCategory, $rPeriod, $rStandards, $rProcedure, $rDesc, $currentUserId, $rowId]);
                    $updated++;
                } else {
                    $ins = $pdo->prepare(
                        "INSERT INTO tbl_master_items (item_name, category, certificate_period_months, reference_standards, inspection_procedure, description_template, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)"
                    );
                    $ins->execute([$rItemName, $rCategory, $rPeriod, $rStandards, $rProcedure, $rDesc, $currentUserId]);
                    $imported++;
                }
            }
            $pdo->commit();
            fclose($handle);
            $message = "Import complete: {$imported} new item(s) added, {$updated} existing item(s) updated.";
        } catch (\PDOException $e) {
            $pdo->rollBack();
            fclose($handle);
            error_log('master_items.php import error: ' . $e->getMessage());
            $error = "Import failed — please check the file format matches the exported CSV exactly.";
        }
    } else {
        $error = "Please choose a CSV file to import.";
    }
}

// Fetch all master items for the searchable dropdown
try {
    $items = $pdo->query("SELECT * FROM tbl_master_items ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
    $items = [];
    $error = "Could not fetch items.";
}

// Registry table: paginated + searchable, separate from the full $items
// array above (which stays intact for the dropdown/edit-select).
$regSearch = trim($_GET['reg_search'] ?? '');
$regPage = isset($_GET['reg_page']) && is_numeric($_GET['reg_page']) ? (int) $_GET['reg_page'] : 1;
if ($regPage < 1) $regPage = 1;
$regLimit = 25;
$regOffset = ($regPage - 1) * $regLimit;

$regCountStmt = $pdo->prepare("SELECT COUNT(*) FROM tbl_master_items WHERE item_name LIKE ? OR category LIKE ?");
$regCountStmt->execute(["%$regSearch%", "%$regSearch%"]);
$regTotal = (int) $regCountStmt->fetchColumn();
$regTotalPages = max(1, (int) ceil($regTotal / $regLimit));

$regStmt = $pdo->prepare("SELECT * FROM tbl_master_items WHERE item_name LIKE ? OR category LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?");
$regStmt->bindValue(1, "%$regSearch%", PDO::PARAM_STR);
$regStmt->bindValue(2, "%$regSearch%", PDO::PARAM_STR);
$regStmt->bindValue(3, $regLimit, PDO::PARAM_INT);
$regStmt->bindValue(4, $regOffset, PDO::PARAM_INT);
$regStmt->execute();
$registryItems = $regStmt->fetchAll(PDO::FETCH_ASSOC);

// Handle selected item to load into the edit form
$selectedItemId = $_GET['select_item_id'] ?? null;
$editItem = [
    'id' => '',
    'item_name' => '',
    'category' => 'LLG',
    'certificate_period_months' => 6,
    'reference_standards' => '',
    'inspection_procedure' => '',
    'description_template' => ''
];

if ($selectedItemId) {
    foreach ($items as $itm) {
        if ($itm['id'] == $selectedItemId) {
            $editItem = $itm;
            break;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
    
    <title>Master Bank - Items Control</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Select2 CSS for Searchable Dropdown -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
</head>
<body class="bg-light">

<div class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-database me-2"></i> Master Bank Control Panel</h2>
        <div>
            <a href="export_master_items.php" class="btn btn-success fw-bold me-2"><i class="fas fa-file-export me-1"></i> Export CSV</a>
            <button type="button" class="btn btn-outline-primary fw-bold me-2" data-bs-toggle="modal" data-bs-target="#importModal"><i class="fas fa-file-import me-1"></i> Import CSV</button>
            <a href="index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to Dashboard</a>
        </div>
    </div>

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

    <!-- Registry: browsable table of all items, like the main jobs register -->
    <div class="card shadow-sm mb-4 border-0">
        <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-table-list me-2"></i> Item Registry (<?= number_format($regTotal); ?> Total)</h5>
        </div>
        <div class="card-body">
            <form method="GET" action="master_items.php" class="mb-3">
                <div class="input-group">
                    <input type="text" name="reg_search" class="form-control" placeholder="Search registry by item name or category..." value="<?= htmlspecialchars($regSearch); ?>">
                    <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button>
                    <?php if ($regSearch !== ''): ?><a href="master_items.php" class="btn btn-outline-secondary">Clear</a><?php endif; ?>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-hover table-sm align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th><th>Item Name</th><th>Category</th><th>Period</th><th>Standards</th><th class="text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($registryItems)): ?>
                            <tr><td colspan="6" class="text-center text-muted py-3">No items found.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($registryItems as $ri): ?>
                            <tr>
                                <td class="text-muted small">#<?= (int) $ri['id']; ?></td>
                                <td class="fw-bold"><?= htmlspecialchars($ri['item_name']); ?></td>
                                <td><span class="badge bg-info text-dark"><?= htmlspecialchars($ri['category']); ?></span></td>
                                <td><?= (int) $ri['certificate_period_months']; ?> Mos</td>
                                <td class="small text-muted"><?= htmlspecialchars(mb_strimwidth($ri['reference_standards'] ?? '-', 0, 60, '...')); ?></td>
                                <td class="text-center">
                                    <a href="master_items.php?select_item_id=<?= (int) $ri['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-pen"></i> Edit</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($regTotalPages > 1): ?>
                <nav>
                    <ul class="pagination pagination-sm justify-content-center m-0">
                        <li class="page-item <?= $regPage <= 1 ? 'disabled' : ''; ?>">
                            <a class="page-link" href="?reg_search=<?= urlencode($regSearch); ?>&amp;reg_page=<?= $regPage - 1; ?>">Previous</a>
                        </li>
                        <?php for ($i = max(1, $regPage - 2); $i <= min($regTotalPages, $regPage + 2); $i++): ?>
                            <li class="page-item <?= $regPage == $i ? 'active' : ''; ?>">
                                <a class="page-link" href="?reg_search=<?= urlencode($regSearch); ?>&amp;reg_page=<?= $i; ?>"><?= $i; ?></a>
                            </li>
                        <?php endfor; ?>
                        <li class="page-item <?= $regPage >= $regTotalPages ? 'disabled' : ''; ?>">
                            <a class="page-link" href="?reg_search=<?= urlencode($regSearch); ?>&amp;reg_page=<?= $regPage + 1; ?>">Next</a>
                        </li>
                    </ul>
                </nav>
            <?php endif; ?>
        </div>
    </div>

    <!-- Import Modal -->
    <div class="modal fade" id="importModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="import_csv" value="1">
                    <?php csrf_field(); ?>
                    <div class="modal-header">
                        <h5 class="modal-title">Import Master Bank CSV</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p class="small text-muted">Use a file exported from "Export CSV" — edit it in Excel, then upload it here. Rows with a matching ID update that item; rows with no ID add a new one. Nothing else in the system is affected.</p>
                        <input type="file" name="import_file" accept=".csv" class="form-control" required>
                    </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 fw-bold">Import</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Search / Select Existing Master Item -->
    <div class="card shadow-sm mb-4 border-0">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-search me-2"></i> Search Item to Edit (<?= count($items) ?> Total)</h5>
        </div>
        <div class="card-body">
            <form method="GET" action="master_items.php" class="row g-3 align-items-center">
                <div class="col-md-10">
                    <select class="form-select select2-search" name="select_item_id" onchange="this.form.submit()">
                        <option value="">-- Search & Select an Item to Edit --</option>
                        <?php foreach ($items as $item): ?>
                            <option value="<?= $item['id'] ?>" <?= ($selectedItemId == $item['id']) ? 'selected' : '' ?>>
                                [ID: <?= $item['id'] ?>] <?= htmlspecialchars($item['item_name']) ?> (<?= htmlspecialchars($item['category']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <a href="master_items.php" class="btn btn-outline-secondary w-100"><i class="fas fa-plus me-1"></i> New Item</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Add / Edit Master Item Form -->
    <div class="card shadow-sm mb-5 border-0">
        <div class="card-header <?= $editItem['id'] ? 'bg-warning text-dark' : 'bg-dark text-white' ?>">
            <h5 class="mb-0">
                <i class="fas <?= $editItem['id'] ? 'fa-edit' : 'fa-plus-circle' ?> me-2"></i>
                <?= $editItem['id'] ? 'Edit Master Item (ID: ' . $editItem['id'] . ')' : 'Add New Master Item' ?>
            </h5>
        </div>
        <div class="card-body">
            <form action="master_items.php" method="POST">
                <input type="hidden" name="item_id" value="<?= htmlspecialchars($editItem['id']) ?>">
                <input type="hidden" name="save_master_item" value="1">
                <?php csrf_field(); ?>

                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Item Name</label>
                        <input type="text" class="form-control" name="item_name" value="<?= htmlspecialchars($editItem['item_name']) ?>" required placeholder="e.g., Mobile Crane">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Category</label>
                        <select class="form-select" name="category">
                            <option value="LLG" <?= ($editItem['category'] == 'LLG') ? 'selected' : '' ?>>LLG (Lifting Gear)</option>
                            <option value="Appliance" <?= (strcasecmp($editItem['category'], 'Appliance') == 0) ? 'selected' : '' ?>>Appliance (Heavy Equipment)</option>
                            <option value="Misc" <?= ($editItem['category'] == 'Misc') ? 'selected' : '' ?>>Misc</option>
                            <option value="Training" <?= ($editItem['category'] == 'Training') ? 'selected' : '' ?>>Training</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Cert. Period (Months)</label>
                        <input type="number" class="form-control" name="certificate_period_months" value="<?= htmlspecialchars($editItem['certificate_period_months']) ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Reference Standards</label>
                        <input type="text" class="form-control" name="reference_standards" value="<?= htmlspecialchars($editItem['reference_standards']) ?>" placeholder="e.g., BS 7121-1:2016">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Inspection Procedure</label>
                        <input type="text" class="form-control" name="inspection_procedure" value="<?= htmlspecialchars($editItem['inspection_procedure']) ?>" placeholder="e.g., Liftek - IQ - 001">
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-bold">Description Template</label>
                        <textarea class="form-control font-monospace" name="description_template" rows="7"><?= htmlspecialchars($editItem['description_template']) ?></textarea>
                    </div>
                    <div class="col-12 d-flex justify-content-between">
                        <?php if ($editItem['id']): ?>
                            <a href="master_items.php" class="btn btn-outline-secondary">Cancel Edit</a>
                        <?php else: ?>
                            <div></div>
                        <?php endif; ?>
                        <button type="submit" class="btn btn-success px-4"><i class="fas fa-save me-1"></i> <?= $editItem['id'] ? 'Update Master Item' : 'Save to Master Bank' ?></button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- BUG FIX (admin report, 2026-08-25): "Import CSV button doesn't work."
     Root cause: this page loads Bootstrap's CSS (see <head>) but never
     loaded Bootstrap's JS bundle — so data-bs-toggle="modal" on the
     "Import CSV" button (and Bootstrap's own modal component in general)
     had no JavaScript behind it at all and silently did nothing on click,
     no error, no console warning a non-technical user would ever see.
     Confirmed live: clicking Import CSV before this fix opened nothing.
     Added the same Bootstrap JS bundle (same 5.3.0 version already used
     for the CSS here, and the same CDN URL every other page in this app
     already uses, e.g. index.php) — must load before Select2 below, since
     Select2's Bootstrap 5 theme also expects Bootstrap's JS to be present. -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- jQuery and Select2 JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('.select2-search').select2({
        theme: 'bootstrap-5',
        width: '100%',
        placeholder: 'Search items by name or ID...'
    });
});
</script>

</body>
</html>
