<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/admin_layout.php';

library_bootstrap();

$errors = [];

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    try {
        if ($action === 'create_category') {
            $nameEn = trim($_POST['name_en'] ?? '');
            $nameAr = trim($_POST['name_ar'] ?? '');
            if (!$nameEn || !$nameAr) {
                throw new RuntimeException('Both English and Arabic names are required for Category.');
            }
            library_create_category($nameEn, $nameAr);
            library_set_flash('success', 'Category created successfully.');
            header('Location: /admin_categories.php');
            exit;
        } elseif ($action === 'update_category') {
            $nameEn = trim($_POST['name_en'] ?? '');
            $nameAr = trim($_POST['name_ar'] ?? '');
            if (!$id || !$nameEn || !$nameAr) {
                throw new RuntimeException('ID, English name, and Arabic name are required.');
            }
            library_update_category($id, $nameEn, $nameAr);
            library_set_flash('success', 'Category updated successfully.');
            header('Location: /admin_categories.php');
            exit;
        } elseif ($action === 'delete_category') {
            if (!$id) {
                throw new RuntimeException('Invalid Category ID.');
            }
            library_delete_category($id);
            library_set_flash('success', 'Category deleted successfully.');
            header('Location: /admin_categories.php');
            exit;
        }
    } catch (Throwable $exception) {
        $errors[] = $exception->getMessage();
    }
}

// Search Logic
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$categories = library_get_categories($search);

admin_render_header('Categories', 'categories');
?>
<!-- Page Content -->
<?php if ($errors): ?>
    <div class="alert alert-danger"><?= h(implode(' ', $errors)) ?></div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <p class="text-secondary mb-0">Manage document categories.</p>
    <button class="btn btn-primary" onclick="openCreateCategoryModal()">
        <i class="bi bi-plus-lg me-1"></i> Add New Category
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form method="get" action="/admin_categories.php" class="row g-2 align-items-center">
            <div class="col-auto flex-grow-1">
                <input type="text" name="search" class="form-control" placeholder="Search categories..." value="<?= h($search) ?>">
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-outline-primary">
                    <i class="bi bi-search"></i> Search
                </button>
                <?php if ($search): ?>
                    <a href="/admin_categories.php" class="btn btn-outline-secondary">Clear</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-4">Name</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($categories)): ?>
                        <tr><td colspan="2" class="text-center py-5 text-muted">No categories found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($categories as $cat): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="fw-medium text-dark"><?= h($cat['name_en']) ?></div>
                                    <small class="text-muted"><?= h($cat['name_ar']) ?></small>
                                </td>
                                <td class="text-end pe-4">
                                    <button class="btn btn-sm btn-outline-secondary me-1" 
                                            data-id="<?= $cat['id'] ?>"
                                            data-name-en="<?= h($cat['name_en']) ?>"
                                            data-name-ar="<?= h($cat['name_ar']) ?>"
                                            onclick="openEditCategoryModal(this)">
                                        <i class="bi bi-pencil"></i> Edit
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteCategory(<?= $cat['id'] ?>)">
                                        <i class="bi bi-trash"></i> Delete
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Category Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post" action="/admin_categories.php" id="categoryForm">
        <input type="hidden" name="action" id="cat_action" value="create_category">
        <input type="hidden" name="id" id="cat_id" value="">
        <div class="modal-header">
            <h5 class="modal-title" id="categoryModalTitle">Add New Category</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <div class="mb-3">
                <label class="form-label">Name (English)</label>
                <div class="input-group">
                    <input type="text" class="form-control" name="name_en" id="cat_name_en" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="translateText('cat_name_en', 'cat_name_ar', 'Arabic')" title="Translate to Arabic">
                        <i class="bi bi-translate"></i>
                    </button>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Name (Arabic)</label>
                <div class="input-group">
                    <input type="text" class="form-control" name="name_ar" id="cat_name_ar" dir="rtl" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="translateText('cat_name_ar', 'cat_name_en', 'English')" title="Translate to English">
                        <i class="bi bi-translate"></i>
                    </button>
                </div>
            </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-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Delete Confirmation Form -->
<form method="post" action="/admin_categories.php" id="deleteForm">
    <input type="hidden" name="action" id="deleteAction" value="">
    <input type="hidden" name="id" id="deleteId" value="">
</form>

<script>
    let categoryModal;

    document.addEventListener('DOMContentLoaded', function() {
        categoryModal = new bootstrap.Modal(document.getElementById('categoryModal'));
    });

    function openCreateCategoryModal() {
        document.getElementById('categoryModalTitle').innerText = 'Add New Category';
        document.getElementById('cat_action').value = 'create_category';
        document.getElementById('cat_id').value = '';
        document.getElementById('cat_name_en').value = '';
        document.getElementById('cat_name_ar').value = '';
        categoryModal.show();
    }

    function openEditCategoryModal(btn) {
        const id = btn.getAttribute('data-id');
        const nameEn = btn.getAttribute('data-name-en');
        const nameAr = btn.getAttribute('data-name-ar');

        document.getElementById('categoryModalTitle').innerText = 'Edit Category';
        document.getElementById('cat_action').value = 'update_category';
        document.getElementById('cat_id').value = id;
        document.getElementById('cat_name_en').value = nameEn;
        document.getElementById('cat_name_ar').value = nameAr;
        categoryModal.show();
    }

    function deleteCategory(id) {
        if (confirm('Are you sure you want to delete this category? All related subcategories will also be deleted.')) {
            document.getElementById('deleteAction').value = 'delete_category';
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteForm').submit();
        }
    }
</script>

<?php admin_render_footer(); ?>