<?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_subcategory') {
            $catId = (int)($_POST['category_id'] ?? 0);
            $nameEn = trim($_POST['name_en'] ?? '');
            $nameAr = trim($_POST['name_ar'] ?? '');
            if (!$catId || !$nameEn || !$nameAr) {
                throw new RuntimeException(library_trans('subcategory_name_required'));
            }
            library_create_subcategory($catId, $nameEn, $nameAr);
            library_set_flash('success', library_trans('subcategory_created_success'));
            header('Location: /admin_subcategories.php');
            exit;
        } elseif ($action === 'update_subcategory') {
            $catId = (int)($_POST['category_id'] ?? 0);
            $nameEn = trim($_POST['name_en'] ?? '');
            $nameAr = trim($_POST['name_ar'] ?? '');
            if (!$id || !$catId || !$nameEn || !$nameAr) {
                throw new RuntimeException(library_trans('subcategory_update_required'));
            }
            library_update_subcategory($id, $catId, $nameEn, $nameAr);
            library_set_flash('success', library_trans('subcategory_updated_success'));
            header('Location: /admin_subcategories.php');
            exit;
        } elseif ($action === 'delete_subcategory') {
            if (!$id) {
                throw new RuntimeException(library_trans('invalid_subcategory_id'));
            }
            library_delete_subcategory($id);
            library_set_flash('success', library_trans('subcategory_deleted_success'));
            header('Location: /admin_subcategories.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']) : '';

// Get categories for lookup/filter
$categories = library_get_categories();

// Paginated Fetch
$result = library_get_subcategories_paginated(null, $search, $limit, $offset);
$allSubcategories = $result['data'];
$totalSubcategories = $result['total'];
$totalPages = (int)ceil($totalSubcategories / $limit);
$lang = library_get_language();

admin_render_header(library_trans('subcategories'), 'subcategories');
?>
<!-- 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_subcategories_desc') ?></p>
    <button class="btn btn-primary" onclick="openCreateSubcategoryModal()">
        <i class="bi bi-plus-lg me-1"></i> <?= library_trans('add_new_subcategory') ?>
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form method="get" action="/admin_subcategories.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_subcategories.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><?= library_trans('category') ?></th>
                        <th class="text-end pe-4"><?= library_trans('actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($allSubcategories)): ?>
                        <tr><td colspan="3" class="text-center py-5 text-muted"><?= library_trans('no_subcategories_found') ?></td></tr>
                    <?php else: ?>
                        <?php foreach ($allSubcategories as $sub): 
                            $parentName = library_trans('unknown');
                            foreach ($categories as $c) {
                                if ($c['id'] == $sub['category_id']) {
                                    $parentName = library_localized_value($c['name_en'] ?? null, $c['name_ar'] ?? null, $lang, library_trans('unknown'));
                                    break;
                                }
                            }
                        ?>
                            <tr>
                                <td class="ps-4">
                                    <?php $subName = library_localized_value($sub['name_en'] ?? null, $sub['name_ar'] ?? null, $lang); ?>
                                    <div class="fw-medium text-dark" dir="<?= library_text_dir($subName, $lang) ?>"><?= h($subName) ?></div>
                                </td>
                                <td>
                                    <span class="badge bg-light text-dark border" dir="<?= library_text_dir($parentName, $lang) ?>"><?= h($parentName) ?></span>
                                </td>
                                <td class="text-end pe-4">
                                    <button class="btn btn-sm btn-outline-secondary me-1" 
                                            data-id="<?= $sub['id'] ?>"
                                            data-category-id="<?= $sub['category_id'] ?>"
                                            data-name-en="<?= h($sub['name_en']) ?>"
                                            data-name-ar="<?= h($sub['name_ar']) ?>"
                                            onclick="openEditSubcategoryModal(this)">
                                        <i class="bi bi-pencil"></i> <?= library_trans('edit') ?>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteSubcategory(<?= $sub['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_subcategories.php'); ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Subcategory Modal -->
<div class="modal fade" id="subcategoryModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post" action="/admin_subcategories.php" id="subcategoryForm">
        <input type="hidden" name="action" id="sub_action" value="create_subcategory">
        <input type="hidden" name="id" id="sub_id" value="">
        <div class="modal-header">
            <h5 class="modal-title" id="subcategoryModalTitle"><?= library_trans('add_new_subcategory') ?></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('category') ?></label>
                <select class="form-select" name="category_id" id="sub_category_id" required>
                    <option value=""><?= library_trans('select_category') ?></option>
                    <?php foreach ($categories as $cat): ?>
                        <?php $categoryName = library_localized_value($cat['name_en'] ?? null, $cat['name_ar'] ?? null, $lang); ?>
                        <option value="<?= $cat['id'] ?>" dir="<?= library_text_dir($categoryName, $lang) ?>"><?= h($categoryName) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <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="sub_name_en" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="translateText('sub_name_en', 'sub_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="sub_name_ar" dir="rtl" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="translateText('sub_name_ar', 'sub_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_subcategories.php" id="deleteForm">
    <input type="hidden" name="action" id="deleteAction" value="">
    <input type="hidden" name="id" id="deleteId" value="">
</form>

<script>
    let subcategoryModal;

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

    function openCreateSubcategoryModal() {
        document.getElementById('subcategoryModalTitle').innerText = '<?= library_trans('add_new_subcategory') ?>';
        document.getElementById('sub_action').value = 'create_subcategory';
        document.getElementById('sub_id').value = '';
        document.getElementById('sub_category_id').value = '';
        document.getElementById('sub_name_en').value = '';
        document.getElementById('sub_name_ar').value = '';
        subcategoryModal.show();
    }

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

        document.getElementById('subcategoryModalTitle').innerText = '<?= library_trans('edit') ?>';
        document.getElementById('sub_action').value = 'update_subcategory';
        document.getElementById('sub_id').value = id;
        document.getElementById('sub_category_id').value = catId;
        document.getElementById('sub_name_en').value = nameEn;
        document.getElementById('sub_name_ar').value = nameAr;
        subcategoryModal.show();
    }

    function deleteSubcategory(id) {
        if (confirm('<?= library_trans('confirm_delete') ?>')) {
            document.getElementById('deleteAction').value = 'delete_subcategory';
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteForm').submit();
        }
    }
</script>

<?php admin_render_footer(); ?>