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

require_once __DIR__ . '/config/database.php';

// Ensure messages are loaded
if (!isset($messages) || !is_array($messages)) {
    require_once __DIR__ . '/config/messages.php';
    $messages = load_messages();
}

// Load workshift data from database
$workshifts = [];
$grouptypeOptions = []; // Group type options from Properti table
$departmentOptions = []; // Department options from Posion table

try {
    $conn = db_connect();
    if ($conn) {
        $sql = "SELECT Id, name, grouptype, color, in1, out1, in2, out2, total, apply, sang, trua, chieu, dem, Ngaycong, time, Edit_by 
                FROM Workshift 
                ORDER BY Id DESC";
        $stmt = sqlsrv_query($conn, $sql);
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $workshifts[] = $row;
            }
            sqlsrv_free_stmt($stmt);
        }

        // Load group type options from Properti table (Id = 2)
        $isEng = (($_SESSION['lang'] ?? 'vn') === 'eng');
        $sqlGrouptype = "SELECT Type, Name_VN, Name_ENG FROM Properti WHERE Id = 2 ORDER BY Type ASC";
        $stmtGrouptype = sqlsrv_query($conn, $sqlGrouptype);
        if ($stmtGrouptype !== false) {
            while ($row = sqlsrv_fetch_array($stmtGrouptype, SQLSRV_FETCH_ASSOC)) {
                $type = isset($row['Type']) ? (int)$row['Type'] : 0;
                $nameVn = isset($row['Name_VN']) ? trim((string)$row['Name_VN']) : '';
                $nameEng = isset($row['Name_ENG']) ? trim((string)$row['Name_ENG']) : '';
                $displayName = $isEng ? ($nameEng !== '' ? $nameEng : $nameVn) : ($nameVn !== '' ? $nameVn : $nameEng);
                if ($displayName !== '') {
                    $grouptypeOptions[] = [
                        'type' => $type,
                        'label' => $displayName
                    ];
                }
            }
            sqlsrv_free_stmt($stmtGrouptype);
        }

        // Load department options from Posion table
        $departmentSeen = [];
        $sqlDepartment = "
            SELECT DISTINCT
                Khoi,
                Bo_phan
            FROM Posion
            WHERE Bo_phan IS NOT NULL AND LTRIM(RTRIM(Bo_phan)) <> ''
            ORDER BY Khoi, Bo_phan
        ";
        $stmtDepartment = sqlsrv_query($conn, $sqlDepartment);
        if ($stmtDepartment !== false) {
            while ($row = sqlsrv_fetch_array($stmtDepartment, SQLSRV_FETCH_ASSOC)) {
                $branch = isset($row['Khoi']) ? trim((string)$row['Khoi']) : '';
                $dept = isset($row['Bo_phan']) ? trim((string)$row['Bo_phan']) : '';
                if ($dept === '') {
                    continue;
                }
                $key = $branch . '|' . $dept;
                if (isset($departmentSeen[$key])) {
                    continue;
                }
                $departmentSeen[$key] = true;
                $label = $branch !== '' ? ($branch . ' - ' . $dept) : $dept;
                $departmentOptions[] = [
                    'value' => $dept,
                    'label' => $label
                ];
            }
            sqlsrv_free_stmt($stmtDepartment);
        }

        db_disconnect($conn);
    }
} catch (Throwable $e) {
    error_log('Failed to fetch workshift data: ' . $e->getMessage());
}

// Helper function to format time
function format_time($timeValue) {
    if ($timeValue === null) return '';
    if ($timeValue instanceof DateTime) {
        return $timeValue->format('H:i:s');
    }
    if (is_string($timeValue)) {
        return $timeValue;
    }
    return '';
}

// Helper function to format date
function format_date($dateValue) {
    if ($dateValue === null) return '';
    if ($dateValue instanceof DateTime) {
        return $dateValue->format('d/m/Y');
    }
    if (is_string($dateValue)) {
        try {
            $dt = new DateTime($dateValue);
            return $dt->format('d/m/Y');
        } catch (Exception $e) {
            return $dateValue;
        }
    }
    return '';
}

// Pagination
$allowedPageSizes = [5, 10, 20, 50, 100];
$pageSize = isset($_GET['page_size']) ? (int)$_GET['page_size'] : (isset($_SESSION['shift_page_size']) ? (int)$_SESSION['shift_page_size'] : 10);
if (!in_array($pageSize, $allowedPageSizes, true)) { $pageSize = 10; }
$_SESSION['shift_page_size'] = $pageSize;

$itemsPerPage = $pageSize;
$currentPage = (int)($_GET['page'] ?? 1);
$currentPage = max(1, $currentPage);
$totalItems = count($workshifts);
$totalPages = ($itemsPerPage > 0) ? (int)ceil($totalItems / $itemsPerPage) : 1;
$offset = ($currentPage - 1) * $itemsPerPage;
$pageWorkshifts = array_slice($workshifts, $offset, $itemsPerPage);
?>

