<?php
/**
 * Admin - Item Management
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../lib/ExcelExport.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
admin_only();

$pageTitle = 'Item Management';
$db = Database::getInstance();

// Search & Filter (initialized early so export handler can use them)
$search = trim($_GET['search'] ?? '');
$category = $_GET['category'] ?? '';
$status = $_GET['status'] ?? '';
$page = max(1, (int) ($_GET['page'] ?? 1));

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    $action = $_POST['action'] ?? '';

    if ($action === 'export') {
        $format = $_POST['format'] ?? 'csv';
        $exporter = new ExcelExport();
        $exporter->setTitle('Items Export');
        $exporter->setFilename('items');

        // Fetch all items (or apply current filters)
        $where = '1=1';
        $params = [];
        if ($search) {
            $where .= " AND (Item_Code LIKE ? OR Item_Description LIKE ? OR Stores LIKE ?)";
            $params = array_merge($params, ["%$search%", "%$search%", "%$search%"]);
        }
        if ($category) {
            $where .= " AND Item_Group = ?";
            $params[] = $category;
        }
        if ($status) {
            $where .= " AND Status = ?";
            $params[] = $status;
        }
        $exportItems = $db->fetchAll("SELECT * FROM items WHERE $where ORDER BY Item_Code ASC", $params);

$exporter->setHeaders(['Item Code', 'Item Description', 'Item Group', 'Stores', 'Rack', 'Level', 'Bin', 'UOM', 'System Qty', 'Status', 'Image Path']);
        foreach ($exportItems as $item) {
            $exporter->addRow([
                $item['Item_Code'],
                $item['Item_Description'] ?? '',
                $item['Item_Group'] ?? '',
                $item['Stores'] ?? '',
                $item['Rack'] ?? '',
                $item['Level'] ?? '',
                $item['Bin'] ?? '',
                $item['Uom'] ?? 'pcs',
                $item['System_Qty'],
                $item['Status'],
                $item['image_path'] ?? ''
            ]);
        }

        if ($format === 'xlsx') {
            $exporter->downloadXLSX();
        } elseif ($format === 'csv') {
            $exporter->downloadCSV();
        } elseif ($format === 'json') {
            if (ob_get_level()) ob_clean();
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="items_' . date('Ymd_His') . '.json"');
            header('Pragma: no-cache');
            header('Cache-Control: private, no-cache, no-store, must-revalidate');
            echo json_encode($exportItems, JSON_PRETTY_PRINT);
            exit;
        }
    } elseif ($action === 'import') {
        if (isset($_FILES['import_file']) && $_FILES['import_file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['import_file'];
            if ($file['size'] > UPLOAD_MAX_SIZE) {
                set_error('File too large. Max ' . (UPLOAD_MAX_SIZE / 1024 / 1024) . 'MB.');
            } else {
                $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                if (!in_array($ext, ['csv', 'xlsx'])) {
                    set_error('Only CSV or XLSX files are allowed.');
                } else {
                    $db->beginTransaction();
                    try {
                        $imported = 0;

                        if ($ext === 'xlsx') {
                            $rows = ExcelExport::readXLSX($file['tmp_name'], true);
                        } else {
                            $rows = ExcelExport::readCSV($file['tmp_name'], true);
                        }

                        foreach ($rows as $row) {
                            if (count($row) < 2) continue;
                            $item_code = trim((string)($row[0] ?? ''));
                            if (empty($item_code)) continue;

                            $data = [
                                'Item_Code' => $item_code,
                                'Item_Description' => trim((string)($row[1] ?? '')),
                                'Item_Group' => trim((string)($row[2] ?? '')),
                                'Stores' => trim((string)($row[3] ?? '')),
                                'Rack' => trim((string)($row[4] ?? '')),
                                'Level' => trim((string)($row[5] ?? '')),
                                'Bin' => trim((string)($row[6] ?? '')),
                                'Uom' => trim((string)($row[7] ?? 'pcs')),
                                'System_Qty' => (float) ($row[8] ?? 0),
                                'Status' => trim((string)($row[9] ?? 'Active')),
                                'image_path' => trim((string)($row[10] ?? null)),
                            ];

                            $existing = $db->fetchColumn('SELECT id FROM items WHERE Item_Code = ?', [$item_code]);
                            if ($existing) {
                                $db->update('items', $data, 'Item_Code = ?', [$item_code]);
                                log_action(SessionManager::getUserId(), 'update', 'items', $existing, $data);
                            } else {
                                $db->insert('items', $data);
                                log_action(SessionManager::getUserId(), 'create', 'items', $db->fetchColumn("SELECT LAST_INSERT_ID()"), $data);
                            }
                            $imported++;
                        }

                        $db->commit();
                        set_success("$imported items imported/updated successfully.");
                    } catch (Exception $e) {
                        $db->rollBack();
                        set_error('Import failed: ' . $e->getMessage());
                    }
                }
            }
        } else {
            set_error('No file uploaded or upload error.');
        }
    } elseif ($action === 'add') {
        $data = [
            'Item_Code' => trim($_POST['item_code'] ?? ''),
            'Item_Description' => trim($_POST['item_description'] ?? ''),
            'Item_Group' => trim($_POST['item_group'] ?? ''),
            'Stores' => trim($_POST['stores'] ?? ''),
            'Rack' => trim($_POST['rack'] ?? ''),
            'Level' => trim($_POST['level'] ?? ''),
            'Bin' => trim($_POST['bin'] ?? ''),
            'Uom' => trim($_POST['uom'] ?? 'pcs'),
            'System_Qty' => (float) ($_POST['system_qty'] ?? 0),
            'Status' => 'Active',
            'image_path' => null,
        ];

        // Handle image upload
        $image_path = upload_image('item_image');
        if ($image_path !== false) {
            $data['image_path'] = $image_path;
        }

        // Validate required fields
        if (empty($data['Item_Code'])) {
            set_error('Item Code is required.');
        } else {
            $existing = $db->fetchColumn('SELECT id FROM items WHERE Item_Code = ?', [$data['Item_Code']]);
            if ($existing) {
                set_error('Item Code already exists.');
            } else {
                $id = $db->insert('items', $data);
                log_action(SessionManager::getUserId(), 'create', 'items', $id, $data);
                set_success('Item created successfully.');
            }
        }
    } elseif ($action === 'update') {
        $id = (int) ($_POST['item_id'] ?? 0);
        $existing_item = $db->fetch('SELECT image_path FROM items WHERE id = ?', [$id]);
        $data = [
            'Item_Code' => trim($_POST['item_code'] ?? ''),
            'Item_Description' => trim($_POST['item_description'] ?? ''),
            'Item_Group' => trim($_POST['item_group'] ?? ''),
            'Stores' => trim($_POST['stores'] ?? ''),
            'Rack' => trim($_POST['rack'] ?? ''),
            'Level' => trim($_POST['level'] ?? ''),
            'Bin' => trim($_POST['bin'] ?? ''),
            'Uom' => trim($_POST['uom'] ?? 'pcs'),
            'System_Qty' => (float) ($_POST['system_qty'] ?? 0),
        ];

        // Handle image upload/replace
        $image_path = upload_image('item_image');
        if ($image_path !== false) {
            // Delete old image if exists
            if ($existing_item['image_path']) {
                delete_image($existing_item['image_path']);
            }
            $data['image_path'] = $image_path;
        }

        if (empty($data['Item_Code'])) {
            set_error('Item Code is required.');
        } else {
            $db->update('items', $data, 'id = ?', [$id]);
            log_action(SessionManager::getUserId(), 'update', 'items', $id, $data);
            set_success('Item updated successfully.');
        }
    } elseif ($action === 'delete_image') {
        $id = (int) ($_POST['item_id'] ?? 0);
        $item = $db->fetch('SELECT image_path FROM items WHERE id = ?', [$id]);
        if ($item && $item['image_path']) {
            delete_image($item['image_path']);
            $db->update('items', ['image_path' => null], 'id = ?', [$id]);
            log_action(SessionManager::getUserId(), 'delete_image', 'items', $id);
            set_success('Item image removed.');
        } else {
            set_error('No image found.');
        }
    } elseif ($action === 'delete') {
        $id = (int) ($_POST['item_id'] ?? 0);
        $item = $db->fetch('SELECT image_path FROM items WHERE id = ?', [$id]);
        if ($item && $item['image_path']) {
            delete_image($item['image_path']);
        }
        $db->delete('items', 'id = ?', [$id]);
        log_action(SessionManager::getUserId(), 'delete', 'items', $id);
        set_success('Item deleted.');
    } elseif ($action === 'toggle_status') {
        $id = (int) ($_POST['item_id'] ?? 0);
        $item = $db->fetch("SELECT Status FROM items WHERE id = ?", [$id]);
        if ($item) {
            $newStatus = $item['Status'] === 'Active' ? 'Inactive' : 'Active';
            $db->update('items', ['Status' => $newStatus], 'id = ?', [$id]);
            set_success('Item status updated to ' . $newStatus . '.');
        }
    }

    redirect(APP_URL . '/admin/items.php');
}

// Build query for listing
$where = '1=1';
$params = [];
if ($search) {
    $where .= " AND (Item_Code LIKE ? OR Item_Description LIKE ? OR Stores LIKE ?)";
    $params = array_merge($params, ["%$search%", "%$search%", "%$search%"]);
}
if ($category) {
    $where .= " AND Item_Group = ?";
    $params[] = $category;
}
if ($status) {
    $where .= " AND Status = ?";
    $params[] = ucfirst($status);
}

$total = $db->fetchColumn("SELECT COUNT(*) FROM items WHERE $where", $params);
$pagination = new Pagination($total, ITEMS_PER_PAGE, $page);
$items = $db->fetchAll("SELECT id, Item_Code as item_code, Item_Description as description, Item_Group as category, Stores, Rack, Level, Bin, Uom as unit_of_measure, System_Qty as system_quantity, Status as status, image_path FROM items WHERE $where ORDER BY Item_Code ASC LIMIT {$pagination->getLimit()} OFFSET {$pagination->getOffset()}", $params);
$categories = $db->fetchAll("SELECT DISTINCT Item_Group as category FROM items WHERE Item_Group IS NOT NULL AND Item_Group != '' ORDER BY Item_Group");

include APP_ROOT . '/templates/header.php';
?>

<!-- Add Item Modal -->
<div class="modal-overlay" id="addItemModal">
    <div class="modal">
        <div class="modal-header">
            <h3>Add New Item</h3>
            <button class="modal-close" onclick="closeModal('addItemModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST" id="addItemForm">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="add">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Item Code *</label>
                        <input type="text" name="item_code" class="form-control" required placeholder="e.g., ITM-001">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Item Description</label>
                        <input type="text" name="item_description" class="form-control" placeholder="Item description">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Item Group</label>
                        <input type="text" name="item_group" class="form-control" placeholder="e.g., Electronics">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Stores</label>
                        <input type="text" name="stores" class="form-control" placeholder="e.g., Warehouse A">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Rack</label>
                        <input type="text" name="rack" class="form-control" placeholder="e.g., R1">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Level</label>
                        <input type="text" name="level" class="form-control" placeholder="e.g., L2">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Bin</label>
                        <input type="text" name="bin" class="form-control" placeholder="e.g., B3">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Unit of Measure</label>
                        <input type="text" name="uom" class="form-control" value="pcs">
                    </div>
                    <div class="form-group">
                        <label class="form-label">System Quantity</label>
                        <input type="number" name="system_qty" class="form-control" step="0.01" value="0">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Item Image</label>
                    <input type="file" name="item_image" class="form-control" accept="image/*">
                    <small class="form-hint">JPG, PNG, GIF, WebP, SVG (max 2MB)</small>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Create Item</button>
                    <button type="button" class="btn btn-outline" onclick="closeModal('addItemModal')">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Item Modal -->
<div class="modal-overlay" id="editItemModal">
    <div class="modal">
        <div class="modal-header">
            <h3>Edit Item</h3>
            <button class="modal-close" onclick="closeModal('editItemModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST" id="editItemForm">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="item_id" id="edit_item_id">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Item Code *</label>
                        <input type="text" name="item_code" id="edit_item_code" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Item Description</label>
                        <input type="text" name="item_description" id="edit_item_description" class="form-control">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Item Group</label>
                        <input type="text" name="item_group" id="edit_item_group" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Stores</label>
                        <input type="text" name="stores" id="edit_stores" class="form-control">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Rack</label>
                        <input type="text" name="rack" id="edit_rack" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Level</label>
                        <input type="text" name="level" id="edit_level" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Bin</label>
                        <input type="text" name="bin" id="edit_bin" class="form-control">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Unit of Measure</label>
                        <input type="text" name="uom" id="edit_uom" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">System Quantity</label>
                        <input type="number" name="system_qty" id="edit_system_qty" class="form-control" step="0.01">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Item Image</label>
                    <input type="file" name="item_image" id="edit_item_image" class="form-control" accept="image/*">
                    <small class="form-hint">JPG, PNG, GIF, WebP, SVG (max 2MB) - leave empty to keep current</small>
                    <div id="current_item_image" style="margin-top:10px;"></div>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Update Item</button>
                    <button type="button" class="btn btn-outline" onclick="closeModal('editItemModal')">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Import Modal -->
<div class="modal-overlay" id="importModal">
    <div class="modal">
        <div class="modal-header">
            <h3>Import Items from CSV/XLSX</h3>
            <button class="modal-close" onclick="closeModal('importModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST" enctype="multipart/form-data">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="import">
                <div class="form-group">
                    <label class="form-label">File * <small>(CSV or XLSX)</small></label>
                    <input type="file" name="import_file" class="form-control" accept=".csv,.xlsx" required>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Import</button>
                    <button type="button" class="btn btn-outline" onclick="closeModal('importModal')">Cancel</button>
                </div>
            </form>
            <div style="margin-top:15px;font-size:0.85rem;color:#666">
                <strong>Expected columns:</strong> Item Code, Item Description, Item Group, Stores, Rack, Level, Bin, UOM, System Qty, Status<br>
                <strong>Sample:</strong> ITM001, Dell Laptop, Electronics, Warehouse A, R1, L2, B3, pcs, 50, Active
            </div>
        </div>
    </div>
</div>

<div class="toolbar" style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
    <form method="GET" class="toolbar-left" style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
        <div class="search-box">
            <input type="text" name="search" class="form-control" placeholder="Search items..." value="<?= e($search) ?>">
        </div>
        <select name="category" class="form-control" style="width:auto">
            <option value="">All Categories</option>
            <?php foreach ($categories as $cat): ?>
            <option value="<?= e($cat['category']) ?>" <?= $category === $cat['category'] ? 'selected' : '' ?>><?= e($cat['category']) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="status" class="form-control" style="width:auto">
            <option value="">All Status</option>
            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Inactive</option>
        </select>
        <button type="submit" class="btn btn-outline">Filter</button>
    </form>

    <!-- Export -->
    <form method="POST" style="display:inline" class="export-form">
        <?= Csrf::field() ?>
        <input type="hidden" name="action" value="export">
        <select name="format" class="form-control" style="width:auto;font-size:0.85rem;padding:6px">
            <option value="xlsx">XLSX (Excel)</option>
            <option value="csv">CSV (Excel)</option>
            <option value="json">JSON</option>
        </select>
        <button type="submit" class="btn btn-success" title="Export filtered results"><i>&#11015;</i> Export</button>
    </form>

<!-- Import Modal Trigger -->
    <button type="button" class="btn btn-info" onclick="openModal('importModal')" title="Import from CSV/XLSX">
        <i>&#11014;</i> Import
    </button>
    <button class="btn btn-primary" onclick="openAddModal()">+ Add Item</button>
</div>

<div class="card">
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Image</th>
                    <th>Item Code</th>
                    <th>Item Description</th>
                    <th>Item Group</th>
                    <th>Stores</th>
                    <th>Rack</th>
                    <th>Level</th>
                    <th>Bin</th>
                    <th>UOM</th>
                    <th>System Qty</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($items)): ?>
                <tr><td colspan="11" class="text-center text-muted" style="padding:40px">No items found.</td></tr>
                <?php else: foreach ($items as $item): ?>
                <tr>
                    <td style="width:60px;"><?= item_image_thumbnail($item['image_path'], 40, 40) ?></td>
                    <td><strong><?= e($item['item_code']) ?></strong></td>
                    <td><?= e($item['description'] ?: '-') ?></td>
                    <td><?= e($item['category'] ?: '-') ?></td>
                    <td><?= format_location($item['Stores'], $item['Rack'], $item['Level'], $item['Bin']) ?></td>
                    <td><?= e($item['Rack'] ?: '-') ?></td>
                    <td><?= e($item['Level'] ?: '-') ?></td>
                    <td><?= e($item['Bin'] ?: '-') ?></td>
                    <td><?= e($item['unit_of_measure']) ?></td>
                    <td><strong><?= format_number($item['system_quantity']) ?></strong></td>
                    <td><?= status_badge($item['status']) ?></td>
                    <td>
                        <div class="table-actions">
                            <button type="button" class="btn btn-sm btn-outline-primary" title="Edit"
                                onclick="openEditModal(<?= (int)$item['id'] ?>, '<?= e($item['item_code']) ?>', '<?= e($item['description']) ?>', '<?= e($item['category']) ?>', '<?= e($item['Stores']) ?>', '<?= e($item['Rack']) ?>', '<?= e($item['Level']) ?>', '<?= e($item['Bin']) ?>', '<?= e($item['unit_of_measure']) ?>', '<?= e((string)$item['system_quantity']) ?>', '<?= e($item['image_path'] ?? '') ?>')">&#9998;</button>
                            <form method="POST" style="display:inline">
                                <?= Csrf::field() ?>
                                <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                                <input type="hidden" name="action" value="toggle_status">
                                <button type="submit" class="btn btn-sm <?= $item['status']==='Active'?'btn-warning':'btn-success' ?>" title="Toggle Status">
                                    <?= $item['status']==='Active'?'&#9632;':'&#9658;' ?>
                                </button>
                            </form>
                            <form method="POST" style="display:inline" onsubmit="return confirm('Delete this item?')">
                                <?= Csrf::field() ?>
                                <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                                <input type="hidden" name="action" value="delete">
                                <button type="submit" class="btn btn-sm btn-danger" title="Delete">&#128465;</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($pagination->getTotalPages() > 1): ?>
    <div class="card-footer"><?= $pagination->render(get_current_url()) ?></div>
    <?php endif; ?>
</div>

<script>
function openModal(id) {
    document.getElementById(id).style.display = 'flex';
}
function closeModal(id) {
    document.getElementById(id).style.display = 'none';
}
function openAddModal() {
    document.getElementById('addItemForm').reset();
    openModal('addItemModal');
}
function openEditModal(id, code, description, group, stores, rack, level, bin, uom, qty, image_path) {
    document.getElementById('edit_item_id').value = id;
    document.getElementById('edit_item_code').value = code;
    document.getElementById('edit_item_description').value = description;
    document.getElementById('edit_item_group').value = group;
    document.getElementById('edit_stores').value = stores;
    document.getElementById('edit_rack').value = rack;
    document.getElementById('edit_level').value = level;
    document.getElementById('edit_bin').value = bin;
    document.getElementById('edit_uom').value = uom;
    document.getElementById('edit_system_qty').value = qty;
    const currentImg = document.getElementById('current_item_image');
    if (image_path) {
        currentImg.innerHTML = `Current: <a href="${APP_URL}/${image_path}" target="_blank">View Image</a> | <button type="button" onclick="deleteCurrentImage(${id})" class="btn btn-sm btn-danger">Remove</button>`;
    } else {
        currentImg.innerHTML = '';
    }
    openModal('editItemModal');
}

function deleteCurrentImage(id) {
    if (confirm('Remove this item image?')) {
        fetch(`${APP_URL}/admin/items.php`, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `action=delete_image&item_id=${id}&${document.querySelector('[name=csrf_token]').value}`
        }).then(() => location.reload());
    }
}
</script>

<?php include APP_ROOT . '/templates/footer.php'; ?>
