<?php
if (!defined('LUNA_APP')) {
    http_response_code(403);
    exit('Forbidden');
}
if (!isset($messages) || !is_array($messages)) {
    require_once __DIR__ . '/config/messages.php';
    $messages = load_messages();
}
require_once __DIR__ . '/config/database.php';
$appLicense = (string)((db_connection_settings()['license'] ?? ''));
// Load companies for select (VN/ENG based on session lang)
$companies = [];
try {
    $conn = db_connect();
    if ($conn) {
        $stmt = sqlsrv_query($conn, 'SELECT ID_Company, Name_Vn, Name_Eng FROM Company ORDER BY ID_Company ASC');
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $companies[] = [
                    'id' => (int)($row['ID_Company'] ?? 0),
                    'vn' => (string)($row['Name_Vn'] ?? ''),
                    'eng' => (string)($row['Name_Eng'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { /* ignore */ }

// Get next document ID
$nextDocumentId = 1;
try {
    $conn = db_connect();
    if ($conn) {
        $stmt = sqlsrv_query($conn, 'SELECT ISNULL(MAX(Id), 0) + 1 as next_id FROM Document');
        if ($stmt !== false) {
            if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $nextDocumentId = (int)($row['next_id'] ?? 1);
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { /* ignore */ }

// Load categories for select (VN/ENG based on session lang)
$categories = [];
try {
    $conn = db_connect();
    if ($conn) {
        $stmt = sqlsrv_query($conn, 'SELECT ID_Category, Name_Vn, Name_Eng FROM Category ORDER BY ID_Category ASC');
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $categories[] = [
                    'id' => (int)($row['ID_Category'] ?? 0),
                    'vn' => (string)($row['Name_Vn'] ?? ''),
                    'eng' => (string)($row['Name_Eng'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { /* ignore */ }

// Load recipients for export modal (MSNV 00092 and 00114)
$recipients = [];
try {
    $conn = db_connect();
    if ($conn) {
        $stmt = sqlsrv_query($conn, "SELECT Maso_NV, Hoten, Name FROM DataWork WHERE Maso_NV IN ('00092', '00096') ORDER BY Maso_NV ASC");
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $recipients[] = [
                    'msnv' => (string)($row['Maso_NV'] ?? ''),
                    'hoten' => (string)($row['Hoten'] ?? ''),
                    'name' => (string)($row['Name'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { /* ignore */ }

// Load document types for select (VN/ENG based on session lang)
$docTypes = [];
try {
    $conn = db_connect();
    if ($conn) {
        $stmt = sqlsrv_query($conn, 'SELECT Id_Type, Name_Vn, Name_Eng FROM DocType ORDER BY Id_Type ASC');
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $docTypes[] = [
                    'id' => (int)($row['Id_Type'] ?? 0),
                    'vn' => (string)($row['Name_Vn'] ?? ''),
                    'eng' => (string)($row['Name_Eng'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { /* ignore */ }

// Load document page types for select (VN/ENG based on session lang)
$docPageTypes = [];
try {
    $conn = db_connect();
    if ($conn) {
        $stmt = sqlsrv_query($conn, 'SELECT Id_Type, Name_Vn, Name_Eng FROM DocPageType ORDER BY Id_Type ASC');
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $docPageTypes[] = [
                    'id' => (int)($row['Id_Type'] ?? 0),
                    'vn' => (string)($row['Name_Vn'] ?? ''),
                    'eng' => (string)($row['Name_Eng'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { /* ignore */ }

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

// Load incoming documents list
$allDocuments = [];
$searchQuery = !empty($_GET['search_query']) ? trim($_GET['search_query']) : '';

try {
    $conn = db_connect();
    if ($conn) {
        $sql = "SELECT d.Id, d.ID_Symbol, d.TitleVi, d.Issuer, d.EffectiveDate, d.FileUrl,
                       d.Summary, d.ID_Category, d.DocType, d.TypeDoc, d.Quantity,
                       d.ExpiryDate, d.ID_Company, d.FileStorage, d.Notes,
                       c.Name_Vn as CompanyName_Vn, c.Name_Eng as CompanyName_Eng,
                       cat.Name_Vn as CategoryName_Vn, cat.Name_Eng as CategoryName_Eng
                FROM Document d
                LEFT JOIN Company c ON d.ID_Company = c.ID_Company
                LEFT JOIN Category cat ON d.ID_Category = cat.ID_Category";
        
        $parameters = [];
        
        // Simple search: search in symbol, title, and issuer
        if (!empty($searchQuery)) {
            $sql .= " WHERE (d.ID_Symbol LIKE ? OR d.TitleVi LIKE ? OR d.Issuer LIKE ?)";
            $searchPattern = '%' . $searchQuery . '%';
            $parameters = [$searchPattern, $searchPattern, $searchPattern];
        }
        
        $sql .= " ORDER BY d.EffectiveDate DESC, d.Id DESC";
        
        if (!empty($parameters)) {
            $stmt = sqlsrv_prepare($conn, $sql, $parameters);
            $success = $stmt && sqlsrv_execute($stmt);
        } else {
            $stmt = sqlsrv_query($conn, $sql);
            $success = ($stmt !== false);
        }
        if ($stmt !== false) {
            error_log("SQL query executed successfully");
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $allDocuments[] = [
                    'id' => (int)($row['Id'] ?? 0),
                    'symbol' => (string)($row['ID_Symbol'] ?? ''),
                    'title' => (string)($row['TitleVi'] ?? ''),
                    'issuer' => (string)($row['Issuer'] ?? ''),
                    'effective_date' => $row['EffectiveDate'] ? date('d/m/Y', strtotime($row['EffectiveDate'])) : '',
                    'file_url' => (string)($row['FileUrl'] ?? ''),
                    'summary' => (string)($row['Summary'] ?? ''),
                    'id_category' => (int)($row['ID_Category'] ?? 0),
                    'doctype' => (string)($row['DocType'] ?? ''),
                    'typedoc' => (string)($row['TypeDoc'] ?? ''),
                    'quantity' => (int)($row['Quantity'] ?? 0),
                    'expiration_date' => $row['ExpiryDate'] ? date('d/m/Y', strtotime($row['ExpiryDate'])) : '',
                    'id_company' => (int)($row['ID_Company'] ?? 0),
                    'storage_location' => (string)($row['FileStorage'] ?? ''),
                    'notes' => (string)($row['Notes'] ?? ''),
                    'company_vn' => (string)($row['CompanyName_Vn'] ?? ''),
                    'company_eng' => (string)($row['CompanyName_Eng'] ?? ''),
                    'category_vn' => (string)($row['CategoryName_Vn'] ?? ''),
                    'category_eng' => (string)($row['CategoryName_Eng'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        } else {
            $errors = sqlsrv_errors();
            error_log("SQL query failed: " . print_r($errors, true));
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { 
    error_log("Incoming documents load error: " . $e->getMessage());
}

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

// Debug info
error_log("Incoming documents debug - Total items: " . $totalItems . ", Current page: " . $currentPage . ", Documents count: " . count($documents));
echo "<!-- DEBUG: Total items: " . $totalItems . ", Current page: " . $currentPage . ", Documents count: " . count($documents) . " -->";
?>
<section class="panel-grid incoming-documents-grid">
    <div class="panel wide incoming-panel">
        <header class="panel-header">
            <h3><?= htmlspecialchars($messages['control_nav_incoming_documents'], ENT_QUOTES, 'UTF-8') ?></h3>
            <div class="panel-controls incoming-controls">
                <button type="button" class="btn btn-primary incoming-btn" data-incoming-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['incoming_btn_add_new'] ?? 'Thêm mới', ENT_QUOTES, 'UTF-8') ?></span>
                </button>
                <a href="index.php?incoming=log" class="btn btn-secondary incoming-btn incoming-log-link">
                    <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">
                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                            <polyline points="14,2 14,8 20,8" />
                        </svg>
                    </span>
                    <span class="btn-text-wrapper">View Log</span>
                </a>
                <button type="button" class="btn btn-success incoming-btn" data-export-open="true">
                    <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">
                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                            <polyline points="14,2 14,8 20,8"/>
                            <line x1="12" y1="18" x2="12" y2="12"/>
                            <line x1="9" y1="15" x2="15" y2="15"/>
                        </svg>
                    </span>
                    <span class="btn-text-wrapper"><?= htmlspecialchars($messages['excel_export_btn'] ?? 'Xuất Excel', ENT_QUOTES, 'UTF-8') ?></span>
                </button>
            </div>
        </header>
        
        <!-- Simple Search Bar -->
        <div class="search-filter-section" style="padding: 16px; background: rgba(255, 255, 255, 0.02); border-bottom: 1px solid rgba(255, 255, 255, 0.1); display: flex; justify-content: center;">
            <form id="incoming-search-form" autocomplete="on" style="display: flex; align-items: center; max-width: 600px; width: 100%;">
                <div class="input-wrap" style="flex: 1; position: relative;">
                    <span class="icon" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); opacity: 0.5; pointer-events: none; z-index: 1;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor;">
                            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                        </svg>
                    </span>
                    <input type="text" 
                           id="search-query-incoming" 
                           name="search_query" 
                           autocomplete="on" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" inputmode="search" enterkeyhint="search"
                           placeholder="<?= htmlspecialchars($messages['search_placeholder'] ?? 'Tìm kiếm theo số hiệu, tiêu đề, cơ quan nhận...', ENT_QUOTES, 'UTF-8') ?>" 
                           value="<?= htmlspecialchars($searchQuery, ENT_QUOTES, 'UTF-8') ?>"
                           style="width: 100%; padding: 10px 50px 10px 42px; background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 6px; color: #fff; font-size: 12px; transition: all 0.3s ease;">
                    <button type="submit" 
                            id="search-submit-btn"
                            style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); background: #7adcc9; border: none; border-radius: 4px; padding: 6px 10px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.3s ease; z-index: 10; pointer-events: auto; width: 34px; height: 28px;"
                            title="<?= htmlspecialchars($messages['search_button'] ?? 'Tìm kiếm', ENT_QUOTES, 'UTF-8') ?>">
                        <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: #1a3a3a;">
                            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                        </svg>
                    </button>
                </div>
                <?php if (!empty($searchQuery)): ?>
                <?php endif; ?>
            </form>
            <?php if (!empty($searchQuery)): ?>
            <?php endif; ?>
        </div>
        <?php if (!empty($searchQuery)): ?>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            try {
                var count = <?= (int)($totalItems ?? 0) ?>;
                var q = "<?= htmlspecialchars($searchQuery, ENT_QUOTES, 'UTF-8') ?>";
                var foundText = "<?= htmlspecialchars($messages['search_results_found'] ?? 'Tìm thấy', ENT_QUOTES, 'UTF-8') ?>";
                var forText = "<?= htmlspecialchars($messages['search_results_for'] ?? 'kết quả cho', ENT_QUOTES, 'UTF-8') ?>";
                var successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var msg = foundText + ' <strong style="color:#7adcc9">' + count + '</strong> ' + forText + ' "<strong>' + q + '</strong>"';
                if (typeof window.showToast === 'function') {
                    if (count > 0) {
                        window.showToast('success', '<div class="success-header">' + successTitle + '</div>' + msg);
                    } else {
                        window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + msg);
                    }
                }
            } catch (_) {}
        });
        </script>
        <?php endif; ?>

        <div class="table-wrapper">
            <table class="data-table data-table--responsive">
                <thead>
                    <tr>
                        <th style="width:60px"><?= htmlspecialchars($messages['incoming_col_id'] ?? 'ID', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['incoming_col_symbol'] ?? 'Số hiệu', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['incoming_col_title'] ?? 'Tiêu đề', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['incoming_col_issuer'] ?? 'Cơ quan cấp', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['incoming_col_effective_date'] ?? 'Ngày hiệu lực', ENT_QUOTES, 'UTF-8') ?></th>
                        <th class="col-actions" style="width:160px"><?= htmlspecialchars($messages['incoming_col_actions'] ?? 'Thao tác', ENT_QUOTES, 'UTF-8') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($documents)): ?>
                        <tr><td colspan="6" style="text-align:center"><?= htmlspecialchars($messages['incoming_empty'] ?? 'Chưa có dữ liệu', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <?php else: ?>
                        <?php foreach ($documents as $doc): ?>
                            <tr data-document="<?= htmlspecialchars(json_encode($doc), ENT_QUOTES, 'UTF-8') ?>">
                                <td data-label="<?= htmlspecialchars($messages['incoming_col_id'] ?? 'ID', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['id'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['incoming_col_symbol'] ?? 'Số hiệu', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['symbol'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['incoming_col_title'] ?? 'Tiêu đề', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['title'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['incoming_col_issuer'] ?? 'Cơ quan cấp', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['issuer'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['incoming_col_effective_date'] ?? 'Ngày hiệu lực', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['effective_date'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="col-actions" data-label="<?= htmlspecialchars($messages['incoming_col_actions'] ?? 'Thao tác', ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="button" class="btn btn-sm btn-secondary" data-incoming-edit="<?= $doc['id'] ?>" title="<?= htmlspecialchars($messages['incoming_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>
                                    <?php if (!empty($doc['file_url'])): ?>
                                        <button type="button" class="btn btn-sm btn-info" data-incoming-view="<?= $doc['id'] ?>" title="<?= htmlspecialchars($messages['incoming_tooltip_view'] ?? 'Xem file', ENT_QUOTES, 'UTF-8') ?>">
                                            <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                                                <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                                            </svg>
                                        </button>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-sm btn-success" data-incoming-import="<?= $doc['id'] ?>" title="<?= htmlspecialchars($messages['incoming_tooltip_import'] ?? 'Nhập file', ENT_QUOTES, 'UTF-8') ?>">
                                        <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                                            <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
                                            <path d="M12,11L16,15H13V19H11V15H8L12,11Z"/>
                                        </svg>
                                    </button>
                                    <?php if ($doc['quantity'] > 0): ?>
                                        <button type="button" class="btn btn-sm btn-warning" data-incoming-export="<?= $doc['id'] ?>" title="<?= htmlspecialchars($messages['incoming_tooltip_export'] ?? 'Xuất file', ENT_QUOTES, 'UTF-8') ?>">
                                            <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                                                <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
                                                <path d="M12,19L8,15H11V11H13V15H16L12,19Z"/>
                                            </svg>
                                        </button>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-sm btn-danger" data-incoming-delete="<?= $doc['id'] ?>" title="<?= htmlspecialchars($messages['incoming_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>
                                </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?incoming&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?incoming&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?incoming&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?incoming&page=<?= $totalPages ?>" class="pagination-number"><?= $totalPages ?></a>
                    <?php endif; ?>
                </div>
                
                <?php if ($currentPage < $totalPages): ?>
                    <a href="index.php?incoming&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_document'] ?? 'công văn', ENT_QUOTES, 'UTF-8') ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Incoming Document Modal -->
<div id="incoming-modal" class="modal-backdrop" aria-hidden="true">
    <div class="modal">
        <div class="modal-header">
            <h4 id="incoming-modal-title" data-label-create="<?= htmlspecialchars($messages['incoming_create_heading'] ?? 'THÊM CÔNG VĂN ĐẾN', ENT_QUOTES, 'UTF-8') ?>" data-label-update="<?= htmlspecialchars($messages['incoming_update_heading'] ?? 'CẬP NHẬT CÔNG VĂN ĐẾN', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($messages['incoming_create_heading'] ?? 'THÊM CÔNG VĂN ĐẾN', ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close>&times;</button>
        </div>
        <div class="modal-body">
            <form id="incoming-form" action="modules/incoming_service.php" method="POST" class="form-grid grid-2" novalidate>
                <input type="hidden" name="action" value="create" id="incoming-action">
                <input type="hidden" name="id_document" value="0" id="incoming-id">
                <input type="hidden" name="document_id" value="<?= $nextDocumentId ?>" id="document-id">
                <input type="hidden" name="license" id="incoming-license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">

                <div class="form-row">
                    <label for="doc-symbol"><?= htmlspecialchars($messages['incoming_form_symbol_label'] ?? 'Số hiệu', 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" id="doc-symbol" name="id_symbol" placeholder="<?= htmlspecialchars($messages['incoming_form_symbol_placeholder'] ?? 'VD: 123/QĐ-UBND', ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="doc-code"><?= htmlspecialchars($messages['incoming_form_document_code_label'] ?? 'Mã số văn bản', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                        </span>
                        <input type="text" id="doc-code" name="document_code" value="<?= $nextDocumentId ?>" placeholder="Tự động tạo" readonly style="color: #7adcc9; font-weight: bold;" data-next-id="<?= $nextDocumentId ?>">
                    </div>
                </div>

                

                <div class="form-row full">
                    <label for="doc-title"><?= $messages['incoming_form_title_label'] ?? 'Tiêu đề' ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14,2 14,8 20,8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10,9 9,9 8,9"/></svg>
                        </span>
                        <input type="text" id="doc-title" name="title_vi" placeholder="<?= htmlspecialchars($messages['incoming_form_title_placeholder'] ?? 'Nhập tiêu đề công văn', ENT_QUOTES, 'UTF-8') ?>" required>
                    </div>
                </div>

                <div class="form-row full">
                    <label for="doc-summary"><?= htmlspecialchars($messages['incoming_form_summary_label'] ?? 'Tóm tắt nội dung', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <textarea id="doc-summary" name="summary" rows="3" placeholder="<?= htmlspecialchars($messages['incoming_form_summary_placeholder'] ?? 'Nhập tóm tắt nội dung', ENT_QUOTES, 'UTF-8') ?>"></textarea>
                    </div>
                </div>

                <div class="form-row">
                    <label><?= $messages['incoming_form_type_label'] ?? 'Thể loại <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <div class="custom-select" id="doctype-custom-select">
                            <button type="button" class="custom-select-toggle" data-placeholder="--">--</button>
                            <div class="custom-select-menu" role="listbox">
                                <?php $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng'); if (!empty($docTypes)): foreach ($docTypes as $dt): ?>
                                    <div class="custom-select-option" role="option" data-value="<?= (int)$dt['id'] ?>">
                                        <?= htmlspecialchars($isEng ? $dt['eng'] : $dt['vn'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endforeach; else: ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">Chưa có dữ liệu</div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" name="doc_type" id="doc-type-id" value="">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label><?= $messages['incoming_form_type_doc_label'] ?? 'Loại giấy tờ <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <div class="custom-select" id="docpagetype-custom-select">
                            <button type="button" class="custom-select-toggle" data-placeholder="--">--</button>
                            <div class="custom-select-menu" role="listbox">
                                <?php $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng'); if (!empty($docPageTypes)): foreach ($docPageTypes as $dpt): ?>
                                    <div class="custom-select-option" role="option" data-value="<?= (int)$dpt['id'] ?>">
                                        <?= htmlspecialchars($isEng ? $dpt['eng'] : $dpt['vn'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endforeach; else: ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">Chưa có dữ liệu</div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" name="type_doc" id="doc-typedoc-id" value="">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="doc-quantity"><?= $messages['incoming_form_quantity_label'] ?? 'Số lượng <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M9 11H5a2 2 0 0 0-2 2v3c0 1.1.9 2 2 2h4m0-7h10a2 2 0 0 1 2 2v3c0 1.1-.9 2-2 2H9m0-7V9a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1"/></svg>
                        </span>
                        <input type="number" id="doc-quantity" name="quantity" min="0" step="1" pattern="[0-9]*" inputmode="numeric" placeholder="<?= htmlspecialchars($messages['incoming_form_quantity_placeholder'] ?? 'Nhập số lượng', ENT_QUOTES, 'UTF-8') ?>">
                        <div class="number-spinner">
                            <div class="spinner-up" onclick="incrementQuantity()"></div>
                            <div class="spinner-down" onclick="decrementQuantity()"></div>
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="doc-issuer"><?= $messages['incoming_form_issuer_label'] ?? 'Cơ quan cấp <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M3 21h18"/><path d="M5 21V7l8-4v18"/><path d="M19 21V11l-6-4"/></svg>
                        </span>
                        <input type="text" id="doc-issuer" name="issuer" placeholder="<?= htmlspecialchars($messages['incoming_form_issuer_placeholder'] ?? 'Nhập cơ quan cấp', ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="doc-effective"><?= $messages['incoming_form_effective_label'] ?? 'Ngày hiệu lực <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <span class="icon date-icon" data-target="doc-effective">
                            <svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                        </span>
                        <input type="date" id="doc-effective" name="effective_date" placeholder="<?= htmlspecialchars($messages['incoming_form_effective_placeholder'] ?? 'dd/mm/yyyy', ENT_QUOTES, 'UTF-8') ?>" required style="font-size: 16px;" autocomplete="off">
                    </div>
                </div>

                <div class="form-row">
                    <label for="doc-expiry"><?= htmlspecialchars($messages['incoming_form_expiry_label'] ?? 'Ngày hết hạn', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon date-icon" data-target="doc-expiry">
                            <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12,6 12,12 16,14"/></svg>
                        </span>
                        <input type="date" id="doc-expiry" name="expiry_date" placeholder="<?= htmlspecialchars($messages['incoming_form_expiry_placeholder'] ?? 'dd/mm/yyyy', ENT_QUOTES, 'UTF-8') ?>" style="font-size: 16px;" autocomplete="off">
                    </div>
                </div>

                <div class="form-row">
                    <label><?= $messages['incoming_form_company_label'] ?? 'Thuộc công ty <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <div class="custom-select" id="company-custom-select">
                            <button type="button" class="custom-select-toggle" data-placeholder="--">--</button>
                            <div class="custom-select-menu" role="listbox">
                                <?php $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng'); if (!empty($companies)): foreach ($companies as $c): ?>
                                    <div class="custom-select-option" role="option" data-value="<?= (int)$c['id'] ?>">
                                        <?= htmlspecialchars($isEng ? $c['eng'] : $c['vn'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endforeach; else: ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">Chưa có dữ liệu</div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" name="id_company" id="doc-company-id" value="">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label><?= $messages['incoming_form_category_label'] ?? 'Hạng mục <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <div class="custom-select" id="category-custom-select">
                            <button type="button" class="custom-select-toggle" data-placeholder="--">--</button>
                            <div class="custom-select-menu" role="listbox">
                                <?php $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng'); if (!empty($categories)): foreach ($categories as $cat): ?>
                                    <div class="custom-select-option" role="option" data-value="<?= (int)$cat['id'] ?>">
                                        <?= htmlspecialchars($isEng ? $cat['eng'] : $cat['vn'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endforeach; else: ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">Chưa có dữ liệu</div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" name="id_category" id="doc-category-id" value="">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="doc-file"><?= htmlspecialchars($messages['incoming_form_file_link_label'] ?? 'Link file', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap input-with-button">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14,2 14,8 20,8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10,9 9,9 8,9"/></svg>
                        </span>
                        <input type="text" id="doc-file" name="file_url" placeholder="<?= htmlspecialchars($messages['incoming_form_file_link_placeholder'] ?? 'Click vào icon => để upload file', ENT_QUOTES, 'UTF-8') ?>" style="padding-right: 80px;" readonly>
                        <button type="button" id="view-pdf-btn" class="view-pdf-icon-btn" style="display: none;" title="<?= htmlspecialchars($messages['incoming_tooltip_view_pdf'] ?? 'Xem file PDF', ENT_QUOTES, 'UTF-8') ?>">
                            <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: currentColor;">
                                <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                            </svg>
                        </button>
                        <button type="button" id="upload-pdf-btn" class="upload-pdf-icon-btn">
                            <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: currentColor;">
                                <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
                                <path d="M12,15L15,12H13V8H11V12H9L12,15Z"/>
                            </svg>
                        </button>
                        <input type="file" id="pdf-file-input" accept=".pdf" style="display: none;">
                    </div>
                </div>

                <div class="form-row">
                    <label for="file-storage"><?= htmlspecialchars($messages['incoming_form_file_storage_label'] ?? 'Nơi lưu file', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M10 4H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2h-8l-2-2z"/></svg>
                        </span>
                        <input type="text" id="file-storage" name="file_storage" placeholder="<?= htmlspecialchars($messages['incoming_form_file_storage_placeholder'] ?? 'Nhập nơi lưu file', ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row full">
                    <label for="doc-notes"><?= htmlspecialchars($messages['incoming_form_notes_label'] ?? 'Ghi chú', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <textarea id="doc-notes" name="notes" rows="3"></textarea>
                    </div>
                </div>

                <?php 
                // Set timezone to Vietnam
                date_default_timezone_set('Asia/Ho_Chi_Minh');
                $currentDateTime = date('Y-m-d H:i:s'); 
                ?>
                <div class="form-row">
                    <label for="doc-owner"><?= htmlspecialchars($messages['incoming_form_employee_id_label'] ?? 'Mã số NV nhập', 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" id="doc-owner" name="id_by" value="<?= htmlspecialchars($_SESSION['user']['username'] ?? '', ENT_QUOTES, 'UTF-8') ?>" readonly style="color: #7adcc9; font-weight: bold;">
                    </div>
                </div>
                <div class="form-row">
                    <label for="doc-created-at"><?= htmlspecialchars($messages['incoming_form_created_at_label'] ?? 'Ngày nhập', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                        </span>
                        <input type="text" id="doc-created-at" name="created_at" value="<?= htmlspecialchars($currentDateTime, ENT_QUOTES, 'UTF-8') ?>" readonly style="color: #7adcc9; font-weight: bold;">
                    </div>
                </div>

                <div class="form-actions full">
                    <button type="submit" class="btn btn-primary" id="incoming-submit" data-label-create="<?= htmlspecialchars($messages['incoming_btn_save'] ?? 'Lưu', ENT_QUOTES, 'UTF-8') ?>" data-label-update="<?= htmlspecialchars($messages['incoming_btn_update'] ?? 'Cập nhật', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($messages['incoming_btn_save'] ?? 'Lưu', ENT_QUOTES, 'UTF-8') ?></button>
                    <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['incoming_btn_cancel'] ?? 'Hủy', ENT_QUOTES, 'UTF-8') ?></button>
                </div>
            </form>
        </div>
    </div>
 </div>

<!-- Export Modal -->
<div id="export-modal" class="modal-backdrop" aria-hidden="true" style="display: none;">
    <div class="modal">
        <div class="modal-header">
            <h4 id="export-modal-title"><?= htmlspecialchars($messages['export_modal_title'] ?? 'XUẤT FILE', ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close title="<?= htmlspecialchars($messages['incoming_btn_cancel'] ?? 'Đóng', ENT_QUOTES, 'UTF-8') ?>">&times;</button>
        </div>
        <div class="modal-body">
            <form id="export-form" class="form-grid grid-2" novalidate>
                <input type="hidden" id="export-doc-id" name="document_id">
                
                <div class="form-row">
                    <label for="export-quantity"><?= $messages['export_quantity_label'] ?? 'Số lượng <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M9 11H5a2 2 0 0 0-2 2v3c0 1.1.9 2 2 2h4m0-7h10a2 2 0 0 1 2 2v3c0 1.1-.9 2-2 2H9m0-7V9a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1"/></svg>
                        </span>
                        <input type="number" id="export-quantity" name="export_quantity" min="1" step="1" pattern="[0-9]*" inputmode="numeric" required placeholder="<?= htmlspecialchars($messages['export_quantity_placeholder'] ?? 'Nhập số lượng xuất', ENT_QUOTES, 'UTF-8') ?>">
                        <div class="number-spinner">
                            <div class="spinner-up" onclick="incrementExportQuantity()"></div>
                            <div class="spinner-down" onclick="decrementExportQuantity()"></div>
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label><?= $messages['export_recipient_label'] ?? 'Người nhận <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <div class="custom-select" id="export-recipient-custom-select">
                            <button type="button" class="custom-select-toggle" data-placeholder="<?= htmlspecialchars($messages['export_recipient_placeholder'] ?? 'Chọn người nhận', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($messages['export_recipient_placeholder'] ?? 'Chọn người nhận', ENT_QUOTES, 'UTF-8') ?></button>
                            <div class="custom-select-menu" role="listbox">
                                <?php 
                                $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng'); 
                                if (!empty($recipients)): 
                                    foreach ($recipients as $recipient): 
                                ?>
                                    <div class="custom-select-option" role="option" data-value="<?= htmlspecialchars($recipient['msnv'], ENT_QUOTES, 'UTF-8') ?>">
                                        <?= htmlspecialchars($isEng ? $recipient['name'] : $recipient['hoten'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php 
                                    endforeach; 
                                else: 
                                ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">
                                        <?= htmlspecialchars($messages['export_recipient_placeholder'] ?? 'Chọn người nhận', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" name="export_recipient" id="export-recipient-id" value="">
                        </div>
                    </div>
                </div>
                
                <div class="form-row full">
                    <label for="export-reason"><?= $messages['export_reason_label'] ?? 'Lý do xuất <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <textarea id="export-reason" name="export_reason" rows="4" required placeholder="<?= htmlspecialchars($messages['export_reason_placeholder'] ?? 'Nhập lý do xuất file', ENT_QUOTES, 'UTF-8') ?>"></textarea>
                    </div>
                </div>
                
                <div class="form-actions full">
                    <button type="submit" class="btn btn-primary"><?= htmlspecialchars($messages['export_btn_save'] ?? 'Xuất file', ENT_QUOTES, 'UTF-8') ?></button>
                    <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['incoming_btn_cancel'] ?? 'Hủy', ENT_QUOTES, 'UTF-8') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Import Modal -->
<div id="import-modal" class="modal-backdrop" aria-hidden="true" style="display: none;">
    <div class="modal">
        <div class="modal-header">
            <h4 id="import-modal-title"><?= htmlspecialchars($messages['import_modal_title'] ?? 'NHẬP FILE', ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close title="<?= htmlspecialchars($messages['incoming_btn_cancel'] ?? 'Đóng', ENT_QUOTES, 'UTF-8') ?>">&times;</button>
        </div>
        <div class="modal-body">
            <form id="import-form" class="form-grid grid-2" novalidate>
                <input type="hidden" id="import-doc-id" name="document_id">
                <input type="hidden" id="import-license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">
                
                <div class="form-row">
                    <label for="import-quantity"><?= $messages['import_quantity_label'] ?? 'Số lượng nhập <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M9 11H5a2 2 0 0 0-2 2v3c0 1.1.9 2 2 2h4m0-7h10a2 2 0 0 1 2 2v3c0 1.1-.9 2-2 2H9m0-7V9a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1"/></svg>
                        </span>
                        <input type="number" id="import-quantity" name="import_quantity" min="1" step="1" pattern="[0-9]*" inputmode="numeric" required placeholder="<?= htmlspecialchars($messages['import_quantity_placeholder'] ?? 'Nhập số lượng', ENT_QUOTES, 'UTF-8') ?>">
                        <div class="number-spinner">
                            <div class="spinner-up" onclick="incrementImportQuantity()"></div>
                            <div class="spinner-down" onclick="decrementImportQuantity()"></div>
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label><?= $messages['import_sender_label'] ?? 'Người gửi <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <div class="custom-select" id="import-sender-custom-select">
                            <button type="button" class="custom-select-toggle" data-placeholder="<?= htmlspecialchars($messages['import_sender_placeholder'] ?? 'Chọn người gửi', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($messages['import_sender_placeholder'] ?? 'Chọn người gửi', ENT_QUOTES, 'UTF-8') ?></button>
                            <div class="custom-select-menu" role="listbox">
                                <?php 
                                $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng'); 
                                if (!empty($recipients)): 
                                    foreach ($recipients as $recipient): 
                                ?>
                                    <div class="custom-select-option" role="option" data-value="<?= htmlspecialchars($recipient['msnv'], ENT_QUOTES, 'UTF-8') ?>">
                                        <?= htmlspecialchars($isEng ? $recipient['name'] : $recipient['hoten'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php 
                                    endforeach; 
                                else: 
                                ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">
                                        <?= htmlspecialchars($messages['import_sender_placeholder'] ?? 'Chọn người gửi', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" name="import_sender" id="import-sender-id" value="">
                        </div>
                    </div>
                </div>
                
                <div class="form-row full">
                    <label for="import-reason"><?= $messages['import_reason_label'] ?? 'Lý do nhập <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <textarea id="import-reason" name="import_reason" rows="4" required placeholder="<?= htmlspecialchars($messages['import_reason_placeholder'] ?? 'Nhập lý do nhập file', ENT_QUOTES, 'UTF-8') ?>"></textarea>
                    </div>
                </div>
                
                <div class="form-actions full">
                    <button type="submit" class="btn btn-primary"><?= htmlspecialchars($messages['import_btn_save'] ?? 'Nhập file', ENT_QUOTES, 'UTF-8') ?></button>
                    <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['incoming_btn_cancel'] ?? 'Hủy', ENT_QUOTES, 'UTF-8') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Export Excel Modal -->
<div class="modal-backdrop" id="export-excel-modal" aria-hidden="true">
    <div class="modal">
        <div class="modal-header">
            <h4>
                <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 2; vertical-align: middle; margin-right: 8px;">
                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                    <polyline points="14,2 14,8 20,8"/>
                    <line x1="12" y1="18" x2="12" y2="12"/>
                    <line x1="9" y1="15" x2="15" y2="15"/>
                </svg>
                <?= htmlspecialchars($messages['excel_export_modal_title'] ?? 'XUẤT EXCEL - CÔNG VĂN ĐẾN', ENT_QUOTES, 'UTF-8') ?>
            </h4>
            <button type="button" class="modal-close" data-modal-close title="<?= htmlspecialchars($messages['excel_export_btn_close'] ?? 'Đóng', ENT_QUOTES, 'UTF-8') ?>">&times;</button>
        </div>
        <div class="modal-body">
            <form method="post" action="modules/incoming/export_incoming.php" class="form-grid grid-2" id="export-excel-form">
                <input type="hidden" name="action" value="export">
                <input type="hidden" name="license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">
                
                <div class="form-row full">
                    <label style="color: #7adcc9; font-weight: 600; margin-bottom: 12px; display: block;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor; vertical-align: middle; margin-right: 6px;">
                            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        <?= htmlspecialchars($messages['excel_export_modal_subtitle'] ?? 'Chọn điều kiện xuất:', ENT_QUOTES, 'UTF-8') ?>
                    </label>
                </div>
                
                <!-- Xuất tất cả -->
                <div class="form-row full">
                    <label style="display: flex; align-items: center; padding: 12px; background: rgba(122, 220, 201, 0.08); border: 1px solid rgba(122, 220, 201, 0.2); border-radius: 8px; cursor: pointer; transition: all 0.2s;">
                        <input type="radio" name="export_type" value="all" checked style="margin-right: 10px; width: 18px; height: 18px; cursor: pointer;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor; vertical-align: middle; margin-right: 8px;">
                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                            <polyline points="14,2 14,8 20,8"/>
                            <line x1="16" y1="13" x2="8" y2="13"/>
                            <line x1="16" y1="17" x2="8" y2="17"/>
                        </svg>
                        <span style="color: #e8fbf6; font-weight: 500;"><?= htmlspecialchars($messages['excel_export_all_documents'] ?? 'Xuất tất cả công văn', ENT_QUOTES, 'UTF-8') ?></span>
                    </label>
                </div>
                
                <!-- Theo công ty -->
                <div class="form-row full">
                    <label style="display: flex; align-items: center; padding: 12px; background: rgba(122, 220, 201, 0.08); border: 1px solid rgba(122, 220, 201, 0.2); border-radius: 8px; cursor: pointer; transition: all 0.2s;">
                        <input type="radio" name="export_type" value="company" style="margin-right: 10px; width: 18px; height: 18px; cursor: pointer;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor; vertical-align: middle; margin-right: 8px;">
                            <path d="M3 21h18"/>
                            <path d="M5 21V7l8-4v18"/>
                            <path d="M19 21V11l-6-4"/>
                        </svg>
                        <span style="color: #e8fbf6; font-weight: 500;"><?= htmlspecialchars($messages['excel_export_by_company'] ?? 'Theo công ty', ENT_QUOTES, 'UTF-8') ?></span>
                    </label>
                    <div id="company-select-container" style="margin-top: 10px; display: none;">
                        <div class="custom-select" id="export-company-custom-select">
                            <button type="button" class="custom-select-toggle" data-placeholder="<?= htmlspecialchars($messages['excel_export_select_company'] ?? 'Chọn công ty', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($messages['excel_export_select_company'] ?? 'Chọn công ty', ENT_QUOTES, 'UTF-8') ?></button>
                            <div class="custom-select-menu" role="listbox">
                                <?php 
                                $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng'); 
                                if (!empty($companies)): 
                                    foreach ($companies as $company): 
                                ?>
                                    <div class="custom-select-option" role="option" data-value="<?= (int)$company['id'] ?>">
                                        <?= htmlspecialchars($isEng ? $company['eng'] : $company['vn'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php 
                                    endforeach; 
                                else: 
                                ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">
                                        <?= htmlspecialchars($messages['excel_export_select_company'] ?? 'Chọn công ty', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" name="company_id" id="export-company-select" value="">
                        </div>
                    </div>
                </div>
                
                <!-- Theo mã số văn bản -->
                <div class="form-row full">
                    <label style="display: flex; align-items: center; padding: 12px; background: rgba(122, 220, 201, 0.08); border: 1px solid rgba(122, 220, 201, 0.2); border-radius: 8px; cursor: pointer; transition: all 0.2s;">
                        <input type="radio" name="export_type" value="document_number" style="margin-right: 10px; width: 18px; height: 18px; cursor: pointer;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor; vertical-align: middle; margin-right: 8px;">
                            <path d="M4 4h16v4H4zM4 12h10v8H4zM16 12h4v8h-4z"/>
                        </svg>
                        <span style="color: #e8fbf6; font-weight: 500;"><?= htmlspecialchars($messages['excel_export_by_document_number'] ?? 'Theo mã số văn bản', ENT_QUOTES, 'UTF-8') ?></span>
                    </label>
                    <div id="document-number-container" style="margin-top: 10px; display: none;">
                        <input type="text" name="document_number" id="export-document-number" placeholder="<?= htmlspecialchars($messages['excel_export_document_number_placeholder'] ?? 'Nhập mã số văn bản', ENT_QUOTES, 'UTF-8') ?>" style="width: 100%; padding: 10px; background: rgba(11, 31, 34, 0.65); border: 1px solid rgba(122, 220, 201, 0.28); border-radius: 8px; color: #e8fbf6;">
                    </div>
                </div>
                
                <!-- Theo ngày hiệu lực -->
                <div class="form-row full">
                    <label style="display: flex; align-items: center; padding: 12px; background: rgba(122, 220, 201, 0.08); border: 1px solid rgba(122, 220, 201, 0.2); border-radius: 8px; cursor: pointer; transition: all 0.2s;">
                        <input type="radio" name="export_type" value="date_range" style="margin-right: 10px; width: 18px; height: 18px; cursor: pointer;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor; vertical-align: middle; margin-right: 8px;">
                            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                            <line x1="16" y1="2" x2="16" y2="6"/>
                            <line x1="8" y1="2" x2="8" y2="6"/>
                            <line x1="3" y1="10" x2="21" y2="10"/>
                        </svg>
                        <span style="color: #e8fbf6; font-weight: 500;"><?= htmlspecialchars($messages['excel_export_by_effective_date'] ?? 'Theo ngày hiệu lực', ENT_QUOTES, 'UTF-8') ?></span>
                    </label>
                    <div id="date-range-container" style="margin-top: 10px; display: none;">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                            <div>
                                <label style="color: #7adcc9; font-size: 12px; margin-bottom: 4px; display: block;"><?= htmlspecialchars($messages['excel_export_date_from_placeholder'] ?? 'Từ ngày', ENT_QUOTES, 'UTF-8') ?></label>
                                <input type="date" name="date_from" id="export-date-from" style="width: 100%; padding: 10px; background: rgba(11, 31, 34, 0.65); border: 1px solid rgba(122, 220, 201, 0.28); border-radius: 8px; color: #e8fbf6;">
                            </div>
                            <div>
                                <label style="color: #7adcc9; font-size: 12px; margin-bottom: 4px; display: block;"><?= htmlspecialchars($messages['excel_export_date_to_placeholder'] ?? 'Đến ngày', ENT_QUOTES, 'UTF-8') ?></label>
                                <input type="date" name="date_to" id="export-date-to" style="width: 100%; padding: 10px; background: rgba(11, 31, 34, 0.65); border: 1px solid rgba(122, 220, 201, 0.28); border-radius: 8px; color: #e8fbf6;">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-actions full">
                    <button type="submit" class="btn btn-primary" style="background: linear-gradient(135deg, rgba(122, 220, 201, 0.35), rgba(100, 167, 166, 0.45)); border: 1px solid rgba(122, 220, 201, 0.5); color: #e8fbf6;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor; vertical-align: middle; margin-right: 6px;">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                            <polyline points="7 10 12 15 17 10"/>
                            <line x1="12" y1="15" x2="12" y2="3"/>
                        </svg>
                        <?= htmlspecialchars($messages['excel_export_btn_export'] ?? 'Xuất Excel', ENT_QUOTES, 'UTF-8') ?>
                    </button>
                    <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['excel_export_btn_close'] ?? 'Đóng', ENT_QUOTES, 'UTF-8') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Set language and tooltips for JavaScript
window.APP_LANG = '<?= ($_SESSION['lang'] ?? 'vn') ?>';
window.PDF_TOOLTIPS = {
    vn: {
        prev: '<?= htmlspecialchars($messages['pdf_tooltip_prev'] ?? 'Trang trước', ENT_QUOTES) ?>',
        next: '<?= htmlspecialchars($messages['pdf_tooltip_next'] ?? 'Trang sau', ENT_QUOTES) ?>',
        zoom_out: '<?= htmlspecialchars($messages['pdf_tooltip_zoom_out'] ?? 'Thu nhỏ', ENT_QUOTES) ?>',
        zoom_in: '<?= htmlspecialchars($messages['pdf_tooltip_zoom_in'] ?? 'Phóng to', ENT_QUOTES) ?>',
        rotate: '<?= htmlspecialchars($messages['pdf_tooltip_rotate'] ?? 'Xoay', ENT_QUOTES) ?>',
        download: '<?= htmlspecialchars($messages['pdf_tooltip_download'] ?? 'Tải xuống', ENT_QUOTES) ?>',
        print: '<?= htmlspecialchars($messages['pdf_tooltip_print'] ?? 'In', ENT_QUOTES) ?>',
        close: '<?= htmlspecialchars($messages['pdf_tooltip_close'] ?? 'Đóng', ENT_QUOTES) ?>'
    },
    eng: {
        prev: 'Previous page',
        next: 'Next page',
        zoom_out: 'Zoom out',
        zoom_in: 'Zoom in',
        rotate: 'Rotate',
        download: 'Download',
        print: 'Print',
        close: 'Close'
    }
};
// Function to get current language from various sources
window.getCurrentLanguage = function() {
    // Check URL parameter first
    const urlParams = new URLSearchParams(window.location.search);
    const urlLang = urlParams.get('lang');
    if (urlLang && ['vn', 'eng'].includes(urlLang)) {
        return urlLang;
    }
    
    // Check session language from PHP
    if (window.APP_LANG && ['vn', 'eng'].includes(window.APP_LANG)) {
        return window.APP_LANG;
    }
    
    // Default to Vietnamese
    return 'vn';
};

// Helper function to get tooltip text
window.getTooltipText = function(key) {
    const currentLang = window.getCurrentLanguage();
    const tooltips = window.PDF_TOOLTIPS && window.PDF_TOOLTIPS[currentLang];
    if (tooltips && tooltips[key]) {
        return tooltips[key];
    }
    // Fallback to Vietnamese
    const vnTooltips = window.PDF_TOOLTIPS && window.PDF_TOOLTIPS['vn'];
    if (vnTooltips && vnTooltips[key]) {
        return vnTooltips[key];
    }
    // Final fallback
    const fallbacks = {
        prev: 'Trang trước',
        next: 'Trang sau', 
        zoom_out: 'Thu nhỏ',
        zoom_in: 'Phóng to',
        rotate: 'Xoay',
        download: 'Tải xuống',
        print: 'In',
        close: 'Đóng'
    };
    return fallbacks[key] || key;
};
</script>

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

<script>
// Simple Search Form functionality for Incoming Documents
document.addEventListener('DOMContentLoaded', function() {
    const searchForm = document.getElementById('incoming-search-form');
    const searchInput = document.getElementById('search-query-incoming');
    const searchButton = document.getElementById('search-submit-btn');
    
    // Handle search form submission
    if (searchForm && searchInput) {
        searchForm.addEventListener('submit', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const query = searchInput.value.trim();
            
            if (query) {
                window.location.href = 'index.php?incoming&search_query=' + encodeURIComponent(query);
            } else {
                window.location.href = 'index.php?incoming';
            }
        });
        
        // Also handle button click directly
        if (searchButton) {
            searchButton.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                const query = searchInput.value.trim();
                
                if (query) {
                    window.location.href = 'index.php?incoming&search_query=' + encodeURIComponent(query);
                } else {
                    window.location.href = 'index.php?incoming';
                }
            });
            
            // Add mousedown event as backup
            searchButton.addEventListener('mousedown', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                const query = searchInput.value.trim();
                
                if (query) {
                    window.location.href = 'index.php?incoming&search_query=' + encodeURIComponent(query);
                } else {
                    window.location.href = 'index.php?incoming';
                }
            });
        }
    }
    
    // Add focus effect to input
    if (searchInput) {
        searchInput.addEventListener('focus', function() {
            this.style.borderColor = 'rgba(124, 220, 201, 0.5)';
            this.style.boxShadow = '0 0 0 3px rgba(124, 220, 201, 0.1)';
        });
        
        searchInput.addEventListener('blur', function() {
            this.style.borderColor = 'rgba(255, 255, 255, 0.1)';
            this.style.boxShadow = 'none';
        });
        
        // Allow Enter key to submit
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const query = searchInput.value.trim();
                if (query) {
                    window.location.href = 'index.php?incoming&search_query=' + encodeURIComponent(query);
                } else {
                    window.location.href = 'index.php?incoming';
                }
            }
        });
    }
    
    // Add hover effect to search button
    if (searchButton) {
        searchButton.addEventListener('mouseenter', function() {
            this.style.background = '#92e4d4';
            this.style.transform = 'translateY(-50%) scale(1.05)';
        });
        
        searchButton.addEventListener('mouseleave', function() {
            this.style.background = '#7adcc9';
            this.style.transform = 'translateY(-50%)';
        });
    }
});
</script>

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

.incoming-panel .incoming-controls .incoming-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;
    width: auto !important;
}

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

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

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

.incoming-panel .incoming-controls .incoming-btn.btn-primary {
    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;
}

.incoming-panel .incoming-controls .incoming-btn.btn-primary: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;
}

.incoming-panel .incoming-controls .incoming-btn.btn-secondary {
    background: rgba(17, 46, 51, 0.6) !important;
    color: #7adcc9 !important;
    border: 1px solid rgba(122, 220, 201, 0.3) !important;
}

.incoming-panel .incoming-controls .incoming-btn.btn-secondary:hover {
    background: rgba(17, 46, 51, 0.8) !important;
    border-color: rgba(122, 220, 201, 0.5) !important;
    transform: translateY(-1px) !important;
    color: #e8fbf6 !important;
}

.incoming-panel .incoming-controls .incoming-btn.btn-success {
    background: linear-gradient(135deg, rgba(122, 220, 201, 0.25), rgba(100, 167, 166, 0.4)) !important;
    color: #e8fbf6 !important;
    border: 1px solid rgba(122, 220, 201, 0.45) !important;
}

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

.incoming-panel .incoming-controls .incoming-log-link {
    text-decoration: none !important;
}

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

@media (max-width: 768px) {
    .incoming-panel .incoming-controls {
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: center;
        gap: 10px;
    }

    .incoming-panel .incoming-controls .incoming-btn {
        flex: 1 1 calc(50% - 10px);
        max-width: calc(50% - 10px);
        width: calc(50% - 10px) !important;
        justify-content: center !important;
        font-size: 12px !important;
        padding: 6px 12px !important;
    }

    .incoming-panel .incoming-controls .incoming-btn .btn-text-wrapper {
        font-size: 12px !important;
    }

    .incoming-panel .incoming-controls .incoming-btn:last-child:nth-child(odd) {
        flex: 1 1 100%;
        max-width: 100%;
        width: 100% !important;
    }
}
</style>

<script>
// Show success/error message from URL parameter (same behavior as Company/Category)
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>

<script>
// Export Excel Modal Handler
(function() {
    const exportModal = document.getElementById('export-excel-modal');
    const exportButton = document.querySelector('[data-export-open="true"]');
    const closeButtons = exportModal.querySelectorAll('[data-modal-close]');
    const radioButtons = document.querySelectorAll('input[name="export_type"]');
    
    // Open modal
    if (exportButton) {
        exportButton.addEventListener('click', function() {
            exportModal.classList.add('show');
            exportModal.setAttribute('aria-hidden', 'false');
            
            // Setup custom select for export company when modal opens
            setTimeout(function() {
                setupExportCompanyCustomSelect();
            }, 100);
        });
    }
    
    // Close modal
    closeButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            exportModal.classList.remove('show');
            exportModal.setAttribute('aria-hidden', 'true');
        });
    });
    
    // Close on backdrop click
    exportModal.addEventListener('click', function(e) {
        if (e.target === exportModal) {
            exportModal.classList.remove('show');
            exportModal.setAttribute('aria-hidden', 'true');
        }
    });
    
    // Toggle input containers based on selected radio
    radioButtons.forEach(radio => {
        radio.addEventListener('change', function() {
            // Hide all containers
            document.getElementById('company-select-container').style.display = 'none';
            document.getElementById('document-number-container').style.display = 'none';
            document.getElementById('date-range-container').style.display = 'none';
            
            // Show relevant container
            if (this.value === 'company') {
                document.getElementById('company-select-container').style.display = 'block';
            } else if (this.value === 'document_number') {
                document.getElementById('document-number-container').style.display = 'block';
            } else if (this.value === 'date_range') {
                document.getElementById('date-range-container').style.display = 'block';
            }
        });
    });
    
    // Form validation and normal submit (no AJAX)
    const exportForm = document.getElementById('export-excel-form');
    if (exportForm) {
        exportForm.addEventListener('submit', function(e) {
            const exportType = document.querySelector('input[name="export_type"]:checked').value;
            
                // Validation - prevent submit if invalid
                if (exportType === 'company') {
                    const companyId = document.getElementById('export-company-select').value;
                    if (!companyId) {
                        e.preventDefault();
                        const errorMsg = window.__MESSAGES__?.['excel_export_validation_company_required'] || 'Vui lòng chọn công ty';
                        const errorTitle = window.__MESSAGES__?.['error_notification_title'] || 'THÔNG BÁO';
                        if (window.showToast) {
                            window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + errorMsg);
                        } else {
                            alert(errorMsg);
                        }
                        return false;
                    }
                } else if (exportType === 'document_number') {
                    const docNumber = document.getElementById('export-document-number').value.trim();
                    if (!docNumber) {
                        e.preventDefault();
                        const errorMsg = window.__MESSAGES__?.['excel_export_validation_document_number_required'] || 'Vui lòng nhập mã số văn bản';
                        const errorTitle = window.__MESSAGES__?.['error_notification_title'] || 'THÔNG BÁO';
                        if (window.showToast) {
                            window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + errorMsg);
                        } else {
                            alert(errorMsg);
                        }
                        return false;
                    }
                } else if (exportType === 'date_range') {
                    const dateFrom = document.getElementById('export-date-from').value;
                    const dateTo = document.getElementById('export-date-to').value;
                    if (!dateFrom || !dateTo) {
                        e.preventDefault();
                        const errorMsg = window.__MESSAGES__?.['excel_export_validation_date_range_required'] || 'Vui lòng chọn khoảng thời gian';
                        const errorTitle = window.__MESSAGES__?.['error_notification_title'] || 'THÔNG BÁO';
                        if (window.showToast) {
                            window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + errorMsg);
                        } else {
                            alert(errorMsg);
                        }
                        return false;
                    }
                    if (new Date(dateFrom) > new Date(dateTo)) {
                        e.preventDefault();
                        const errorMsg = window.__MESSAGES__?.['excel_export_validation_date_from_after_to'] || 'Ngày bắt đầu phải nhỏ hơn ngày kết thúc';
                        const errorTitle = window.__MESSAGES__?.['error_notification_title'] || 'THÔNG BÁO';
                        if (window.showToast) {
                            window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + errorMsg);
                        } else {
                            alert(errorMsg);
                        }
                        return false;
                    }
                }
            
            // Just submit the form normally - browser will handle download
            // Close modal after a short delay
            setTimeout(() => {
                exportModal.classList.remove('show');
                exportModal.setAttribute('aria-hidden', 'true');
            }, 500);
        });
        }
    })();

    // Setup custom select for export company
    function setupExportCompanyCustomSelect() {
        var custom = document.getElementById('export-company-custom-select');
        if (!custom) return;
        
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('export-company-select');
        if (!toggle || !menu) return;
        
        var placeholder = toggle.getAttribute('data-placeholder') || 'Chọn công ty';
        var closeOnScroll = null; 
        var closeOnResize = null;

        var anchorParent = null; 
        var anchorNext = null; 
        var isPortaled = false;
        
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { 
                    anchorParent.insertBefore(menu, anchorNext); 
                } else { 
                    anchorParent.appendChild(menu); 
                }
            }
            isPortaled = false;
        }
        
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - width - pad);
            }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { 
                window.removeEventListener('scroll', closeOnScroll, true); 
                closeOnScroll = null; 
            }
            if (closeOnResize) { 
                window.removeEventListener('resize', closeOnResize); 
                closeOnResize = null; 
            }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ 
                    if (menu.contains(ev.target)) return; 
                    closeAll(); 
                };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ 
                it.classList.toggle('is-selected', it === opt); 
            });
            closeAll();
        });

        // Close on outside click
        document.addEventListener('click', function(e){
            if (!custom.contains(e.target)) {
                closeAll();
            }
        });
    }
</script>

<script>
// Load messages for JavaScript
window.__MESSAGES__ = <?= json_encode($messages, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
</script>