<section class="panel-grid shift-grid">
    <div class="panel wide shift-panel">
        <header class="panel-header">
            <h3 style="text-transform: uppercase;"><?= htmlspecialchars($messages['control_nav_workshift'] ?? 'Ca làm việc', ENT_QUOTES, 'UTF-8') ?></h3>
            <div class="panel-controls shift-controls">
                <button type="button" class="btn btn-primary shift-btn" data-shift-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['shift_btn_add_new'] ?? 'Thêm mới', ENT_QUOTES, 'UTF-8') ?></span>
                </button>
            </div>
        </header>

        <div class="table-wrapper">
            <table class="data-table data-table--responsive" id="shift-table">
                <thead>
                    <tr>
                        <th><?= htmlspecialchars($messages['shift_col_id'] ?? 'ID', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_name'] ?? 'Tên ca', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_grouptype'] ?? 'Loại nhóm', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_color'] ?? 'Màu', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_in1'] ?? 'Vào 1', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_out1'] ?? 'Ra 1', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_in2'] ?? 'Vào 2', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_out2'] ?? 'Ra 2', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_total'] ?? 'Tổng', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_apply'] ?? 'Áp dụng', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_sang'] ?? 'Sáng', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_trua'] ?? 'Trưa', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_chieu'] ?? 'Chiều', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_dem'] ?? 'Đêm', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_ngaycong'] ?? 'Ngày công', ENT_QUOTES, 'UTF-8') ?></th>
                        <th><?= htmlspecialchars($messages['shift_col_time'] ?? 'Ngày', ENT_QUOTES, 'UTF-8') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($pageWorkshifts)): ?>
                        <?php foreach ($pageWorkshifts as $row): ?>
                            <tr>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_id'] ?? 'ID', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['Id'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_name'] ?? 'Tên ca', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['name'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_grouptype'] ?? 'Loại nhóm', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['grouptype'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_color'] ?? 'Màu', ENT_QUOTES, 'UTF-8') ?>">
                                    <?php if (!empty($row['color'])): ?>
                                        <span style="display: inline-block; width: 20px; height: 20px; background-color: <?= htmlspecialchars($row['color'], ENT_QUOTES, 'UTF-8') ?>; border-radius: 4px; border: 1px solid rgba(255,255,255,0.2);"></span>
                                    <?php else: ?>
                                        --
                                    <?php endif; ?>
                                </td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_in1'] ?? 'Vào 1', ENT_QUOTES, 'UTF-8') ?>"><?= format_time($row['in1'] ?? null) ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_out1'] ?? 'Ra 1', ENT_QUOTES, 'UTF-8') ?>"><?= format_time($row['out1'] ?? null) ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_in2'] ?? 'Vào 2', ENT_QUOTES, 'UTF-8') ?>"><?= format_time($row['in2'] ?? null) ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_out2'] ?? 'Ra 2', ENT_QUOTES, 'UTF-8') ?>"><?= format_time($row['out2'] ?? null) ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_total'] ?? 'Tổng', ENT_QUOTES, 'UTF-8') ?>"><?= format_time($row['total'] ?? null) ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_apply'] ?? 'Áp dụng', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['apply'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_sang'] ?? 'Sáng', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['sang'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_trua'] ?? 'Trưa', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['trua'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_chieu'] ?? 'Chiều', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['chieu'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_dem'] ?? 'Đêm', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['dem'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_ngaycong'] ?? 'Ngày công', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($row['Ngaycong'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                <td data-label="<?= htmlspecialchars($messages['shift_col_time'] ?? 'Ngày', ENT_QUOTES, 'UTF-8') ?>"><?= format_date($row['time'] ?? null) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="16" style="text-align:center;opacity:.7;"><?= htmlspecialchars($messages['shift_no_data'] ?? 'Chưa có dữ liệu hiển thị', ENT_QUOTES, 'UTF-8') ?></td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($totalPages > 1): ?>
        <div class="pagination-wrapper" style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">
            <div style="display: flex; align-items: center; gap: 8px;">
                <label style="color: #9ec9c1; font-size: 13px;"><?= htmlspecialchars($messages['pagination_show'] ?? 'Hiển thị:', ENT_QUOTES, 'UTF-8') ?></label>
                <select id="shift-page-size" style="padding: 6px 10px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; color: #e8fbf6; font-size: 13px; cursor: pointer;">
                    <?php foreach ($allowedPageSizes as $size): ?>
                        <option value="<?= $size ?>" <?= ($pageSize === $size) ? 'selected' : '' ?>><?= $size ?></option>
                    <?php endforeach; ?>
                </select>
                <span style="color: #9ec9c1; font-size: 13px;"><?= htmlspecialchars($messages['pagination_rows_per_page'] ?? 'dòng/trang', ENT_QUOTES, 'UTF-8') ?></span>
            </div>
            <div class="pagination" style="display: flex; gap: 8px; align-items: center;">
                <?php if ($currentPage > 1): ?>
                    <a href="index.php?shift&page=<?= $currentPage - 1 ?>&page_size=<?= $pageSize ?>" class="pagination-btn" style="padding: 8px 12px; background: rgba(122,220,201,0.1); border: 1px solid rgba(122,220,201,0.3); border-radius: 6px; color: #7adcc9; text-decoration: none; font-size: 13px;">
                        <?= htmlspecialchars($messages['pagination_prev'] ?? '&lt; Trước', ENT_QUOTES, 'UTF-8') ?>
                    </a>
                <?php endif; ?>
                
                <?php
                $startPage = max(1, $currentPage - 2);
                $endPage = min($totalPages, $currentPage + 2);
                
                if ($startPage > 1): ?>
                    <a href="index.php?shift&page=1&page_size=<?= $pageSize ?>" class="pagination-btn" style="padding: 8px 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; color: #e8fbf6; text-decoration: none; font-size: 13px;">1</a>
                    <?php if ($startPage > 2): ?>
                        <span style="color: #9ec9c1; padding: 0 4px;">...</span>
                    <?php endif; ?>
                <?php endif; ?>
                
                <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                    <a href="index.php?shift&page=<?= $i ?>&page_size=<?= $pageSize ?>" 
                       class="pagination-btn <?= ($i === $currentPage) ? 'active' : '' ?>"
                       style="padding: 8px 12px; background: <?= ($i === $currentPage) ? 'rgba(122,220,201,0.2)' : 'rgba(255,255,255,0.05)' ?>; border: 1px solid <?= ($i === $currentPage) ? 'rgba(122,220,201,0.4)' : 'rgba(255,255,255,0.1)' ?>; border-radius: 6px; color: <?= ($i === $currentPage) ? '#7adcc9' : '#e8fbf6' ?>; text-decoration: none; font-size: 13px; font-weight: <?= ($i === $currentPage) ? '600' : '400' ?>;">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>
                
                <?php if ($endPage < $totalPages): ?>
                    <?php if ($endPage < $totalPages - 1): ?>
                        <span style="color: #9ec9c1; padding: 0 4px;">...</span>
                    <?php endif; ?>
                    <a href="index.php?shift&page=<?= $totalPages ?>&page_size=<?= $pageSize ?>" class="pagination-btn" style="padding: 8px 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; color: #e8fbf6; text-decoration: none; font-size: 13px;"><?= $totalPages ?></a>
                <?php endif; ?>
                
                <?php if ($currentPage < $totalPages): ?>
                    <a href="index.php?shift&page=<?= $currentPage + 1 ?>&page_size=<?= $pageSize ?>" class="pagination-btn" style="padding: 8px 12px; background: rgba(122,220,201,0.1); border: 1px solid rgba(122,220,201,0.3); border-radius: 6px; color: #7adcc9; text-decoration: none; font-size: 13px;">
                        <?= htmlspecialchars($messages['pagination_next'] ?? 'Sau &gt;', ENT_QUOTES, 'UTF-8') ?>
                    </a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Shift Create Modal -->
