<?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(library_trans('category_name_required'));
            }
            library_create_category($nameEn, $nameAr);
            library_set_flash('success', library_trans('category_created_success'));
            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(library_trans('category_update_required'));
            }
            library_update_category($id, $nameEn, $nameAr);
            library_set_flash('success', library_trans('category_updated_success'));
            header('Location: /admin_categories.php');
            exit;
        } elseif ($action === 'delete_category') {
            if (!$id) {
                throw new RuntimeException(library_trans('invalid_category_id'));
            }
            library_delete_category($id);
            library_set_flash('success', library_trans('category_deleted_success'));
            header('Location: /admin_categories.php');
            exit;
        }
    } catch (Throwable $exception) {
        $errors[] = $exception->getMessage();
    }
}

// Search & Pagination Logic
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$result = library_get_categories_paginated($search, $limit, $offset);
$categories = $result['data'];
$totalCategories = $result['total'];
$totalPages = (int)ceil($totalCategories / $limit);
$lang = library_get_language();

admin_render_header(library_trans('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"><?= library_trans('manage_categories_desc') ?></p>
    <button class="btn btn-primary" onclick="openCreateCategoryModal()">
        <i class="bi bi-plus-lg me-1"></i> <?= library_trans('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="<?= library_trans('search_placeholder') ?>" value="<?= h($search) ?>">
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-outline-primary">
                    <i class="bi bi-search"></i> <?= library_trans('search') ?>
                </button>
                <?php if ($search): ?>
                    <a href="/admin_categories.php" class="btn btn-outline-secondary"><?= library_trans('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"><?= library_trans('name') ?></th>
                        <th class="text-end pe-4"><?= library_trans('actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($categories)): ?>
                        <tr><td colspan="2" class="text-center py-5 text-muted"><?= library_trans('no_categories_found') ?></td></tr>
                    <?php else: ?>
                        <?php foreach ($categories as $cat): ?>
                            <tr>
                                <td class="ps-4">
                                    <?php $categoryName = library_localized_value($cat['name_en'] ?? null, $cat['name_ar'] ?? null, $lang); ?>
                                    <div class="fw-medium text-dark" dir="<?= library_text_dir($categoryName, $lang) ?>"><?= h($categoryName) ?></div>
                                </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> <?= library_trans('edit') ?>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteCategory(<?= $cat['id'] ?>)">
                                        <i class="bi bi-trash"></i> <?= library_trans('delete') ?>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <div class="p-3 border-top">
                <?php library_render_pagination($page, $totalPages, '/admin_categories.php'); ?>
            </div>
        <?php endif; ?>
    </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"><?= library_trans('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"><?= library_trans('name_en') ?></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="<?= library_trans('translation_to_arabic') ?>">
                        <i class="bi bi-translate"></i>
                    </button>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label"><?= library_trans('name_ar') ?></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="<?= library_trans('translation_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"><?= library_trans('cancel') ?></button>
            <button type="submit" class="btn btn-primary"><?= library_trans('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 = '<?= library_trans('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 = '<?= library_trans('edit') ?>';
        
        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('<?= library_trans('confirm_delete') ?>')) {
            document.getElementById('deleteAction').value = 'delete_category';
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteForm').submit();
        }
    }
</script>

<?php admin_render_footer(); ?>