<?php
// Prevent direct access
if (!defined('LUNA_APP')) {
    http_response_code(403);
    exit('Forbidden');
}

require_once __DIR__ . '/config/messages.php';
require_once __DIR__ . '/modules/category_service.php';
require_once __DIR__ . '/config/database.php';
$messages = load_messages();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$error = '';
$success = '';
if (!empty($_SESSION['flash']['error'])) { $error = (string)$_SESSION['flash']['error']; unset($_SESSION['flash']['error']); }
if (!empty($_SESSION['flash']['success'])) { $success = (string)$_SESSION['flash']['success']; unset($_SESSION['flash']['success']); }

// Pagination parameters
$itemsPerPage = 5;
$currentPage = (int)($_GET['page'] ?? 1);
$currentPage = max(1, $currentPage);

// Get paginated categories
$allCategories = category_list();
$totalItems = count($allCategories);
$totalPages = ceil($totalItems / $itemsPerPage);
$offset = ($currentPage - 1) * $itemsPerPage;
$categories = array_slice($allCategories, $offset, $itemsPerPage);


$appLicense = (string)((db_connection_settings()['license'] ?? ''));
?>
<section class="panel-grid category-grid">
    <div class="panel wide category-panel">
        <header class="panel-header">
            <h3><?= htmlspecialchars($messages['category_heading_list'], ENT_QUOTES, 'UTF-8') ?></h3>
            <div class="panel-controls category-controls">
                <button type="button" class="btn btn-primary category-btn" data-category-open="create">
                    <span aria-hidden="true" class="btn-icon-wrapper">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="12" y1="5" x2="12" y2="19"></line>
                            <line x1="5" y1="12" x2="19" y2="12"></line>
                        </svg>
                    </span>
                    <span class="btn-text-wrapper"><?= htmlspecialchars($messages['company_btn_add_new'], ENT_QUOTES, 'UTF-8') ?></span>
                </button>
            </div>
        </header>
        <div class="table-wrapper">
            <table class="data-table data-table--responsive">
                <thead>
                    <tr>
                        <th style="width:100px"><?= htmlspecialchars($messages['category_col_id'], ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['category_col_name_vn'], ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['category_col_name_eng'], ENT_QUOTES, 'UTF-8') ?></th>
                        <th class="col-actions" style="width:160px"><?= htmlspecialchars($messages['category_col_actions'], ENT_QUOTES, 'UTF-8') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$categories): ?>
                        <tr><td colspan="4" style="text-align:center"><?= htmlspecialchars($messages['category_empty'], ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <?php else: ?>
                        <?php foreach ($categories as $c): ?>
                            <tr>
                                <td data-label="<?= htmlspecialchars($messages['category_col_id'], ENT_QUOTES, 'UTF-8') ?>"><?= (int)$c['id'] ?></td>
                                <td data-label="<?= htmlspecialchars($messages['category_col_name_vn'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($c['name_vn'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['category_col_name_eng'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($c['name_eng'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="col-actions" data-label="<?= htmlspecialchars($messages['category_col_actions'], ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="button" class="btn btn-secondary btn-sm" data-category-edit
                                            data-category-id="<?= (int)$c['id'] ?>"
                                            data-category-name-vn="<?= htmlspecialchars($c['name_vn'], ENT_QUOTES, 'UTF-8') ?>"
                                            data-category-name-eng="<?= htmlspecialchars($c['name_eng'], ENT_QUOTES, 'UTF-8') ?>"
                                            title="<?= htmlspecialchars($messages['category_tooltip_edit'] ?? 'Sửa', ENT_QUOTES, 'UTF-8') ?>">
                                        <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                                            <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
                                        </svg>
                                    </button>
                                    <form method="post" action="modules/category_service.php" style="display:inline-block" class="needs-confirm">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id_category" value="<?= (int)$c['id'] ?>">
                                        <input type="hidden" name="license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">
                                        <button type="submit" class="btn btn-danger btn-sm" data-confirm-message="<?= htmlspecialchars($messages['category_confirm_delete'], ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars($messages['category_tooltip_delete'] ?? 'Xóa', ENT_QUOTES, 'UTF-8') ?>">
                                            <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                                                <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                                            </svg>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($totalPages > 1): ?>
        <div class="pagination-wrapper">
            <div class="pagination">
                <?php if ($currentPage > 1): ?>
                    <a href="index.php?category&page=<?= $currentPage - 1 ?>" class="pagination-btn pagination-prev">
                        <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                            <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
                        </svg>
                        <?= htmlspecialchars($messages['pagination_previous'] ?? 'Trước', ENT_QUOTES, 'UTF-8') ?>
                    </a>
                <?php endif; ?>
                
                <div class="pagination-numbers">
                    <?php
                    $startPage = max(1, $currentPage - 2);
                    $endPage = min($totalPages, $currentPage + 2);
                    
                    if ($startPage > 1): ?>
                        <a href="index.php?category&page=1" class="pagination-number">1</a>
                        <?php if ($startPage > 2): ?>
                            <span class="pagination-ellipsis">...</span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                        <a href="index.php?category&page=<?= $i ?>" class="pagination-number <?= $i === $currentPage ? 'active' : '' ?>"><?= $i ?></a>
                    <?php endfor; ?>
                    
                    <?php if ($endPage < $totalPages): ?>
                        <?php if ($endPage < $totalPages - 1): ?>
                            <span class="pagination-ellipsis">...</span>
                        <?php endif; ?>
                        <a href="index.php?category&page=<?= $totalPages ?>" class="pagination-number"><?= $totalPages ?></a>
                    <?php endif; ?>
                </div>
                
                <?php if ($currentPage < $totalPages): ?>
                    <a href="index.php?category&page=<?= $currentPage + 1 ?>" class="pagination-btn pagination-next">
                        <?= htmlspecialchars($messages['pagination_next'] ?? 'Sau', ENT_QUOTES, 'UTF-8') ?>
                        <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                            <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
                        </svg>
                    </a>
                <?php endif; ?>
            </div>
            
            <div class="pagination-info">
                <?= htmlspecialchars($messages['table_info_display'] ?? 'Hiển thị', ENT_QUOTES, 'UTF-8') ?> <?= (($currentPage - 1) * $itemsPerPage) + 1 ?>-<?= min($currentPage * $itemsPerPage, $totalItems) ?> 
                <?= htmlspecialchars($messages['table_info_of_total'] ?? 'trong tổng số', ENT_QUOTES, 'UTF-8') ?> <?= $totalItems ?> <?= htmlspecialchars($messages['table_info_category'] ?? 'hạng mục', ENT_QUOTES, 'UTF-8') ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<style>
.category-panel .category-controls {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    justify-content: flex-end;
    align-items: center;
}

.category-panel .category-controls .category-btn {
    padding: 8px 16px !important;
    font-size: 13px !important;
    font-weight: 500 !important;
    border-radius: 8px !important;
    min-height: 36px !important;
    display: inline-flex !important;
    align-items: center !important;
    gap: 8px !important;
    transition: all 0.2s ease !important;
    text-decoration: none !important;
    background: linear-gradient(135deg, rgba(100, 167, 166, 0.9), rgba(122, 220, 201, 0.95)) !important;
    color: #052729 !important;
    border: 1px solid rgba(122, 220, 201, 0.4) !important;
}

.category-panel .category-controls .category-btn:hover {
    background: linear-gradient(135deg, rgba(122, 220, 201, 0.95), rgba(100, 167, 166, 0.9)) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(122, 220, 201, 0.3) !important;
}

.category-panel .category-controls .btn-icon-wrapper {
    display: inline-grid;
    place-items: center;
    width: 14px;
    height: 14px;
}

.category-panel .category-controls .btn-icon-wrapper svg {
    width: 14px;
    height: 14px;
}

.category-panel .category-controls .btn-text-wrapper {
    font-size: 13px;
    font-weight: 500;
    color: inherit;
}

.category-panel .category-controls .category-btn:focus-visible {
    outline: 2px solid rgba(122, 220, 201, 0.6) !important;
    outline-offset: 2px !important;
}

@media (max-width: 768px) {
    .category-panel .category-controls {
        justify-content: center;
    }

    .category-panel .category-controls .category-btn {
        width: 100% !important;
        justify-content: center !important;
        font-size: 12px !important;
        padding: 6px 12px !important;
    }

    .category-panel .category-controls .btn-text-wrapper {
        font-size: 12px !important;
    }
}
</style>

<div class="modal-backdrop" id="category-modal" aria-hidden="true">
    <div class="modal">
        <header class="modal-header">
            <h4 id="category-modal-title"><?= htmlspecialchars($messages['category_form_heading'], ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close>&times;</button>
        </header>
        <form method="post" action="modules/category_service.php" class="form-grid" id="category-form" novalidate>
            <input type="hidden" name="action" value="create" id="category-action">
            <input type="hidden" name="id_category" value="0" id="category-id">
            <input type="hidden" name="license" id="category-license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">
            <div class="form-row">
                <label for="category-name-vn"><?= htmlspecialchars($messages['category_form_name_vn_label'], ENT_QUOTES, 'UTF-8') ?></label>
                <div class="input-wrap">
                    <span class="icon"><svg viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></span>
                    <input type="text" name="name_vn" id="category-name-vn" placeholder="<?= htmlspecialchars($messages['category_form_name_vn_placeholder'], ENT_QUOTES, 'UTF-8') ?>" required>
                </div>
            </div>
            <div class="form-row">
                <label for="category-name-eng"><?= htmlspecialchars($messages['category_form_name_eng_label'], ENT_QUOTES, 'UTF-8') ?></label>
                <div class="input-wrap">
                    <span class="icon"><svg viewBox="0 0 24 24"><path d="M4 4h16v4H4zM4 12h10v8H4zM16 12h4v8h-4z"/></svg></span>
                    <input type="text" name="name_eng" id="category-name-eng" placeholder="<?= htmlspecialchars($messages['category_form_name_eng_placeholder'], ENT_QUOTES, 'UTF-8') ?>" required>
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary" id="category-submit"><?= htmlspecialchars($messages['category_btn_save'], ENT_QUOTES, 'UTF-8') ?></button>
                <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['category_btn_reset'], ENT_QUOTES, 'UTF-8') ?></button>
            </div>
        </form>
    </div>
</div>

<script src="assets/js/category.js?v=<?php echo time(); ?>"></script>


<script>
// Show success/error message from URL parameter (same behavior as Company)
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const successMsg = urlParams.get('success');
    const errorMsg = urlParams.get('error');
    if (successMsg && window.showToast) {
        const decodedMsg = decodeURIComponent(successMsg).replace(/\n/g, '<br>');
        const successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
        const successWithHeader = '<div class="success-header">' + successTitle + '</div>' + decodedMsg;
        window.showToast('success', successWithHeader);
        const newUrl = new URL(window.location);
        newUrl.searchParams.delete('success');
        newUrl.searchParams.delete('error');
        window.history.replaceState({}, '', newUrl);
    } else if (errorMsg && window.showToast) {
        const decodedErr = decodeURIComponent(errorMsg).replace(/\n/g, '<br>');
        const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
        const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + decodedErr;
        window.showToast('error', errorWithHeader);
        const newUrl = new URL(window.location);
        newUrl.searchParams.delete('error');
        window.history.replaceState({}, '', newUrl);
    }
});
</script>