<div id="shift-modal" class="modal-backdrop" aria-hidden="true">
    <div class="modal">
        <div class="modal-header">
            <h4><?= htmlspecialchars($messages['shift_create_heading'] ?? 'THÊM CA LÀM VIỆC', ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close>&times;</button>
        </div>
        <div class="modal-body">
            <form id="shift-form" action="modules/shift_service.php" method="POST" class="form-grid grid-2" novalidate>
                <input type="hidden" name="action" value="create">
                
                <div class="form-row">
                    <label for="shift-name"><?= htmlspecialchars($messages['shift_form_name_label'] ?? 'Tên ca', ENT_QUOTES, 'UTF-8') ?> <span class="required-asterisk">*</span></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="shift-name" name="name" placeholder="<?= htmlspecialchars($messages['shift_form_name_placeholder'] ?? 'Nhập tên ca', ENT_QUOTES, 'UTF-8') ?>" required>
                    </div>
                </div>

                <div class="form-row">
                    <label><?= htmlspecialchars($messages['shift_form_grouptype_label'] ?? 'Loại nhóm', ENT_QUOTES, 'UTF-8') ?> <span class="required-asterisk">*</span></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                        </span>
                        <div class="custom-select" id="shift-grouptype-select">
                            <button type="button"
                                    class="custom-select-toggle"
                                    data-placeholder="--">
                                --
                            </button>
                            <div class="custom-select-menu" role="listbox">
                                <?php if (!empty($grouptypeOptions)): ?>
                                    <?php foreach ($grouptypeOptions as $option): ?>
                                        <div class="custom-select-option"
                                             role="option"
                                             data-value="<?= htmlspecialchars((string)$option['type'], ENT_QUOTES, 'UTF-8') ?>">
                                            <?= htmlspecialchars($option['label'], ENT_QUOTES, 'UTF-8') ?>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">
                                        <?= htmlspecialchars($messages['profile_edit_no_data'] ?? 'Chưa có dữ liệu', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden"
                                   name="grouptype"
                                   id="shift-grouptype-input"
                                   value="">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-color"><?= htmlspecialchars($messages['shift_form_color_label'] ?? 'Màu', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 2v4m0 12v4M2 12h4m12 0h4"/></svg>
                        </span>
                        <input type="color" id="shift-color" name="color" value="#7adcc9" style="height: 40px; cursor: pointer;">
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-in1"><?= htmlspecialchars($messages['shift_form_in1_label'] ?? 'Vào 1', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap time-wrap">
                        <span class="icon time-icon" data-target="shift-in1">
                            <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="text"
                               class="shift-time-input"
                               id="shift-in1"
                               name="in1"
                               placeholder="hh:mm:ss"
                               autocomplete="off"
                               inputmode="numeric"
                               pattern="^\d{2}:\d{2}:\d{2}$"
                               readonly>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-out1"><?= htmlspecialchars($messages['shift_form_out1_label'] ?? 'Ra 1', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap time-wrap">
                        <span class="icon time-icon" data-target="shift-out1">
                            <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="text"
                               class="shift-time-input"
                               id="shift-out1"
                               name="out1"
                               placeholder="hh:mm:ss"
                               autocomplete="off"
                               inputmode="numeric"
                               pattern="^\d{2}:\d{2}:\d{2}$"
                               readonly>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-in2"><?= htmlspecialchars($messages['shift_form_in2_label'] ?? 'Vào 2', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap time-wrap">
                        <span class="icon time-icon" data-target="shift-in2">
                            <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="text"
                               class="shift-time-input"
                               id="shift-in2"
                               name="in2"
                               placeholder="hh:mm:ss"
                               autocomplete="off"
                               inputmode="numeric"
                               pattern="^\d{2}:\d{2}:\d{2}$"
                               readonly>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-out2"><?= htmlspecialchars($messages['shift_form_out2_label'] ?? 'Ra 2', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap time-wrap">
                        <span class="icon time-icon" data-target="shift-out2">
                            <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="text"
                               class="shift-time-input"
                               id="shift-out2"
                               name="out2"
                               placeholder="hh:mm:ss"
                               autocomplete="off"
                               inputmode="numeric"
                               pattern="^\d{2}:\d{2}:\d{2}$"
                               readonly>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-total"><?= htmlspecialchars($messages['shift_form_total_label'] ?? 'Tổng', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap time-wrap">
                        <span class="icon time-icon" data-target="shift-total">
                            <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="text"
                               class="shift-time-input"
                               id="shift-total"
                               name="total"
                               placeholder="hh:mm:ss"
                               autocomplete="off"
                               inputmode="numeric"
                               pattern="^\d{2}:\d{2}:\d{2}$"
                               readonly>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-department">Bộ phận</label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M21 16V8a2 2 0 0 0-1-1.73L13 2.27a2 2 0 0 0-2 0L4 6.27A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4a2 2 0 0 0 1-1.73Z"/><path d="M7.5 4.21 12 6.81l4.5-2.6"/><path d="M3.27 6.96 12 12.01l8.73-5.05"/><path d="M12 22.08V12"/></svg>
                        </span>
                        <div class="custom-select" id="shift-department-select">
                            <button type="button"
                                    class="custom-select-toggle"
                                    data-placeholder="<?= htmlspecialchars($messages['shift_form_department_placeholder'] ?? '--', ENT_QUOTES, 'UTF-8') ?>">
                                <?= htmlspecialchars($messages['shift_form_department_placeholder'] ?? '--', ENT_QUOTES, 'UTF-8') ?>
                            </button>
                            <div class="custom-select-menu" role="listbox">
                                <div class="custom-select-option"
                                     role="option"
                                     data-value="all">
                                    <?= htmlspecialchars($messages['shift_form_department_all'] ?? 'Tất cả', ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                <?php if (!empty($departmentOptions)): ?>
                                    <?php foreach ($departmentOptions as $dept): ?>
                                        <div class="custom-select-option"
                                             role="option"
                                             data-value="<?= htmlspecialchars((string)$dept['value'], ENT_QUOTES, 'UTF-8') ?>">
                                            <?= htmlspecialchars($dept['label'], ENT_QUOTES, 'UTF-8') ?>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="custom-select-option" role="option" data-value="" aria-disabled="true">
                                        <?= htmlspecialchars($messages['profile_edit_no_data'] ?? 'Chưa có dữ liệu', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden"
                                   name="department"
                                   id="shift-department-input"
                                   value="">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-apply"><?= htmlspecialchars($messages['shift_form_apply_label'] ?? 'Áp dụng', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
                        </span>
                        <input type="text" id="shift-apply" name="apply" placeholder="<?= htmlspecialchars($messages['shift_form_apply_placeholder'] ?? 'Nhập thông tin áp dụng', ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                    <div id="shift-apply-tags-host" class="apply-tags-host"></div>
                </div>

                <div class="form-row full">
                    <label>Khung giờ áp dụng <span class="required-asterisk">*</span></label>
                    <div class="period-toggle-group" role="group" aria-label="Chọn khung giờ áp dụng">
                        <button type="button" class="period-toggle" data-target="shift-sang" aria-pressed="false">
                            <span class="icon">
                                <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
                            </span>
                            <span>Sáng</span>
                        </button>
                        <button type="button" class="period-toggle" data-target="shift-trua" aria-pressed="false">
                            <span class="icon">
                                <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
                            </span>
                            <span>Trưa</span>
                        </button>
                        <button type="button" class="period-toggle" data-target="shift-chieu" aria-pressed="false">
                            <span class="icon">
                                <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
                            </span>
                            <span>Chiều</span>
                        </button>
                        <button type="button" class="period-toggle" data-target="shift-dem" aria-pressed="false">
                            <span class="icon">
                                <svg viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
                            </span>
                            <span>Đêm</span>
                        </button>
                        <input type="hidden" id="shift-sang" name="sang" value="0">
                        <input type="hidden" id="shift-trua" name="trua" value="0">
                        <input type="hidden" id="shift-chieu" name="chieu" value="0">
                        <input type="hidden" id="shift-dem" name="dem" value="0">
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-ngaycong"><?= htmlspecialchars($messages['shift_form_ngaycong_label'] ?? 'Ngày công', ENT_QUOTES, 'UTF-8') ?> <span class="required-asterisk">*</span></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="number" id="shift-ngaycong" name="Ngaycong" min="0" step="1" pattern="[0-9]*" inputmode="numeric" placeholder="<?= htmlspecialchars($messages['shift_form_ngaycong_placeholder'] ?? 'Nhập ngày công', ENT_QUOTES, 'UTF-8') ?>">
                        <div class="number-spinner">
                            <div class="spinner-up" onclick="incrementNgaycong()"></div>
                            <div class="spinner-down" onclick="decrementNgaycong()"></div>
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="shift-time"><?= htmlspecialchars($messages['shift_form_time_label'] ?? 'Ngày', ENT_QUOTES, 'UTF-8') ?> <span class="required-asterisk">*</span></label>
                    <div class="input-wrap">
                        <span class="icon date-icon" data-target="shift-time">
                            <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="shift-time" name="time" required style="font-size: 16px;" autocomplete="off">
                    </div>
                </div>

                <div class="form-actions full">
                    <button type="submit" class="btn btn-primary"><?= htmlspecialchars($messages['shift_form_submit'] ?? 'Lưu', ENT_QUOTES, 'UTF-8') ?></button>
                    <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['shift_form_cancel'] ?? 'Hủy', ENT_QUOTES, 'UTF-8') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.shift-panel .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}
.shift-controls {
    display: flex;
    gap: 12px;
    align-items: center;
}
.shift-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;
    justify-content: center !important;
    gap: 8px !important;
    white-space: nowrap !important;
    text-decoration: none !important;
    background: linear-gradient(135deg, rgba(100,167,166,0.9), rgba(122,220,201,0.95)) !important;
    color: #052729 !important;
    border: 1px solid rgba(122,220,201,0.4) !important;
}
.shift-btn:hover {
    background: linear-gradient(135deg, rgba(122,220,201,0.95), rgba(100,167,166,0.9)) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(122,220,201,0.3) !important;
}
.shift-btn .btn-icon-wrapper {
    display: inline-grid;
    place-items: center;
    width: 14px;
    height: 14px;
}
.shift-btn .btn-icon-wrapper svg {
    width: 14px;
    height: 14px;
}
.shift-btn .btn-text-wrapper {
    font-size: 13px;
    font-weight: 500;
    color: inherit;
}
#shift-modal {
    position: fixed;
    inset: 0;
    display: none;
    align-items: center;
    justify-content: center;
    overflow: auto;
    z-index: 10000;
    padding: 12px;
    background: rgba(6, 22, 28, 0.65);
}
#shift-modal.show {
    display: flex;
}
#shift-modal .modal {
    width: min(800px, calc(100% - 24px));
    max-width: 100%;
    max-height: calc(100vh - 24px);
    background: rgba(17, 46, 51, 0.98);
    border: 1px solid rgba(122, 220, 201, 0.2);
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
#shift-modal .modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid rgba(122, 220, 201, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
#shift-modal .modal-header h4 {
    margin: 0;
    color: #e8fbf6;
    font-size: 18px;
    font-weight: 600;
}
#shift-modal .modal-close {
    background: transparent;
    border: none;
    color: #9ec9c1;
    font-size: 24px;
    cursor: pointer;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    transition: all 0.2s;
}
#shift-modal .modal-close:hover {
    background: rgba(122, 220, 201, 0.1);
    color: #7adcc9;
}
#shift-modal .modal-body {
    padding: 24px;
    overflow-y: auto;
    flex: 1;
}
#shift-modal .form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
}
#shift-modal .form-row.full {
    grid-column: 1 / -1;
}
#shift-modal .form-row label {
    display: block;
    margin-bottom: 6px;
    color: #9ec9c1;
    font-size: 13px;
    font-weight: 500;
}
#shift-modal .form-row .required-asterisk {
    color: #ff6b6b;
}
#shift-modal .input-wrap {
    position: relative;
    display: flex;
    align-items: center;
}
#shift-modal .input-wrap .icon {
    position: absolute;
    left: 12px;
    width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #7adcc9;
    opacity: 0.6;
    pointer-events: none;
    z-index: 1;
}
#shift-modal .input-wrap .icon svg {
    width: 18px;
    height: 18px;
}
#shift-modal .input-wrap.time-wrap {
    border-radius: 12px;
    border: 1px solid rgba(122, 220, 201, 0.28);
    padding-left: 0;
    background: rgba(11, 31, 34, 0.65);
}
#shift-modal .input-wrap.time-wrap:focus-within {
    border-color: rgba(122, 220, 201, 0.45);
    box-shadow: 0 0 0 2px rgba(122, 220, 201, 0.08);
}
#shift-modal .input-wrap.time-wrap .icon.time-icon {
    left: 14px;
    cursor: pointer;
    opacity: 0.8;
}
#shift-modal .shift-time-input {
    font-size: 14px;
    font-family: monospace;
    line-height: 1.2;
    color: #e8fbf6;
    font-weight: 500;
    -webkit-text-fill-color: #e8fbf6;
    border: 0 !important;
    background: transparent !important;
    padding-left: 44px;
    caret-color: transparent;
    cursor: pointer;
}
#shift-modal .shift-time-input::placeholder {
    color: #9ec9c1;
    opacity: 0.8;
}
#shift-modal .input-wrap input[type="text"],
#shift-modal .input-wrap input[type="number"],
#shift-modal .input-wrap input[type="time"],
#shift-modal .input-wrap input[type="date"],
#shift-modal .input-wrap input[type="color"] {
    width: 100%;
    padding: 10px 12px 10px 42px;
    height: 38px;
    min-height: 38px;
    line-height: 18px;
    box-sizing: border-box;
    background: rgba(0, 0, 0, 0.25);
    border: 1px solid rgba(122, 220, 201, 0.28);
    border-radius: 8px;
    color: #e8fbf6;
    font-size: 14px;
    transition: all 0.2s;
}
#shift-modal .input-wrap input[type="date"] {
    -webkit-appearance: none;
    appearance: none;
}
#shift-modal .input-wrap input[type="color"] {
    padding: 5px;
    cursor: pointer;
}
#shift-modal .input-wrap input:focus {
    outline: none;
    border-color: rgba(122, 220, 201, 0.5);
    box-shadow: 0 0 0 3px rgba(122, 220, 201, 0.1);
}
#shift-modal .custom-select {
    position: relative;
    width: 100%;
}
#shift-modal .custom-select-toggle {
    width: 100%;
    padding: 10px 12px 10px 42px;
    background: rgba(0, 0, 0, 0.25);
    border: 1px solid rgba(122, 220, 201, 0.28);
    border-radius: 8px;
    color: #e8fbf6;
    font-size: 14px;
    text-align: left;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 38px;
    min-height: 38px;
}
#shift-modal .custom-select-toggle::after {
    content: '';
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 6px solid #7adcc9;
    margin-left: 8px;
    transition: transform 0.2s;
}
#shift-modal .custom-select.open .custom-select-toggle::after {
    transform: rotate(180deg);
}
#shift-modal .custom-select.open .custom-select-toggle {
    border-color: rgba(122, 220, 201, 0.5);
    box-shadow: 0 0 0 3px rgba(122, 220, 201, 0.1);
}
#shift-modal .custom-select-menu {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: rgba(17, 46, 51, 0.98);
    border: 1px solid rgba(122, 220, 201, 0.3);
    border-radius: 8px;
    margin-top: 4px;
    max-height: 260px;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
