<?php
// Handle Create/Update/Delete Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add_category') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $description = $_POST['description'] ?? '';

            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO inventory_categories (name_en, name_ar, description) VALUES (?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $description]);
                $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('category_added_successfully') . '</div>';
            } else {
                $_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('fill_all_required_fields') . '</div>';
            }
        } elseif ($_POST['action'] === 'delete_category') {
            $id = $_POST['id'] ?? 0;
            // Check if used
            $stmt = $db->prepare("SELECT COUNT(*) FROM inventory_items WHERE category_id = ?");
            $stmt->execute([$id]);
            if ($stmt->fetchColumn() > 0) {
                $_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('cannot_delete_category_in_use') . '</div>';
            } else {
                $stmt = $db->prepare("DELETE FROM inventory_categories WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('category_deleted_successfully') . '</div>';
            }
        } elseif ($_POST['action'] === 'edit_category') {
             $id = $_POST['id'] ?? 0;
             $name_en = $_POST['name_en'] ?? '';
             $name_ar = $_POST['name_ar'] ?? '';
             $description = $_POST['description'] ?? '';
             
             if ($name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE inventory_categories SET name_en = ?, name_ar = ?, description = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $description, $id]);
                $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('category_updated_successfully') . '</div>';
             }
        }
        
        // Redirect to avoid resubmission
        header("Location: inventory_categories.php");
        exit;
    }
}

// Fetch Categories
$categories = $db->query("SELECT * FROM inventory_categories ORDER BY id DESC")->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_categories'); ?></h2>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
        <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_category'); ?>
    </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>#</th>
                        <th><?php echo __('name_en'); ?></th>
                        <th><?php echo __('name_ar'); ?></th>
                        <th><?php echo __('description'); ?></th>
                        <th class="text-end"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($categories)): ?>
                    <tr>
                        <td colspan="5" class="text-center py-4 text-muted"><?php echo __('no_data_available'); ?></td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($categories as $cat): ?>
                        <tr>
                            <td><?php echo $cat['id']; ?></td>
                            <td><?php echo htmlspecialchars($cat['name_en']); ?></td>
                            <td><?php echo htmlspecialchars($cat['name_ar']); ?></td>
                            <td><?php echo htmlspecialchars($cat['description'] ?? ''); ?></td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary me-1" 
                                        onclick="editCategory(<?php echo htmlspecialchars(json_encode($cat)); ?>)">
                                    <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_category">
                                    <input type="hidden" name="id" value="<?php echo $cat['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 Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo __('add_category'); ?></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_category">
                    <div class="mb-3">
                        <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="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                        <input type="text" name="name_ar" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('description'); ?></label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </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 Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo __('edit_category'); ?></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_category">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="mb-3">
                        <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="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                        <input type="text" name="name_ar" id="edit_name_ar" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('description'); ?></label>
                        <textarea name="description" id="edit_description" class="form-control" rows="3"></textarea>
                    </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 editCategory(cat) {
    document.getElementById('edit_id').value = cat.id;
    document.getElementById('edit_name_en').value = cat.name_en;
    document.getElementById('edit_name_ar').value = cat.name_ar;
    document.getElementById('edit_description').value = cat.description || '';
    
    var myModal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
    myModal.show();
}
</script>
