<?php
// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add_item') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $category_id = $_POST['category_id'] ?? null;
            $sku = $_POST['sku'] ?? '';
            $unit = $_POST['unit'] ?? 'piece';
            $min_level = $_POST['min_level'] ?? 10;
            $reorder_level = $_POST['reorder_level'] ?? 20;
            $description = $_POST['description'] ?? '';

            if ($name_en && $category_id) {
                try {
                    $stmt = $db->prepare("INSERT INTO inventory_items (name_en, name_ar, category_id, sku, unit, min_level, reorder_level, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$name_en, $name_ar, $category_id, $sku, $unit, $min_level, $reorder_level, $description]);
                    $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('item_added_successfully') . '</div>';
                } catch (PDOException $e) {
                    $_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('error_adding_item') . ': ' . $e->getMessage() . '</div>';
                }
            } else {
                $_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('fill_all_required_fields') . '</div>';
            }
        } elseif ($_POST['action'] === 'edit_item') {
            $id = $_POST['id'] ?? 0;
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $category_id = $_POST['category_id'] ?? null;
            $sku = $_POST['sku'] ?? '';
            $unit = $_POST['unit'] ?? 'piece';
            $min_level = $_POST['min_level'] ?? 10;
            $reorder_level = $_POST['reorder_level'] ?? 20;
            $description = $_POST['description'] ?? '';

            if ($name_en && $category_id) {
                try {
                    $stmt = $db->prepare("UPDATE inventory_items SET name_en = ?, name_ar = ?, category_id = ?, sku = ?, unit = ?, min_level = ?, reorder_level = ?, description = ? WHERE id = ?");
                    $stmt->execute([$name_en, $name_ar, $category_id, $sku, $unit, $min_level, $reorder_level, $description, $id]);
                    $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('item_updated_successfully') . '</div>';
                } catch (PDOException $e) {
                    $_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('error_updating_item') . ': ' . $e->getMessage() . '</div>';
                }
            }
        } elseif ($_POST['action'] === 'delete_item') {
            $id = $_POST['id'] ?? 0;
            // Check usage
            $stmt = $db->prepare("SELECT COUNT(*) FROM inventory_batches WHERE item_id = ? AND quantity > 0");
            $stmt->execute([$id]);
            if ($stmt->fetchColumn() > 0) {
                $_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('cannot_delete_item_with_stock') . '</div>';
            } else {
                $stmt = $db->prepare("DELETE FROM inventory_items WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('item_deleted_successfully') . '</div>';
            }
        }
        header("Location: inventory_items.php");
        exit;
    }
}

// Fetch Items with Stock
$items = $db->query("
    SELECT i.*, c.name_en as category_name, 
    COALESCE((SELECT SUM(quantity) FROM inventory_batches b WHERE b.item_id = i.id), 0) as current_stock 
    FROM inventory_items i 
    LEFT JOIN inventory_categories c ON i.category_id = c.id 
    ORDER BY i.name_en ASC
")->fetchAll(PDO::FETCH_ASSOC);

// Fetch Categories for Dropdown
$categories = $db->query("SELECT * FROM inventory_categories ORDER BY name_en ASC")->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="mb-0 fw-bold text-dark"><?php echo __('inventory_items'); ?></h2>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addItemModal">
        <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_item'); ?>
    </button>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr>
                        <th><?php echo __('sku'); ?></th>
                        <th><?php echo __('item_name'); ?></th>
                        <th><?php echo __('category'); ?></th>
                        <th><?php echo __('unit'); ?></th>
                        <th><?php echo __('min_level'); ?></th>
                        <th><?php echo __('current_stock'); ?></th>
                        <th class="text-end"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($items)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4 text-muted"><?php echo __('no_items_found'); ?></td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($items as $item): ?>
                        <tr class="<?php echo ($item['current_stock'] <= $item['min_level']) ? 'table-warning' : ''; ?>">
                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars($item['sku'] ?? '-'); ?></span></td>
                            <td>
                                <div class="fw-bold"><?php echo htmlspecialchars($item['name_en']); ?></div>
                                <small class="text-muted"><?php echo htmlspecialchars($item['name_ar']); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($item['category_name'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($item['unit']); ?></td>
                            <td><?php echo $item['min_level']; ?></td>
                            <td>
                                <?php if ($item['current_stock'] == 0): ?>
                                    <span class="badge bg-danger"><?php echo __('out_of_stock'); ?></span>
                                <?php elseif ($item['current_stock'] <= $item['min_level']): ?>
                                    <span class="badge bg-warning text-dark"><?php echo $item['current_stock']; ?> (Low)</span>
                                <?php else: ?>
                                    <span class="badge bg-success"><?php echo $item['current_stock']; ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary me-1" 
                                        onclick='editItem(<?php echo json_encode($item, JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <form method="POST" class="d-inline" onsubmit="return confirm('<?php echo __('are_you_sure'); ?>');">
                                    <input type="hidden" name="action" value="delete_item">
                                    <input type="hidden" name="id" value="<?php echo $item['id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Item Modal -->
<div class="modal fade" id="addItemModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo __('add_item'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_item">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                            <input type="text" name="name_en" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_ar'); ?></label>
                            <input type="text" name="name_ar" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('category'); ?> <span class="text-danger">*</span></label>
                            <select name="category_id" class="form-select" required>
                                <option value=""><?php echo __('select_category'); ?></option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name_en']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('sku'); ?></label>
                            <input type="text" name="sku" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('unit'); ?></label>
                            <input type="text" name="unit" class="form-control" value="piece">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('min_level'); ?></label>
                            <input type="number" name="min_level" class="form-control" value="10">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('reorder_level'); ?></label>
                            <input type="number" name="reorder_level" class="form-control" value="20">
                        </div>
                        <div class="col-12">
                            <label class="form-label"><?php echo __('description'); ?></label>
                            <textarea name="description" class="form-control" rows="2"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Item Modal -->
<div class="modal fade" id="editItemModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo __('edit_item'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit_item">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                            <input type="text" name="name_en" id="edit_name_en" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_ar'); ?></label>
                            <input type="text" name="name_ar" id="edit_name_ar" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('category'); ?> <span class="text-danger">*</span></label>
                            <select name="category_id" id="edit_category_id" class="form-select" required>
                                <option value=""><?php echo __('select_category'); ?></option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name_en']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('sku'); ?></label>
                            <input type="text" name="sku" id="edit_sku" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('unit'); ?></label>
                            <input type="text" name="unit" id="edit_unit" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('min_level'); ?></label>
                            <input type="number" name="min_level" id="edit_min_level" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('reorder_level'); ?></label>
                            <input type="number" name="reorder_level" id="edit_reorder_level" class="form-control">
                        </div>
                        <div class="col-12">
                            <label class="form-label"><?php echo __('description'); ?></label>
                            <textarea name="description" id="edit_description" class="form-control" rows="2"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('update'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editItem(item) {
    document.getElementById('edit_id').value = item.id;
    document.getElementById('edit_name_en').value = item.name_en;
    document.getElementById('edit_name_ar').value = item.name_ar;
    document.getElementById('edit_category_id').value = item.category_id;
    document.getElementById('edit_sku').value = item.sku || '';
    document.getElementById('edit_unit').value = item.unit || 'piece';
    document.getElementById('edit_min_level').value = item.min_level;
    document.getElementById('edit_reorder_level').value = item.reorder_level;
    document.getElementById('edit_description').value = item.description || '';
    
    var myModal = new bootstrap.Modal(document.getElementById('editItemModal'));
    myModal.show();
}
</script>