#shift-modal .custom-select.open .custom-select-menu {
    display: block;
}
#shift-modal .custom-select-option {
    padding: 10px 12px;
    color: #e8fbf6;
    cursor: pointer;
    transition: background 0.2s;
    font-size: 14px;
}
#shift-modal .custom-select-option:hover {
    background: rgba(122, 220, 201, 0.15);
}
#shift-modal .custom-select-option.is-selected {
    background: rgba(122, 220, 201, 0.25);
    color: #7adcc9;
}
#shift-modal .custom-select-option[aria-disabled="true"] {
    opacity: 0.5;
    cursor: not-allowed;
}
.period-toggle-group {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 10px;
    width: 100%;
}
.period-toggle {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 12px;
    border-radius: 8px;
    border: 1px solid rgba(122, 220, 201, 0.28);
    background: rgba(0, 0, 0, 0.25);
    color: #e8fbf6;
    cursor: pointer;
    transition: all 0.2s;
    justify-content: flex-start;
    text-align: left;
}
.period-toggle .icon {
    position: static;
    opacity: 0.7;
    width: 18px;
    height: 18px;
}
.period-toggle .icon svg {
    width: 18px;
    height: 18px;
}
.period-toggle:hover {
    border-color: rgba(122, 220, 201, 0.5);
    box-shadow: 0 0 0 3px rgba(122, 220, 201, 0.08);
}
.period-toggle.is-active {
    background: rgba(122, 220, 201, 0.18);
    border-color: rgba(122, 220, 201, 0.6);
    color: #7adcc9;
}
.apply-tags-host {
    margin-top: 8px;
}
@media (max-width: 600px) {
    .period-toggle-group {
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 8px;
    }
    .period-toggle {
        width: 100%;
        justify-content: center;
    }
}
.luna-time-picker{
    position:fixed;
    width:220px;
    height:240px;
    background:rgba(12,38,43,.98);
    border:1px solid rgba(122,220,201,.35);
    border-radius:12px;
    box-shadow:0 18px 38px rgba(3,15,21,.75);
    z-index:2147483000;
    display:none;
    padding:12px;
    box-sizing:border-box;
}
.luna-time-picker.show{display:block;}
.luna-time-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;padding-bottom:8px;border-bottom:1px solid rgba(122,220,201,.2);}
.luna-time-display{font-size:13px;font-weight:600;color:#e8fbf6;letter-spacing:1px;}
.luna-time-actions{display:flex;gap:6px;justify-content:flex-end;}
.luna-time-actions button{background:transparent;border:1px solid rgba(122,220,201,.28);color:#bfeee3;border-radius:6px;padding:4px 8px;cursor:pointer;font-size:9px;}
.luna-time-actions button:hover{background:rgba(122,220,201,.12);color:#7adcc9;}
.luna-time-columns{display:grid;grid-template-columns:1fr 20px 1fr 20px 1fr;gap:6px;height:150px;}
.time-col{overflow-y:auto;border:1px solid rgba(122,220,201,.18);border-radius:8px;padding:4px;}
.time-sep{display:grid;place-items:center;color:#9ec9c1;font-weight:600;}
.time-item{text-align:center;padding:3px 0;color:#e8fbf6;border-radius:6px;cursor:pointer;font-size:13px;}
.time-item:hover{background:rgba(122,220,201,.12);}
.time-item.selected{background:#7adcc9;color:#0b2228;font-weight:600;}
.time-labels{display:grid;grid-template-columns:1fr 20px 1fr 20px 1fr;gap:6px;margin-top:6px;color:#9ec9c1;font-size:11px;font-weight:600;text-align:center;}
.time-labels .spacer{width:20px;}
.luna-time-actions .ok-btn-header{background:#7adcc9;color:#052729;}
.luna-time-actions .ok-btn-header:hover{color:#052729;background:rgba(121,219,200,0.58);}
#shift-modal .form-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid rgba(122, 220, 201, 0.1);
}
#shift-modal .btn {
    padding: 10px 20px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}
#shift-modal .btn-primary {
    background: linear-gradient(135deg, rgba(100,167,166,0.9), rgba(122,220,201,0.95));
    color: #052729;
}
#shift-modal .btn-primary:hover {
    background: linear-gradient(135deg, rgba(122,220,201,0.95), rgba(100,167,166,0.9));
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(122,220,201,0.3);
}
#shift-modal .btn-secondary {
    background: rgba(255, 255, 255, 0.05);
    color: #e8fbf6;
    border: 1px solid rgba(255, 255, 255, 0.1);
}
#shift-modal .btn-secondary:hover {
    background: rgba(255, 255, 255, 0.1);
}
@media (max-width: 768px) {
    #shift-modal .form-grid {
        grid-template-columns: 1fr;
    }
    #shift-modal .form-row.full {
        grid-column: 1;
    }
}
</style>

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

<script>
// Global functions for Ngày công number spinner
function incrementNgaycong() {
    var input = document.getElementById('shift-ngaycong');
    if (input) {
        var currentValue = parseInt(input.value) || 0;
        input.value = currentValue + 1;
        input.dispatchEvent(new Event('input', { bubbles: true }));
    }
}

function decrementNgaycong() {
    var input = document.getElementById('shift-ngaycong');
    if (input) {
        var currentValue = parseInt(input.value) || 0;
        var minValue = parseInt(input.getAttribute('min')) || 0;
        if (currentValue > minValue) {
            input.value = currentValue - 1;
            input.dispatchEvent(new Event('input', { bubbles: true }));
        }
    }
}
</script>

<script>
// Custom Time Picker for Shift modal (reuse Luna style)
document.addEventListener('DOMContentLoaded', function() {
    initShiftTimePicker();
});

function initShiftTimePicker() {
    var modal = document.getElementById('shift-modal');
    if (!modal) return;

    var timeFieldIds = ['shift-in1', 'shift-out1', 'shift-in2', 'shift-out2', 'shift-total'];
    var picker = null, currentInput = null;
    var selectedH = 0, selectedM = 0, selectedS = 0;
    var closeHandlers = { scroll: null, resize: null, outside: null };

    function getTimePickerTexts() {
        var lang = window.getCurrentLanguage ? window.getCurrentLanguage() : (window.APP_LANG || 'vn');
        var texts = {
            vn: { now: 'Bây giờ', clear: 'Xóa', hour: 'GIỜ', minute: 'PHÚT', second: 'GIÂY' },
            eng: { now: 'Now', clear: 'Clear', hour: 'HOUR', minute: 'MINUTE', second: 'SECOND' }
        };
        return texts[lang] || texts.vn;
    }

    function createPicker() {
        var texts = getTimePickerTexts();
        var el = document.createElement('div');
        el.className = 'luna-time-picker';
        el.id = 'luna-time-picker-shift';
        el.innerHTML = '\
            <div class="luna-time-header">\
                <div class="luna-time-display" id="tp-display-shift">00:00:00</div>\
                <div class="luna-time-actions">\
                    <button type="button" class="now-btn">' + texts.now + '</button>\
                    <button type="button" class="clear-btn">' + texts.clear + '</button>\
                    <button type="button" class="ok-btn-header">OK</button>\
                </div>\
            </div>\
            <div class="luna-time-columns">\
                <div class="time-col hours"></div><div class="time-sep">:</div>\
                <div class="time-col minutes"></div><div class="time-sep">:</div>\
                <div class="time-col seconds"></div>\
            </div>\
            <div class="time-labels">\
                <div class="lbl">' + texts.hour + '</div><div class="spacer"></div>\
                <div class="lbl">' + texts.minute + '</div><div class="spacer"></div>\
                <div class="lbl">' + texts.second + '</div>\
            </div>';
        document.body.appendChild(el);
        return el;
    }

    function getPicker() { if (!picker) picker = createPicker(); return picker; }

    function updateDisplay() {
        var d = document.getElementById('tp-display-shift');
        if (d) d.textContent = String(selectedH).padStart(2, '0') + ':' + String(selectedM).padStart(2, '0') + ':' + String(selectedS).padStart(2, '0');
    }

    function renderColumns() {
        var el = getPicker();
        var hCol = el.querySelector('.hours');
        var mCol = el.querySelector('.minutes');
        var sCol = el.querySelector('.seconds');
        hCol.innerHTML = ''; mCol.innerHTML = ''; sCol.innerHTML = '';
        for (var h = 0; h < 24; h++) {
            var b = document.createElement('div');
            b.className = 'time-item' + (h === selectedH ? ' selected' : '');
            b.textContent = String(h).padStart(2, '0');
            b.dataset.h = h;
            b.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); selectedH = parseInt(e.target.dataset.h, 10); renderColumns(); updateDisplay(); });
            hCol.appendChild(b);
        }
        for (var m = 0; m < 60; m++) {
            var c = document.createElement('div');
            c.className = 'time-item' + (m === selectedM ? ' selected' : '');
            c.textContent = String(m).padStart(2, '0');
            c.dataset.m = m;
            c.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); selectedM = parseInt(e.target.dataset.m, 10); renderColumns(); updateDisplay(); });
            mCol.appendChild(c);
        }
        for (var s = 0; s < 60; s++) {
            var d = document.createElement('div');
            d.className = 'time-item' + (s === selectedS ? ' selected' : '');
            d.textContent = String(s).padStart(2, '0');
            d.dataset.s = s;
            d.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); selectedS = parseInt(e.target.dataset.s, 10); renderColumns(); updateDisplay(); });
            sCol.appendChild(d);
        }
        updateDisplay();
    }

    function position() {
        var el = getPicker(); if (!currentInput) return;
        var rect = currentInput.getBoundingClientRect();
        var wrap = currentInput.closest('.input-wrap');
        var box = wrap ? wrap.getBoundingClientRect() : rect;
        var left = box.left; var top = box.bottom + 6;
        var w = 220, h = 240;
        if (left + w > window.innerWidth) left = window.innerWidth - w - 10;
        if (left < 10) left = 10;
        if (top + h > window.innerHeight) top = box.top - h - 6;
        if (top < 10) top = 10;
        el.style.left = left + 'px'; el.style.top = top + 'px';
    }

    function hide() {
        if (!picker) return;
        picker.classList.remove('show');
        document.removeEventListener('click', closeHandlers.outside);
        window.removeEventListener('scroll', closeHandlers.scroll, true);
        window.removeEventListener('resize', closeHandlers.resize);
        currentInput = null;
    }

    function show(input) {
        currentInput = input;
        var h = 0, m = 0, s = 0;
        if (input && input.value) {
            var parts = input.value.split(':');
            if (parts.length >= 2) { h = parseInt(parts[0] || '0', 10) || 0; m = parseInt(parts[1] || '0', 10) || 0; }
            if (parts.length >= 3) { s = parseInt(parts[2] || '0', 10) || 0; }
        } else {
            var now = new Date(); h = now.getHours(); m = now.getMinutes(); s = now.getSeconds();
        }
        selectedH = Math.max(0, Math.min(23, h));
        selectedM = Math.max(0, Math.min(59, m));
        selectedS = Math.max(0, Math.min(59, s));

        var el = getPicker();
        renderColumns();
        position();
        el.classList.add('show');

        el.querySelector('.now-btn').onclick = function () {
            var n = new Date();
            var v = String(n.getHours()).padStart(2, '0') + ':' + String(n.getMinutes()).padStart(2, '0') + ':' + String(n.getSeconds()).padStart(2, '0');
            if (currentInput) { currentInput.value = v; currentInput.dispatchEvent(new Event('change', { bubbles: true })); }
            hide();
        };
        el.querySelector('.clear-btn').onclick = function () { if (currentInput) { currentInput.value = ''; } hide(); };
        var okBtn = el.querySelector('.ok-btn-header');
        if (okBtn) {
            okBtn.onclick = function () {
                if (currentInput) {
                    var v = String(selectedH).padStart(2, '0') + ':' + String(selectedM).padStart(2, '0') + ':' + String(selectedS).padStart(2, '0');
                    currentInput.value = v;
                    currentInput.dispatchEvent(new Event('change', { bubbles: true }));
                }
                hide();
            };
        }

        closeHandlers.outside = function (e) {
            if (!el.contains(e.target) && e.target !== currentInput && !e.target.closest('.time-icon')) hide();
        };
        closeHandlers.scroll = function () { if (el.classList.contains('show')) position(); };
        closeHandlers.resize = function () { if (el.classList.contains('show')) position(); };
        document.addEventListener('click', closeHandlers.outside);
        window.addEventListener('scroll', closeHandlers.scroll, true);
        window.addEventListener('resize', closeHandlers.resize);
    }

    function bindField(id) {
        var input = document.getElementById(id);
        if (!input) return;
        var icon = modal.querySelector('.time-icon[data-target="' + id + '"]');
        var open = function (e) { if (e) { e.preventDefault(); e.stopPropagation(); } show(input); };
        input.addEventListener('click', open);
        input.addEventListener('focus', open);
        if (icon) { icon.addEventListener('click', open); }
    }

    timeFieldIds.forEach(bindField);

    // Fallback delegation (in case elements are re-rendered)
    document.addEventListener('click', function (e) {
        var icon = e.target.closest('.time-icon');
        if (!icon) return;
        var targetId = icon.getAttribute('data-target');
        if (timeFieldIds.indexOf(targetId) === -1) return;
        e.preventDefault();
        e.stopPropagation();
        var input = document.getElementById(targetId);
        if (input) show(input);
    }, true);

    // Hide picker when modal is closed
    modal.querySelectorAll('[data-modal-close]').forEach(function (btn) {
        btn.addEventListener('click', hide);
    });
}
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle page size change
    var pageSizeSelect = document.getElementById('shift-page-size');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', function() {
            var newSize = this.value;
            var urlParams = new URLSearchParams(window.location.search);
            urlParams.set('page_size', newSize);
            urlParams.set('page', '1'); // Reset to first page
            window.location.href = 'index.php?shift&' + urlParams.toString();
        });
    }

    // Fix Ngày công input validation
    function fixNgaycongInput() {
        var ngaycongInput = document.getElementById('shift-ngaycong');
        if (ngaycongInput) {
            // Prevent non-numeric input
            ngaycongInput.addEventListener('input', function(e) {
                // Remove any non-numeric characters
                this.value = this.value.replace(/[^0-9]/g, '');
            });
            
            // Prevent paste of non-numeric content
            ngaycongInput.addEventListener('paste', function(e) {
                e.preventDefault();
                var paste = (e.clipboardData || window.clipboardData).getData('text');
                var numericOnly = paste.replace(/[^0-9]/g, '');
                this.value = numericOnly;
            });
            
            // Prevent keypress of non-numeric characters
            ngaycongInput.addEventListener('keypress', function(e) {
                // Allow: backspace, delete, tab, escape, enter
                if ([8, 9, 27, 13, 46].indexOf(e.keyCode) !== -1 ||
                    // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
                    (e.keyCode === 65 && e.ctrlKey === true) ||
                    (e.keyCode === 67 && e.ctrlKey === true) ||
                    (e.keyCode === 86 && e.ctrlKey === true) ||
                    (e.keyCode === 88 && e.ctrlKey === true)) {
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });
        }
    }
    
    // Apply Ngày công input fixes
    fixNgaycongInput();

    // Shift Modal handling
    var shiftModal = document.getElementById('shift-modal');
    var shiftForm = document.getElementById('shift-form');
    var openShiftBtn = document.querySelector('[data-shift-open="create"]');

    function resetCustomSelect(customId, hiddenInputId) {
        var custom = document.getElementById(customId);
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var hidden = document.getElementById(hiddenInputId);
        if (toggle) {
            var placeholder = toggle.getAttribute('data-placeholder') || '--';
            toggle.textContent = placeholder;
        }
        if (hidden) {
            hidden.value = '';
        }
        custom.classList.remove('open');
    }

    function openShiftModal() {
        if (!shiftModal) return;
        // Reset form
        if (shiftForm) {
            shiftForm.reset();
            // Reset Custom Selects
            resetCustomSelect('shift-grouptype-select', 'shift-grouptype-input');
            resetCustomSelect('shift-department-select', 'shift-department-input');
            // Set default date to today
            var dateInput = document.getElementById('shift-time');
            if (dateInput) {
                var today = new Date();
                dateInput.value = today.toISOString().split('T')[0];
            }
            // Reset period toggles
            document.querySelectorAll('.period-toggle').forEach(function(btn) {
                btn.classList.remove('is-active');
                btn.setAttribute('aria-pressed', 'false');
                var target = btn.getAttribute('data-target');
                var hidden = target ? document.getElementById(target) : null;
                if (hidden) hidden.value = '0';
            });
            // Reset apply tags view
            renderApplyTags();
        }
        shiftModal.classList.add('show');
        shiftModal.setAttribute('aria-hidden', 'false');
        // Re-apply Ngày công input validation when modal opens
        setTimeout(function() {
            fixNgaycongInput();
        }, 100);
        // Focus first input
        var firstInput = shiftForm ? shiftForm.querySelector('input[type="text"]') : null;
        if (firstInput) {
            setTimeout(function() { firstInput.focus(); }, 100);
        }
    }

    function closeShiftModal() {
        if (!shiftModal) return;
        shiftModal.classList.remove('show');
        shiftModal.setAttribute('aria-hidden', 'true');
    }

    // Open modal
    if (openShiftBtn) {
        openShiftBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            openShiftModal();
        });
    }

    // Close modal
    if (shiftModal) {
        var closeBtns = shiftModal.querySelectorAll('[data-modal-close]');
        closeBtns.forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                closeShiftModal();
            });
        });

        // Disable backdrop click close (keep modal open unless explicit close)
        // shiftModal.addEventListener('click', function(e) {
        //     if (e.target === shiftModal) {
        //         closeShiftModal();
        //     }
        // });

        // Close on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && shiftModal.classList.contains('show')) {
                closeShiftModal();
            }
        });
    }

    // Setup Custom Selects
    function setupCustomSelect(customId, hiddenInputId) {
        var custom = document.getElementById(customId);
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById(hiddenInputId);
        if (!toggle || !menu || !hidden) return;

        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        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 pad = 12;
            var width = Math.round(r.width);
            var left = Math.round(r.left);
            var top = Math.round(r.bottom + 6);

            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 = top + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = '260px';
            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 (closeOnResize) {
                window.removeEventListener('resize', closeOnResize);
                closeOnResize = null;
            }
        }

        function openMenu() {
            if (custom.classList.contains('open')) {
                closeAll();
                return;
            }

            // Close other custom selects
            document.querySelectorAll('.custom-select.open').forEach(function(el) {
                if (el !== custom) {
                    el.classList.remove('open');
                    var otherMenu = el.querySelector('.custom-select-menu');
                    if (otherMenu) {
                        otherMenu.style.display = '';
                        otherMenu.style.position = '';
                    }
                }
            });

            custom.classList.add('open');
            mountMenu();
            positionMenu();

            closeOnResize = function() { closeAll(); };
            window.addEventListener('resize', closeOnResize);
        }

        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            openMenu();
        });

        menu.addEventListener('click', function(e) {
            var opt = e.target.closest('.custom-select-option');
            if (!opt || opt.getAttribute('aria-disabled') === 'true') return;

            var value = opt.getAttribute('data-value') || '';
            var text = opt.textContent.trim();

            hidden.value = value;
            toggle.textContent = text || placeholder;

            // Post-select side effects (e.g., department -> apply field)
            if (customId === 'shift-department-select') {
                var applyInput = document.getElementById('shift-apply');
                if (applyInput) {
                    if (value === 'all') {
                        applyInput.value = 'All';
                        renderApplyTags();
                    } else if (value) {
                        var current = (applyInput.value || '').trim();
                        // If current is "All" then reset before adding
                        if (current.toLowerCase() === 'all') {
                            current = '';
                        }
                        var addition = '[' + value + ']';
                        var parts = current ? current.split(';').map(function(v){ return v.trim(); }).filter(Boolean) : [];
                        if (parts.indexOf(addition) === -1) {
                            parts.push(addition);
                        }
                        applyInput.value = parts.join(parts.length ? ';' : '');
                        renderApplyTags();
                    }
                }
            }

            var all = menu.querySelectorAll('.custom-select-option');
            all.forEach(function(o) { o.classList.remove('is-selected'); });
            opt.classList.add('is-selected');

            closeAll();
        });

        document.addEventListener('click', function(e) {
            if (!custom.contains(e.target)) {
                closeAll();
            }
        });

        // Close on Escape
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && custom.classList.contains('open')) {
                closeAll();
            }
        });
    }

    setupCustomSelect('shift-grouptype-select', 'shift-grouptype-input');
    setupCustomSelect('shift-department-select', 'shift-department-input');

    // Apply tags render using ticket-style CSS (kept unchanged)
    var applyTagsHost = document.getElementById('shift-apply-tags-host');
    var applyTagsShadow = applyTagsHost ? applyTagsHost.attachShadow({ mode: 'open' }) : null;
    if (applyTagsShadow) {
        var ticketStyle = document.createElement('style');
        ticketStyle.textContent = "\n    .page-center {\n\n      width: 100%;\n\n      height: 100%;\n\n      display: flex;\n\n      align-items: center;\n\n      justify-content: center;\n\n      background: transparent;\n\n    }\n\n    /* CSS G\u1ed0C THEO B\u00c0I H\u01af\u1edacNG D\u1eaaN */\n\n    .ticket {\n\n      font-family: Arial;\n\n      font-size: 12px;\n\n      font-weight: bold;\n\n      position: relative !important;\n\n      background: #8dc63f;\n\n      float: left;\n\n      padding: 7px 3px;\n\n      margin: 0 5px 5px 0;\n\n    }\n\n    .ticket:after {\n\n      content: \"\";\n\n      position: absolute !important;\n\n      z-index: 100;\n\n      top: 0;\n\n      left: 0;\n\n      border-right: #fff 7px solid;\n\n      border-bottom: #fff 7px solid;\n\n      -moz-border-radius: 0 0 20px 0;\n\n      -webkit-border-radius: 0 0 20px 0;\n\n      border-radius: 0 0 20px 0;\n\n    }\n\n    .ticket:before {\n\n      content: \"\";\n\n      position: absolute !important;\n\n      z-index: 100;\n\n      top: 0;\n\n      right: 0;\n\n      border-left: #fff 7px solid;\n\n      border-bottom: #fff 7px solid;\n\n      -moz-border-radius: 0 0 0 20px;\n\n      -webkit-border-radius: 0 0 0 20px;\n\n      border-radius: 0 0 0 20px;\n\n    }\n\n    .ticket a {\n\n      outline: 1px rgba(255,255,255,0.4) dashed;\n\n      border: 1px rgba(0,0,0,0.3) dashed;\n\n      padding: 4px 10px 4px 20px;\n\n      text-decoration: none;\n\n      color: rgba(255,255,255,0.5);\n\n      white-space: nowrap;\n\n    }\n\n    .ticket a:hover {\n\n      color: rgba(0,0,0,0.5);\n\n    }\n\n    .ticket a:after {\n\n      content: \"\";\n\n      position: absolute !important;\n\n      z-index: 100;\n\n      bottom: 0;\n\n      left: 0;\n\n      border-right: #fff 7px solid;\n\n      border-top: #fff 7px solid;\n\n      -moz-border-radius: 0 20px 0 0;\n\n      -webkit-border-radius: 0 20px 0 0;\n\n      border-radius: 0 20px 0 0;\n\n    }\n\n    .ticket a:before {\n\n      content: \"\";\n\n      position: absolute !important;\n\n      z-index: 1000;\n\n      bottom: 0;\n\n      right: 0;\n\n      border-left: #fff 7px solid;\n\n      border-top: #fff 7px solid;\n\n      -moz-border-radius: 20px 0 0 0;\n\n      -webkit-border-radius: 20px 0 0 0;\n\n      border-radius: 20px 0 0 0;\n\n    }\n\n    .ticket .close-icon {\n\n      position: absolute !important;\n\n      z-index: 100;\n\n      top: 50%;\n\n      left: 8px;\n\n      transform: translateY(-50%);\n\n      width: 16px;\n\n      height: 16px;\n\n      cursor: pointer;\n\n      opacity: 0.8;\n\n      transition: all 0.2s ease;\n\n      display: flex;\n\n      align-items: center;\n\n      justify-content: center;\n\n    }\n\n    .ticket .close-icon:hover {\n\n      opacity: 1;\n\n      transform: translateY(-50%) scale(1.1);\n\n    }\n\n    .ticket .close-icon svg {\n\n      width: 100%;\n\n      height: 100%;\n\n      stroke: #ff4444;\n\n      fill: none;\n\n      stroke-width: 2.5;\n\n      stroke-linecap: round;\n\n    }\n";
        applyTagsShadow.appendChild(ticketStyle);
        var ticketWrap = document.createElement('div');
        ticketWrap.className = 'page-center';
        applyTagsShadow.appendChild(ticketWrap);
    }

    function renderApplyTags() {
        if (!applyTagsShadow) return;
        var wrap = applyTagsShadow.querySelector('.page-center');
        if (!wrap) return;
        wrap.innerHTML = '';
        var input = document.getElementById('shift-apply');
        var val = (input && input.value) ? input.value.trim() : '';
        if (!val) return;
        var parts = val.split(';').map(function(v){ return v.trim(); }).filter(Boolean);
        parts.forEach(function(item, index) {
            var ticket = document.createElement('div');
            ticket.className = 'ticket';
            var closeIcon = document.createElement('span');
            closeIcon.className = 'close-icon';
            closeIcon.setAttribute('data-tag-index', index);
            closeIcon.setAttribute('data-tag-value', item);
            closeIcon.innerHTML = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>';
            closeIcon.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var tagValue = this.getAttribute('data-tag-value');
                var currentVal = (input && input.value) ? input.value.trim() : '';
                if (!currentVal) return;
                var currentParts = currentVal.split(';').map(function(v){ return v.trim(); }).filter(Boolean);
                var newParts = currentParts.filter(function(part) {
                    return part !== tagValue;
                });
                input.value = newParts.join(';');
                renderApplyTags();
            });
            var link = document.createElement('a');
            link.href = '#';
            link.textContent = item;
            ticket.appendChild(closeIcon);
            ticket.appendChild(link);
            wrap.appendChild(ticket);
        });
    }

    // Sync tags on manual edits
    var applyInputEl = document.getElementById('shift-apply');
    if (applyInputEl) {
        applyInputEl.addEventListener('input', renderApplyTags);
    }

    // Period toggle handling (Sáng/Trưa/Chiều/Đêm)
    document.querySelectorAll('.period-toggle').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            var target = btn.getAttribute('data-target');
            if (!target) return;
            var hidden = document.getElementById(target);
            var isActive = btn.classList.contains('is-active');
            if (isActive) {
                btn.classList.remove('is-active');
                btn.setAttribute('aria-pressed', 'false');
                if (hidden) hidden.value = '0';
            } else {
                btn.classList.add('is-active');
                btn.setAttribute('aria-pressed', 'true');
                if (hidden) hidden.value = '1';
            }
        });
    });

    // Form submission
    if (shiftForm) {
        shiftForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            var formData = new FormData(shiftForm);
            
            fetch('modules/shift_service.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                if (data && data.success) {
                    var successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
                    var successMsg = data.message || (window.__MESSAGES__ && window.__MESSAGES__['shift_success_created']) ? window.__MESSAGES__['shift_success_created'] : 'Đã thêm ca làm việc thành công.';
                    if (window.showToast) {
                        window.showToast('success', '<div class="success-header">' + successTitle + '</div>' + successMsg);
                    }
                    closeShiftModal();
                    // Reload page to show new data
                    setTimeout(function() {
                        window.location.reload();
                    }, 500);
                } else {
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    var errorMsg = data.message || (window.__MESSAGES__ && window.__MESSAGES__['shift_error_create']) ? window.__MESSAGES__['shift_error_create'] : 'Không thể thêm ca làm việc.';
                    if (window.showToast) {
                        window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + errorMsg);
                    }
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var errorMsg = (window.__MESSAGES__ && window.__MESSAGES__['shift_error_create']) ? window.__MESSAGES__['shift_error_create'] : 'Không thể thêm ca làm việc.';
                if (window.showToast) {
                    window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + errorMsg);
                }
            });
        });
    }
});
</script>

