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

require_once 'db.php';

$message = '';
$errorMsg = '';

// 1. Handle Form Submission to Add New Check Item
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_checklist'])) {
    require_csrf();

    $itemName     = trim($_POST['item_name'] ?? '');
    $category     = trim($_POST['category'] ?? 'LLG');
    $checkItemTxt = trim($_POST['check_item'] ?? '');
    $displayOrder = intval($_POST['display_order'] ?? 1);

    if (!empty($itemName) && !empty($checkItemTxt)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO tbl_master_checklists (item_name, Category, CheckItem, DisplayOrder, IsActive) VALUES (?, ?, ?, ?, 1)");
            $stmt->execute([$itemName, $category, $checkItemTxt, $displayOrder]);
            $message = "Checklist item successfully added for " . htmlspecialchars($itemName) . "!";
        } catch (\PDOException $e) {
            error_log('manage_checklists.php error: ' . $e->getMessage());
            $errorMsg = "A database error occurred while saving.";
        }
    } else {
        $errorMsg = "Item Name and Checklist Criteria text cannot be empty.";
    }
}

// 2. Handle Deletion of Checklist Item
if (isset($_GET['delete_id'])) {
    require_csrf();

    $delId = intval($_GET['delete_id']);
    try {
        $delStmt = $pdo->prepare("DELETE FROM tbl_master_checklists WHERE MasterCheckID = ?");
        $delStmt->execute([$delId]);
        header("Location: manage_checklists.php?deleted=1");
        exit;
    } catch (\PDOException $e) {
        error_log('manage_checklists.php delete error: ' . $e->getMessage());
        $errorMsg = "Error deleting item.";
    }
}

// 2b. Bulk import — same round-trip pattern as the Master Bank import:
// export → edit in Excel → re-import. Rows with a matching MasterCheckID
// UPDATE that row; rows with no ID (or an unmatched one) INSERT new.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_checklist'])) {
    require_csrf();

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

        $pdo->beginTransaction();
        try {
            while (($row = fgetcsv($handle)) !== false) {
                // Column order matches export_checklists.php exactly:
                // MasterCheckID, item_name, Category, CheckItem, DisplayOrder, IsActive
                $rowId = trim($row[0] ?? '');
                $rItemName = trim($row[1] ?? '');
                $rCategory = trim($row[2] ?? 'LLG');
                $rCheckItem = trim($row[3] ?? '');
                $rOrder = (int) ($row[4] ?? 1);
                $rActive = isset($row[5]) && (int) $row[5] === 1 ? 1 : 1;

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

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

                if ($exists) {
                    $upd = $pdo->prepare("UPDATE tbl_master_checklists SET item_name=?, Category=?, CheckItem=?, DisplayOrder=?, IsActive=? WHERE MasterCheckID=?");
                    $upd->execute([$rItemName, $rCategory, $rCheckItem, $rOrder, $rActive, $rowId]);
                    $updated++;
                } else {
                    $ins = $pdo->prepare("INSERT INTO tbl_master_checklists (item_name, Category, CheckItem, DisplayOrder, IsActive) VALUES (?, ?, ?, ?, ?)");
                    $ins->execute([$rItemName, $rCategory, $rCheckItem, $rOrder, $rActive]);
                    $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('manage_checklists.php import error: ' . $e->getMessage());
            $errorMsg = "Import failed — please check the file format matches the exported CSV exactly.";
        }
    } else {
        $errorMsg = "Please choose a CSV file to import.";
    }
}

