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

require_once __DIR__ . '/config/messages.php';
require_once __DIR__ . '/modules/company_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; //hienthi
$currentPage = (int)($_GET['page'] ?? 1);
$currentPage = max(1, $currentPage);

// Get paginated companies
$allCompanies = company_list();
$totalItems = count($allCompanies);
$totalPages = ceil($totalItems / $itemsPerPage);
$offset = ($currentPage - 1) * $itemsPerPage;
$companies = array_slice($allCompanies, $offset, $itemsPerPage);

$appLicense = (string)((db_connection_settings()['license'] ?? ''));
?>
<section class="panel-grid">
    <div class="panel wide">
        <header class="panel-header">
            <h3><?= htmlspecialchars($messages['company_heading_list'], ENT_QUOTES, 'UTF-8') ?></h3>
            <div class="panel-controls">
                <button type="button" class="btn btn-primary" data-company-open="create"><?= htmlspecialchars($messages['company_btn_add_new'], ENT_QUOTES, 'UTF-8') ?></button>
            </div>
        </header>
        <div class="table-wrapper">
            <?php /* Inline alerts removed in favor of global toast system */ ?>

            <table class="data-table data-table--responsive">
                <thead>
                    <tr>
                        <th style="width:60px"><?= htmlspecialchars($messages['company_col_id'], ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['company_col_name_vn'], ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['company_col_name_eng'], ENT_QUOTES, 'UTF-8') ?></th>
                        <th class="col-actions" style="width:160px"><?= htmlspecialchars($messages['company_col_actions'], ENT_QUOTES, 'UTF-8') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$companies): ?>
                        <tr><td colspan="4" style="text-align:center"><?= htmlspecialchars($messages['company_empty'], ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <?php else: ?>
                        <?php foreach ($companies as $c): ?>
                            <tr>
                                <td data-label="<?= htmlspecialchars($messages['company_col_id'], ENT_QUOTES, 'UTF-8') ?>"><?= (int)$c['id'] ?></td>
                                <td data-label="<?= htmlspecialchars($messages['company_col_name_vn'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($c['name_vn'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['company_col_name_eng'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($c['name_eng'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="col-actions" data-label="<?= htmlspecialchars($messages['company_col_actions'], ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="button" class="btn btn-secondary btn-sm" data-company-edit="<?= (int)$c['id'] ?>"
                                            data-company-id="<?= (int)$c['id'] ?>"
                                            data-company-name-vn="<?= htmlspecialchars($c['name_vn'], ENT_QUOTES, 'UTF-8') ?>"
                                            data-company-name-eng="<?= htmlspecialchars($c['name_eng'], ENT_QUOTES, 'UTF-8') ?>"
                                            title="<?= htmlspecialchars($messages['company_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/company_service.php" style="display:inline-block" class="needs-confirm">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id_company" 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['company_confirm_delete'], ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars($messages['company_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?company&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?company&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?company&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?company&page=<?= $totalPages ?>" class="pagination-number"><?= $totalPages ?></a>
                    <?php endif; ?>
                </div>
                
                <?php if ($currentPage < $totalPages): ?>
                    <a href="index.php?company&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_company'] ?? 'công ty', ENT_QUOTES, 'UTF-8') ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
</section>

<!-- Company Modal -->
<div class="modal-backdrop" id="company-modal" aria-hidden="true">
    <div class="modal">
        <header class="modal-header">
            <h4 id="company-modal-title"><?= htmlspecialchars($messages['company_form_heading'], ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close>&times;</button>
        </header>
        <form method="post" action="modules/company_service.php" class="form-grid" id="company-form" novalidate>
            <input type="hidden" name="action" value="create" id="company-action">
            <input type="hidden" name="id_company" value="0" id="company-id">
            <input type="hidden" name="license" id="company-license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">
            <div class="form-row">
                <label for="company-name-vn"><?= htmlspecialchars($messages['company_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="company-name-vn" placeholder="<?= htmlspecialchars($messages['company_form_name_vn_placeholder'], ENT_QUOTES, 'UTF-8') ?>" required>
                </div>
            </div>
            <div class="form-row">
                <label for="company-name-eng"><?= htmlspecialchars($messages['company_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="company-name-eng" placeholder="<?= htmlspecialchars($messages['company_form_name_eng_placeholder'], ENT_QUOTES, 'UTF-8') ?>" required>
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary" id="company-submit" data-msg-required="<?= htmlspecialchars($messages['company_require_both'] ?? ($messages['company_require_name'] ?? 'Vui lòng nhập đầy đủ tên.'), ENT_QUOTES, 'UTF-8') ?>" data-label-save="<?= htmlspecialchars($messages['company_btn_save'], ENT_QUOTES, 'UTF-8') ?>" data-label-update="<?= htmlspecialchars($messages['company_btn_update'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($messages['company_btn_save'], ENT_QUOTES, 'UTF-8') ?></button>
                <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['company_btn_reset'], ENT_QUOTES, 'UTF-8') ?></button>
            </div>
        </form>
    </div>
 </div>

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

<script>
// Show success message from URL parameter
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);
        // Remove success parameter from URL without reload
        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>

