<?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'] ?? ''));
// Next outgoing document ID
$nextOutgoingId = 1;
try {
    $conn = db_connect();
    if ($conn) {
        $stmt = sqlsrv_query($conn, 'SELECT ISNULL(MAX(Id), 0) + 1 as next_id FROM GoDocument');
        if ($stmt !== false) {
            if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $nextOutgoingId = (int)($row['next_id'] ?? 1);
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { /* ignore */ }
// Load companies
$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 */ }

// Load categories
$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 doc types
$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 page types
$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 outgoing documents list
$allDocuments = [];
$searchQuery = !empty($_GET['search_query']) ? trim($_GET['search_query']) : '';

try {
    $conn = db_connect();
    if ($conn) {
        $sql = "SELECT g.Id, g.ID_Symbol, g.TitleVi, g.Issuer, g.EffectiveDate, g.FileUrl,
                       g.Summary, g.DocType, g.TypeDoc, g.Quantity,
                       g.ID_Company, g.FileStorage, g.Notes,
                       c.Name_Vn as CompanyName_Vn, c.Name_Eng as CompanyName_Eng
                FROM GoDocument g
                LEFT JOIN Company c ON g.ID_Company = c.ID_Company";
        
        $parameters = [];
        
        // Simple search: search in symbol, title, and receiver
        if (!empty($searchQuery)) {
            $sql .= " WHERE (g.ID_Symbol LIKE ? OR g.TitleVi LIKE ? OR g.Issuer LIKE ?)";
            $searchPattern = '%' . $searchQuery . '%';
            $parameters = [$searchPattern, $searchPattern, $searchPattern];
        }
        
        $sql .= " ORDER BY g.EffectiveDate DESC, g.Id DESC";
        
        if (!empty($parameters)) {
            $stmt = sqlsrv_prepare($conn, $sql, $parameters);
            if ($stmt && sqlsrv_execute($stmt)) {
                error_log("Outgoing search 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'] ?? ''),
                        'receiver' => (string)($row['Issuer'] ?? ''),
                        'effective_date' => $row['EffectiveDate'] ? date('d/m/Y', strtotime($row['EffectiveDate'])) : '',
                        'file_url' => (string)($row['FileUrl'] ?? ''),
                        'summary' => (string)($row['Summary'] ?? ''),
                        'doctype' => (string)($row['DocType'] ?? ''),
                        'typedoc' => (string)($row['TypeDoc'] ?? ''),
                        'quantity' => (int)($row['Quantity'] ?? 0),
                        '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'] ?? ''),
                    ];
                }
                sqlsrv_free_stmt($stmt);
            } else {
                $errors = sqlsrv_errors();
                error_log("Outgoing search SQL query failed: " . print_r($errors, true));
            }
        } else {
            $stmt = sqlsrv_query($conn, $sql);
            if ($stmt !== false) {
                error_log("Outgoing 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'] ?? ''),
                        'receiver' => (string)($row['Issuer'] ?? ''),
                        'effective_date' => $row['EffectiveDate'] ? date('d/m/Y', strtotime($row['EffectiveDate'])) : '',
                        'file_url' => (string)($row['FileUrl'] ?? ''),
                        'summary' => (string)($row['Summary'] ?? ''),
                        'doctype' => (string)($row['DocType'] ?? ''),
                        'typedoc' => (string)($row['TypeDoc'] ?? ''),
                        'quantity' => (int)($row['Quantity'] ?? 0),
                        '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'] ?? ''),
                    ];
                }
                sqlsrv_free_stmt($stmt);
            } else {
                $errors = sqlsrv_errors();
                error_log("Outgoing SQL query failed: " . print_r($errors, true));
            }
        }
        db_disconnect($conn);
    }
} catch (Throwable $e) { 
    error_log("Outgoing 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("Outgoing 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">
    <div class="panel wide">
        <header class="panel-header">
            <h3><?= htmlspecialchars($messages['control_nav_outgoing_documents'], ENT_QUOTES, 'UTF-8') ?></h3>
            <div class="panel-controls">
                <button type="button" class="btn btn-primary" data-outgoing-open="create"><?= htmlspecialchars($messages['incoming_btn_add_new'] ?? 'Thêm mới', ENT_QUOTES, 'UTF-8') ?></button>
        </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; ?>
        </header>
        
        <!-- Simple Search Bar (same UI/behavior as Incoming) -->
        <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="inline-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" 
                           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($_GET['search_query'] ?? '', 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: 14px; 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>
            </form>
        </div>
        <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_effective_date'] ?? 'Ngày hiệu lực', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['incoming_col_issuer'] ?? 'Cơ quan cấp', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['incoming_form_summary_label'] ?? 'Tóm tắt nội dung', 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_effective_date'] ?? 'Ngày hiệu lực', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['effective_date'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['incoming_col_issuer'] ?? 'Cơ quan cấp', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['receiver'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['incoming_form_summary_label'] ?? 'Tóm tắt nội dung', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($doc['summary'], 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-outgoing-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-outgoing-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-danger" data-outgoing-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?outgoing&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?outgoing&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?outgoing&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?outgoing&page=<?= $totalPages ?>" class="pagination-number"><?= $totalPages ?></a>
                    <?php endif; ?>
                </div>
                
                <?php if ($currentPage < $totalPages): ?>
                    <a href="index.php?outgoing&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>

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

                <div class="form-row">
                    <label for="out-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="out-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="out-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="out-code" name="document_code" value="<?= $nextOutgoingId ?>" placeholder="Tự động tạo" readonly style="color: #7adcc9; font-weight: bold;">
                    </div>
                </div>
                <div class="form-row full">
                    <label for="out-title"><?= $messages['incoming_form_title_label'] ?? 'Tiêu đề <span class="required-asterisk">*</span>' ?></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="out-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="out-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="out-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 for="out-to"><?= $messages['outgoing_form_receiver_label'] ?? 'Cơ quan nhận <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="out-to" name="receiver" placeholder="<?= htmlspecialchars($messages['outgoing_form_receiver_placeholder'] ?? 'Nhập cơ quan cấp', ENT_QUOTES, 'UTF-8') ?>" required>
                    </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="out-doc-type-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="out-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="out-docpage-type-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="out-type-doc-id" value="">
                        </div>
                    </div>
                </div>
                <div class="form-row">
                    <label for="out-date"><?= $messages['incoming_form_effective_label'] ?? 'Ngày đi <span class="required-asterisk">*</span>' ?></label>
                    <div class="input-wrap">
                        <span class="icon date-icon" data-target="out-date">
                            <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="out-date" 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="out-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="out-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"></div>
                            <div class="spinner-down"></div>
                        </div>
                    </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="out-company-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 $cp): ?>
                                    <div class="custom-select-option" role="option" data-value="<?= (int)$cp['id'] ?>">
                                        <?= htmlspecialchars($isEng ? $cp['eng'] : $cp['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="out-company-id" value="">
                        </div>
                    </div>
                </div>
                <div class="form-row">
                    <label for="out-file-url"><?= htmlspecialchars($messages['incoming_form_file_link_label'] ?? 'PDF Scan', 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"/></svg>
                        </span>
                        <input type="text" id="out-file-url" name="file_url" placeholder="<?= htmlspecialchars($messages['incoming_form_file_link_placeholder'] ?? 'Link file PDF (nếu có)', ENT_QUOTES, 'UTF-8') ?>" style="padding-right: 80px;" readonly>
                        <button type="button" class="view-pdf-icon-btn" style="display:none" title="Xem file PDF">
                            <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" class="upload-pdf-icon-btn" title="Upload PDF">
                            <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" accept=".pdf" style="display:none">
                    </div>
                </div>
                <div class="form-row">
                    <label for="out-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="M3 4h18v6H3zM3 14h18v6H3z"/></svg>
                        </span>
                        <input type="text" id="out-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="out-notes"><?= htmlspecialchars($messages['incoming_form_notes_label'] ?? 'Ghi chú', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <textarea id="out-notes" name="notes" rows="3" placeholder="<?= htmlspecialchars($messages['incoming_form_notes_placeholder'] ?? 'Nhập ghi chú', ENT_QUOTES, 'UTF-8') ?>"></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="out-id-by"><?= 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"><circle cx="12" cy="7" r="4"/><path d="M5.5 22a6.5 6.5 0 0 1 13 0"/></svg>
                        </span>
                        <input type="text" id="out-id-by" 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="out-created"><?= 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="out-created" name="created_at" value="<?= htmlspecialchars($currentDateTime, ENT_QUOTES, 'UTF-8') ?>" readonly style="color: #7adcc9; font-weight: bold;">
                    </div>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary" id="outgoing-submit" data-label-save="<?= 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>

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

<script>
// Simple Search Form functionality (mirrors Incoming)
document.addEventListener('DOMContentLoaded', function() {
    const searchForm = document.getElementById('inline-search-form');
    const searchInput = document.getElementById('search-query');
    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) {
                // Redirect with search query
                window.location.href = 'index.php?outgoing&search_query=' + encodeURIComponent(query);
            } else {
                // If empty, redirect to show all
                window.location.href = 'index.php?outgoing';
            }
        });

        // Button click handler
        if (searchButton) {
            searchButton.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const query = searchInput.value.trim();
                if (query) {
                    window.location.href = 'index.php?outgoing&search_query=' + encodeURIComponent(query);
                } else {
                    window.location.href = 'index.php?outgoing';
                }
            });
        }
        
        // Enter key submit
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const query = searchInput.value.trim();
                if (query) {
                    window.location.href = 'index.php?outgoing&search_query=' + encodeURIComponent(query);
                } else {
                    window.location.href = 'index.php?outgoing';
                }
            }
        });
    }
    
    // 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';
        });
    }
});
</script>

<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>