// BUG FIX (found on live re-verification): $masterItems used to be fetched
// further down in this file (originally "section 3"), AFTER this 2c block —
// so referencing it here threw "Undefined variable $masterItems" +
// "foreach() argument must be of type array|object, null given" on every
// Import Simple List submission (visible as raw PHP warnings above the
// page). Moved the fetch here, before its first use. It's a cheap read with
// no dependency on anything above it, so moving it earlier is safe.
$masterItems = [];
try {
    $itemStmt = $pdo->query("SELECT DISTINCT item_name, category FROM tbl_master_items ORDER BY item_name ASC");
    $masterItems = $itemStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (\Exception $e) {}

// 2c. "Import Simple List" (docx item 8) — a single-column CSV/text file
// where each row is just the checklist item's text, with no MasterCheckID,
// Category, or DisplayOrder columns at all. Always APPENDS (never deletes or
// overwrites) to whichever equipment item is currently selected via the
// filter box above, auto-continuing the DisplayOrder sequence for that item.
// This is intentionally separate from the full 6-column export/re-import
// flow above (2b) — that one is for editing an existing checklist in Excel,
// this one is for a client who already just has a plain list of criteria.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_simple_list'])) {
    require_csrf();

    $targetItem = trim($_POST['simple_list_item_name'] ?? '');
    $skipHeader = isset($_POST['simple_list_skip_header']);

    if ($targetItem === '') {
        $errorMsg = "Select an equipment item above (using the search box) before importing a simple list.";
    } elseif (!isset($_FILES['simple_list_file']) || $_FILES['simple_list_file']['error'] !== UPLOAD_ERR_OK) {
        $errorMsg = "Please choose a CSV or text file to import.";
    } else {
        // Same category lookup already used by the "Add New Checklist Item" form.
        $targetCategory = 'LLG';
        foreach ($masterItems as $m) {
            if ($m['item_name'] === $targetItem) { $targetCategory = $m['category']; break; }
        }

        $handle = fopen($_FILES['simple_list_file']['tmp_name'], 'r');
        $added = 0;
        try {
            $pdo->beginTransaction();

            // Continue the DisplayOrder sequence for this item — never
            // renumbers or touches its existing rows.
            $maxStmt = $pdo->prepare("SELECT COALESCE(MAX(DisplayOrder), 0) FROM tbl_master_checklists WHERE item_name = ?");
            $maxStmt->execute([$targetItem]);
            $nextOrder = (int) $maxStmt->fetchColumn() + 1;

            $insStmt = $pdo->prepare("INSERT INTO tbl_master_checklists (item_name, Category, CheckItem, DisplayOrder, IsActive) VALUES (?, ?, ?, ?, 1)");

            $isFirstRow = true;
            while (($line = fgetcsv($handle)) !== false) {
                // Works for both a true one-column CSV and a plain .txt list —
                // fgetcsv() on a comma-free line just returns that whole line
                // as the single element $line[0].
                $text = trim($line[0] ?? '');
                $isFirstRowLocal = $isFirstRow;
                $isFirstRow = false;
                if ($skipHeader && $isFirstRowLocal) continue;
                if ($text === '') continue;

                $insStmt->execute([$targetItem, $targetCategory, $text, $nextOrder]);
                $nextOrder++;
                $added++;
            }
            fclose($handle);

            if ($added > 0) {
                $pdo->commit();
                $message = "Simple list import complete: {$added} checklist item(s) appended to \"" . htmlspecialchars($targetItem) . "\".";
            } else {
                $pdo->rollBack();
                $errorMsg = "The file had no usable rows to import.";
            }
        } catch (\PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            if (is_resource($handle)) fclose($handle);
            error_log('manage_checklists.php simple-list import error: ' . $e->getMessage());
            $errorMsg = "Import failed — please check the file.";
        }
    }
}

// Selected filter item from dropdown
$selectedItem = $_GET['item_filter'] ?? ($masterItems[0]['item_name'] ?? '');

// 4. Fetch existing checklist criteria for the selected item
$checklistCriteria = [];
if (!empty($selectedItem)) {
    try {
        $critStmt = $pdo->prepare("SELECT * FROM tbl_master_checklists WHERE item_name = ? ORDER BY DisplayOrder ASC");
        $critStmt->execute([$selectedItem]);
        $checklistCriteria = $critStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (\Exception $e) {}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Equipment Checklists</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 my-5" style="max-width: 1000px;">

    <!-- Top Header Bar -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold m-0 text-dark"><i class="fa-solid fa-list-check text-primary me-2"></i> Checklist Manager</h3>
            <small class="text-muted">Configure distinct Page 2 inspection criteria for each item name.</small>
        </div>
        <div>
            <a href="export_checklists.php" class="btn btn-success fw-bold me-2"><i class="fa-solid 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="#importChecklistModal"><i class="fa-solid fa-file-import me-1"></i> Import CSV</button>
            <button type="button" class="btn btn-outline-info fw-bold me-2" data-bs-toggle="modal" data-bs-target="#importSimpleListModal"><i class="fa-solid fa-list-ul me-1"></i> Import Simple List</button>
            <a href="index.php" class="btn btn-outline-dark btn-sm fw-bold"><i class="fa-solid fa-house me-1"></i> Back to Home</a>
        </div>
    </div>

    <!-- Import Modal -->
    <div class="modal fade" id="importChecklistModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="import_checklist" value="1">
                    <?php csrf_field(); ?>
                    <div class="modal-header">
                        <h5 class="modal-title">Import Checklist 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.</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>

    <!-- Import Simple List Modal (docx item 8) -->
    <div class="modal fade" id="importSimpleListModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="manage_checklists.php?item_filter=<?= urlencode($selectedItem); ?>" enctype="multipart/form-data">
                    <input type="hidden" name="import_simple_list" value="1">
                    <input type="hidden" name="simple_list_item_name" value="<?= htmlspecialchars($selectedItem); ?>">
                    <?php csrf_field(); ?>
                    <div class="modal-header">
                        <h5 class="modal-title">Import Simple Checklist List</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p class="small text-muted">
                            Upload a plain CSV or text file with <strong>one column</strong> — each row is just the
                            checklist item's text, nothing else. The items will be <strong>added</strong> to the
                            equipment currently selected above (<strong><?= htmlspecialchars($selectedItem ?: '— none selected —'); ?></strong>)
                            without touching any of its existing criteria. Select a different item above first if needed.
                        </p>
                        <?php if ($selectedItem === ''): ?>
                            <div class="alert alert-warning small py-2">Select an equipment item above first.</div>
                        <?php endif; ?>
                        <input type="file" name="simple_list_file" accept=".csv,.txt" class="form-control mb-2" required>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="simple_list_skip_header" id="simpleListSkipHeader">
                            <label class="form-check-label small" for="simpleListSkipHeader">First row is a header (skip it)</label>
                        </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-info fw-bold text-white" <?= $selectedItem === '' ? 'disabled' : ''; ?>>Import</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php if (!empty($_GET['deleted'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fa-solid fa-circle-check me-2"></i> Checklist item successfully removed.
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fa-solid fa-circle-check me-2"></i> <?= htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($errorMsg): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fa-solid fa-triangle-exclamation me-2"></i> <?= htmlspecialchars($errorMsg); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Filter by Item Name Form -->
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-body bg-white">
            <form method="GET" action="manage_checklists.php" class="row g-3 align-items-center">
                <div class="col-md-9 position-relative">
                    <label class="form-label small fw-bold text-muted">Select Equipment Item Name:</label>
                    <input type="text" id="itemSearchBox" class="form-control fw-bold text-primary" placeholder="Type to search, or click to browse..." autocomplete="off" value="<?= htmlspecialchars($selectedItem); ?>">
                    <input type="hidden" name="item_filter" id="itemFilterHidden" value="<?= htmlspecialchars($selectedItem); ?>">
                    <div id="itemSearchResults" class="list-group position-absolute w-100 shadow-sm" style="z-index: 1060; display:none; max-height: 280px; overflow-y: auto;"></div>
                </div>
                <div class="col-md-3 text-end pt-3">
                    <span class="badge bg-secondary fs-6 p-2"><?= count($checklistCriteria); ?> Criteria Found</span>
                </div>
            </form>

            <script>
            (function () {
                var allItems = <?= json_encode(array_map(fn($m) => ['name' => $m['item_name'], 'category' => $m['category']], $masterItems)); ?>;
                var input = document.getElementById('itemSearchBox');
                var hidden = document.getElementById('itemFilterHidden');
                var results = document.getElementById('itemSearchResults');

                function render(matches) {
                    if (!matches.length) {
                        results.innerHTML = '<div class="list-group-item text-muted small">No matching items.</div>';
                    } else {
                        results.innerHTML = matches.slice(0, 50).map(function (m) {
                            return '<button type="button" class="list-group-item list-group-item-action py-1 small">' +
                                   m.name.replace(/</g, '&lt;') + ' <span class="text-muted">(' + m.category + ')</span></button>';
                        }).join('');
                    }
                    results.style.display = 'block';
                }

                input.addEventListener('input', function () {
                    var q = input.value.trim().toLowerCase();
                    if (q.length < 1) { render(allItems); return; }
                    render(allItems.filter(function (m) { return m.name.toLowerCase().includes(q); }));
                });

                input.addEventListener('focus', function () {
                    if (!input.value.trim()) render(allItems);
                });

                results.addEventListener('click', function (e) {
                    var btn = e.target.closest('button');
                    if (!btn) return;
                    var name = btn.textContent.replace(/\s*\([^)]*\)\s*$/, '').trim();
                    input.value = name;
                    hidden.value = name;
                    results.style.display = 'none';
                    input.form.submit();
                });

                document.addEventListener('click', function (e) {
                    if (e.target !== input) results.style.display = 'none';
                });

                input.addEventListener('input', function () { hidden.value = input.value; });
            })();
            </script>
        </div>
    </div>

    <!-- Add New Checklist Criteria Form -->
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-header bg-primary text-white fw-bold">
            <i class="fa-solid fa-plus-circle me-1"></i> Add New Checklist Item for: <span class="text-warning"><?= htmlspecialchars($selectedItem); ?></span>
        </div>
        <div class="card-body bg-white">
            <form method="POST" action="manage_checklists.php?item_filter=<?= urlencode($selectedItem); ?>">
                <input type="hidden" name="add_checklist" value="1">
                <input type="hidden" name="item_name" value="<?= htmlspecialchars($selectedItem); ?>">
                <?php csrf_field(); ?>

                <?php
                // Determine category for this item
                $itemCat = 'LLG';
                foreach($masterItems as $m) {
                    if($m['item_name'] === $selectedItem) { $itemCat = $m['category']; break; }
                }
                ?>
                <input type="hidden" name="category" value="<?= htmlspecialchars($itemCat); ?>">

                <div class="row g-3">
                    <div class="col-md-9">
                        <label class="form-label small fw-bold">Inspection Criterion / Check Description</label>
                        <input type="text" name="check_item" class="form-control" placeholder="e.g., Thorough visual examination for cracks or deformation" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small fw-bold">Display Order #</label>
                        <input type="number" name="display_order" class="form-control" value="<?= count($checklistCriteria) + 1; ?>" required>
                    </div>
                    <div class="col-12 text-end">
                        <button type="submit" class="btn btn-success fw-bold px-4"><i class="fa-solid fa-save me-1"></i> Save Criterion</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Existing Checklist Items Table -->
    <div class="card shadow-sm border-0">
        <div class="card-header bg-dark text-white fw-bold">
            <i class="fa-solid fa-table-list me-1"></i> Current Checklist Items for <?= htmlspecialchars($selectedItem); ?>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped table-bordered m-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 8%;" class="text-center">Order</th>
                            <th style="width: 72%;">Check Item Description</th>
                            <th style="width: 10%;" class="text-center">Status</th>
                            <th style="width: 10%;" class="text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($checklistCriteria)): ?>
                            <?php foreach ($checklistCriteria as $c): ?>
                                <tr>
                                    <td class="text-center fw-bold"><?= htmlspecialchars($c['DisplayOrder']); ?></td>
                                    <td><?= htmlspecialchars($c['CheckItem']); ?></td>
                                    <td class="text-center">
                                        <span class="badge bg-success">Active</span>
                                    </td>
                                    <td class="text-center">
                                        <a href="manage_checklists.php?item_filter=<?= urlencode($selectedItem); ?>&amp;delete_id=<?= $c['MasterCheckID']; ?>&amp;csrf_token=<?= urlencode(csrf_token()); ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this criterion?');">
                                            <i class="fa-solid fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted py-4">
                                    <i class="fa-solid fa-circle-info me-1"></i> No checklist criteria added for <strong><?= htmlspecialchars($selectedItem); ?></strong> yet. Use the form above to add items!
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
