<?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();
}

$userData = [];
$provinceOptions = [];
$msnv = $_SESSION['user']['username'] ?? '';

if (!empty($msnv)) {
    try {
        $conn = db_connect();
        if ($conn) {
            $sql = "SELECT TOP 1 * FROM DataWork WHERE Maso_NV = ?";
            $params = [$msnv];
            $stmt = sqlsrv_query($conn, $sql, $params);
            if ($stmt !== false) {
                $userData = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
                sqlsrv_free_stmt($stmt);
            }

            $sqlProvince = "SELECT DISTINCT Tinh_TP FROM Address WHERE Tinh_TP IS NOT NULL AND LTRIM(RTRIM(Tinh_TP)) <> '' ORDER BY Tinh_TP ASC";
            $stmtProvince = sqlsrv_query($conn, $sqlProvince);
            if ($stmtProvince !== false) {
                while ($row = sqlsrv_fetch_array($stmtProvince, SQLSRV_FETCH_ASSOC)) {
                    $name = isset($row['Tinh_TP']) ? trim((string)$row['Tinh_TP']) : '';
                    if ($name !== '' && !in_array($name, $provinceOptions, true)) {
                        $provinceOptions[] = $name;
                    }
                }
                sqlsrv_free_stmt($stmtProvince);
            }

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

function get_user_field($field, $default = 'N/A') {
    global $userData;
    $value = $userData[$field] ?? null;
    if (is_a($value, 'DateTime')) {
        return $value->format('d/m/Y');
    }
    return !empty($value) ? htmlspecialchars($value, ENT_QUOTES, 'UTF-8') : $default;
}

function get_full_address() {
    global $userData;
    $parts = [];
    
    // Lấy các phần địa chỉ
    $diachi = !empty($userData['Diachi_TT']) ? trim($userData['Diachi_TT']) : '';
    $phuongXa = !empty($userData['PhuongXa_TT']) ? trim($userData['PhuongXa_TT']) : '';
    $quanHuyen = !empty($userData['QuanHuyen_TT']) ? trim($userData['QuanHuyen_TT']) : '';
    $tinh = !empty($userData['Tinh_TT']) ? trim($userData['Tinh_TT']) : '';
    
    // Thêm các phần không rỗng vào mảng
    if (!empty($diachi)) {
        $parts[] = htmlspecialchars($diachi, ENT_QUOTES, 'UTF-8');
    }
    if (!empty($phuongXa)) {
        $parts[] = htmlspecialchars($phuongXa, ENT_QUOTES, 'UTF-8');
    }
    if (!empty($quanHuyen)) {
        $parts[] = htmlspecialchars($quanHuyen, ENT_QUOTES, 'UTF-8');
    }
    if (!empty($tinh)) {
        $parts[] = htmlspecialchars($tinh, ENT_QUOTES, 'UTF-8');
    }
    
    // Nối các phần bằng dấu phẩy và khoảng trắng
    return !empty($parts) ? implode(', ', $parts) : 'N/A';
}

function get_user_raw($field, $default = '') {
    global $userData;
    if (!array_key_exists($field, $userData)) {
        return $default;
    }
    $value = $userData[$field];
    if ($value instanceof DateTime) {
        return $value->format('Y-m-d');
    }
    if (is_scalar($value)) {
        return trim((string)$value);
    }
    return $default;
}

function get_new_permanent_address() {
    global $userData;
    $parts = [];

    $diachi = !empty($userData['Diachi_TT']) ? trim($userData['Diachi_TT']) : '';
    $phuongXaNew = !empty($userData['PhuongXaN_TT']) ? trim($userData['PhuongXaN_TT']) : '';
    $tinhNew = !empty($userData['TinhN_TT']) ? trim($userData['TinhN_TT']) : '';

    if (!empty($diachi)) {
        $parts[] = htmlspecialchars($diachi, ENT_QUOTES, 'UTF-8');
    }
    if (!empty($phuongXaNew)) {
        $parts[] = htmlspecialchars($phuongXaNew, ENT_QUOTES, 'UTF-8');
    }
    if (!empty($tinhNew)) {
        $parts[] = htmlspecialchars($tinhNew, ENT_QUOTES, 'UTF-8');
    }

    return !empty($parts) ? implode(', ', $parts) : 'N/A';
}

// Avatar logic
$avatarUrl = 'data/avatar/no_avatar.png'; // Default avatar
if (!empty($userData['Maso_NV']) && !empty($userData['Hoten'])) {
    $employeeCode = trim($userData['Maso_NV']);
    $fullName = trim($userData['Hoten']);
    $expectedFilename = $employeeCode . '_' . $fullName . '.jpg';
    $expectedFilePath = __DIR__ . '/data/avatar/' . $expectedFilename;
    if (file_exists($expectedFilePath)) {
        $avatarUrl = 'data/avatar/' . $expectedFilename;
    }
}

?>

<style>
.profile-grid {
    padding: 0px;
}

.profile-container {
    display: flex;
    flex-direction: column; /* Stack vertically by default */
    gap: 20px;
}

.profile-sidebar {
    background: rgba(17, 46, 51, 0.5);
    border-radius: 16px;
    border: 1px solid rgba(122, 220, 201, 0.15);
    padding: 24px;
    text-align: center;
}

.profile-avatar {
    position: relative;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    overflow: hidden;
    margin: 0 auto 16px;
    border: 3px solid rgba(122, 220, 201, 0.4);
    background-color: rgba(0,0,0,0.2);
}

.profile-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.change-avatar-btn {
    position: absolute;
    inset: auto 0 0 0;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.65);
    border: none;
    color: #fff;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.25s ease;
}

.profile-avatar:hover .change-avatar-btn,
.profile-avatar:focus-within .change-avatar-btn {
    opacity: 1;
}

.change-avatar-btn svg {
    pointer-events: none;
}

.profile-sidebar .name {
    margin: 0 0 5px 0;
    color: #e8fbf6;
    font-size: 18px;
    font-weight: 600;
}

.profile-sidebar .employee-code {
    margin: 0;
    color: #7adcc9;
    font-size: 13px;
    font-family: 'Courier New', Courier, monospace;
}

.profile-main {
    width: 100%;
}

.profile-details {
    background: rgba(17, 46, 51, 0.5);
    border-radius: 16px;
    border: 1px solid rgba(122, 220, 201, 0.15);
    padding: 20px;
}

.profile-details .grid {
    display: grid;
    grid-template-columns: 1fr; /* Single column on mobile */
    gap: 16px;
}

.modal.profile-edit-modal {
    max-width: 780px;
    width: 100%;
}

#profile-edit-modal .form-grid {
    width: 100%;
}

#profile-edit-modal textarea {
    resize: vertical;
}

#profile-edit-modal .form-row.full textarea {
    min-height: 68px;
}

.gender-radio-group {
    display: flex;
    gap: 12px;
    align-items: center;
    padding: 10px 12px;
    background-color: rgba(0,0,0,0.25);
    border-radius: 8px;
    border: 1px solid rgba(122, 220, 201, 0.1);
}

.gender-radio-group label {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: #e8fbf6;
    cursor: pointer;
}

.gender-radio-group input[type="radio"] {
    accent-color: #7adcc9;
    width: 16px;
    height: 16px;
}

@media (max-width: 576px) {
    #profile-edit-modal input,
    #profile-edit-modal select,
    #profile-edit-modal textarea {
        font-size: 14px !important;
        line-height: 1.4;
    }
}

.profile-panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
}

.profile-panel-controls {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    justify-content: flex-end;
}

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

.profile-edit-btn: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);
}

.profile-edit-btn .btn-icon-wrapper {
    display: inline-grid;
    place-items: center;
    width: 14px;
    height: 14px;
}

.profile-edit-btn .btn-icon-wrapper svg {
    width: 14px;
    height: 14px;
}

.profile-edit-btn .btn-text-wrapper {
    font-size: 13px;
    font-weight: 500;
}

.detail-item {
    display: flex;
    flex-direction: column;
}

.detail-label {
    font-size: 11px;
    color: #9ec9c1;
    margin-bottom: 5px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.detail-value {
    font-size: 14px;
    color: #e8fbf6;
    font-weight: 500;
    padding: 10px 12px;
    background-color: rgba(0,0,0,0.25);
    border-radius: 8px;
    border: 1px solid rgba(122, 220, 201, 0.1);
    min-height: 40px;
    display: flex;
    align-items: center;
}

/* Desktop layout adjustments */
@media (min-width: 992px) {
    .profile-grid {
        padding: 0px;
    }
    .profile-container {
        flex-direction: row; /* Side-by-side on desktop */
        align-items: flex-start;
        gap: 24px;
    }
    .profile-sidebar {
        flex: 0 0 280px;
    }
    .profile-sidebar .profile-avatar {
        width: 140px;
        height: 140px;
    }
    .profile-details .grid {
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 20px;
    }
    .profile-details {
        padding: 24px;
    }
}

@media (max-width: 768px) {
    .profile-panel-controls {
        width: 100%;
        justify-content: flex-start;
    }
    .profile-edit-btn {
        flex: 1 1 100%;
        max-width: 100%;
        text-align: center;
    }
}
</style>

<section class="panel-grid profile-grid">
    <div class="panel wide">
        <header class="panel-header profile-panel-header">
            <h3><?= htmlspecialchars($messages['profile_page_title'] ?? 'Hồ Sơ Cá Nhân', ENT_QUOTES, 'UTF-8') ?></h3>
            <div class="panel-controls profile-panel-controls">
                <button type="button" class="btn profile-edit-btn" data-profile-edit="true">
                    <span aria-hidden="true" class="btn-icon-wrapper">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M4 21v-3l12.5-12.5a1 1 0 0 1 1.5 0l2 2a1 1 0 0 1 0 1.5L7 21H4z"></path>
                            <path d="M14 5l3 3"></path>
                        </svg>
                    </span>
                    <span class="btn-text-wrapper"><?= htmlspecialchars($messages['profile_btn_edit'] ?? 'Sửa hồ sơ', ENT_QUOTES, 'UTF-8') ?></span>
                </button>
            </div>
        </header>

        <div class="profile-container">
            <div class="profile-sidebar">
                <div class="profile-avatar" id="profile-avatar-container">
                    <img src="<?= htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($messages['profile_avatar_alt'] ?? 'Hình đại diện', ENT_QUOTES, 'UTF-8') ?>" id="profile-avatar-img">
                    <button type="button" class="change-avatar-btn" title="Thay đổi ảnh đại diện">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H3a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h9z"/><path d="m16 16-4-4-4 4"/><path d="M12 12v9"/></svg>
                    </button>
                    <form id="avatar-upload-form" action="modules/avatar_upload.php" method="post" enctype="multipart/form-data" style="display:none;">
                        <input type="file" name="avatar_file" id="avatar-file-input" accept="image/jpeg, image/png, image/gif">
                    </form>
                </div>
                <h4 class="name"><?= get_user_field('Hoten') ?></h4>
                <p class="employee-code"><?= get_user_field('Maso_NV') ?></p>
            </div>
            <div class="profile-main">
                <div class="profile-details">
                    <div class="grid">
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_fullname'] ?? 'Họ và tên', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-fullname"><?= get_user_field('Hoten') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_employee_code'] ?? 'Mã số nhân viên', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-employee-code"><?= get_user_field('Maso_NV') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_birthdate'] ?? 'Ngày sinh', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-birthdate"><?= get_user_field('Ngaysinh') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_gender'] ?? 'Giới tính', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-gender"><?= get_user_field('Gioitinh') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_cccd'] ?? 'Số CCCD', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-cccd"><?= get_user_field('So_CCCD') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_cccd_issue_date'] ?? 'Ngày cấp CCCD', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-cccd-issue-date"><?= get_user_field('Ngaycap_CCCD') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_cmnd'] ?? 'Số CMND', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-cmnd"><?= get_user_field('So_CMND') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_marital_status'] ?? 'Tình trạng hôn nhân', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-marital-status"><?= get_user_field('Tinhtrang') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_address'] ?? 'Địa chỉ thường trú', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-address"><?= get_full_address() ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_new_address'] ?? 'Địa chỉ thường trú mới', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-new-address"><?= get_new_permanent_address() ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_email'] ?? 'Địa chỉ Email', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-email"><?= get_user_field('Email') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_phone'] ?? 'Điện thoại liên hệ', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-phone"><?= get_user_field('So_dien_thoai') ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label"><?= htmlspecialchars($messages['profile_label_bhxh'] ?? 'Mã số BHXH', ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="detail-value" id="profile-bhxh"><?= get_user_field('Maso_BHXH') ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Profile Edit Modal -->
<div id="profile-edit-modal" class="modal-backdrop" aria-hidden="true">
    <div class="modal profile-edit-modal">
        <div class="modal-header">
            <h4><?= htmlspecialchars($messages['profile_edit_modal_title'] ?? 'Chỉnh sửa hồ sơ', ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close>&times;</button>
        </div>
        <div class="modal-body">
            <form id="profile-edit-form"
                  class="form-grid grid-2"
                  novalidate
                  data-success-message="<?= htmlspecialchars($messages['profile_edit_success'] ?? 'Cập nhật hồ sơ thành công.', ENT_QUOTES, 'UTF-8') ?>"
                  data-error-message="<?= htmlspecialchars($messages['profile_edit_error'] ?? 'Không thể cập nhật hồ sơ.', ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="action" value="profile_update">

                <div class="form-row">
                    <label for="profile-birthdate-input"><?= htmlspecialchars($messages['profile_label_birthdate'] ?? 'Ngày sinh', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon date-icon" data-target="profile-birthdate-input">
                            <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="profile-birthdate-input" name="birthdate" value="<?= htmlspecialchars(get_user_raw('Ngaysinh'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-gender-input"><?= htmlspecialchars($messages['profile_label_gender'] ?? 'Giới tính', ENT_QUOTES, 'UTF-8') ?></label>
                    <?php $genderValue = get_user_raw('Gioitinh'); ?>
                    <div class="gender-radio-group" role="radiogroup" aria-labelledby="profile-gender-input">
                        <?php
                            $genderOptions = [
                                ['value' => 'Nam', 'label' => 'Nam'],
                                ['value' => 'Nữ', 'label' => 'Nữ']
                            ];
                        ?>
                        <?php foreach ($genderOptions as $option): ?>
                            <label>
                                <input type="radio" name="gender" value="<?= htmlspecialchars($option['value'], ENT_QUOTES, 'UTF-8') ?>" <?= ($genderValue === $option['value']) ? 'checked' : '' ?>>
                                <?= htmlspecialchars($option['label'], ENT_QUOTES, 'UTF-8') ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-cccd-input"><?= htmlspecialchars($messages['profile_label_cccd'] ?? 'Số CCCD', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M4 4h16v16H4z"/><path d="M4 9h16"/><path d="M9 13h2"/><path d="M13 13h2"/></svg>
                        </span>
                        <input type="text" id="profile-cccd-input" name="cccd" value="<?= htmlspecialchars(get_user_raw('So_CCCD'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-cccd-issue-input"><?= htmlspecialchars($messages['profile_label_cccd_issue_date'] ?? 'Ngày cấp CCCD', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon date-icon" data-target="profile-cccd-issue-input">
                            <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="profile-cccd-issue-input" name="cccd_issue_date" value="<?= htmlspecialchars(get_user_raw('Ngaycap_CCCD'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-cmnd-input"><?= htmlspecialchars($messages['profile_label_cmnd'] ?? 'Số CMND', 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="14" rx="2" ry="2"/><line x1="7" y1="8" x2="7" y2="12"/><line x1="11" y1="8" x2="11" y2="12"/><line x1="15" y1="8" x2="15" y2="12"/></svg>
                        </span>
                        <input type="text" id="profile-cmnd-input" name="cmnd" value="<?= htmlspecialchars(get_user_raw('So_CMND'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-marital-status-input"><?= htmlspecialchars($messages['profile_label_marital_status'] ?? 'Tình trạng hôn nhân', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><circle cx="9" cy="7" r="4"/><path d="M17 11l2 2-2 2"/><path d="M3 21v-2a4 4 0 0 1 4-4h4"/></svg>
                        </span>
                        <input type="text" id="profile-marital-status-input" name="marital_status" value="<?= htmlspecialchars(get_user_raw('Tinhtrang'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row full">
                    <label for="profile-address-input"><?= htmlspecialchars($messages['profile_label_address'] ?? 'Địa chỉ thường trú', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <textarea id="profile-address-input" name="address_street" rows="2"><?= htmlspecialchars(get_user_raw('Diachi_TT'), ENT_QUOTES, 'UTF-8') ?></textarea>
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-ward-input"><?= htmlspecialchars($messages['profile_label_address_ward'] ?? 'Phường/Xã', ENT_QUOTES, 'UTF-8') ?></label>
                    <?php $currentWard = get_user_raw('PhuongXa_TT'); ?>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5z"/></svg>
                        </span>
                        <div class="custom-select" 
                             id="profile-ward-select"
                             data-msg-select-district="<?= htmlspecialchars($messages['profile_edit_select_district_first'] ?? 'Vui lòng chọn Quận/Huyện trước', ENT_QUOTES, 'UTF-8') ?>"
                             data-msg-loading="<?= htmlspecialchars($messages['profile_edit_loading'] ?? 'Đang tải...', ENT_QUOTES, 'UTF-8') ?>"
                             data-msg-no-data="<?= htmlspecialchars($messages['profile_edit_no_data'] ?? 'Không có dữ liệu', ENT_QUOTES, 'UTF-8') ?>"
                             data-msg-error="<?= htmlspecialchars($messages['profile_edit_load_error'] ?? 'Lỗi khi tải dữ liệu', ENT_QUOTES, 'UTF-8') ?>">
                            <button type="button"
                                    class="custom-select-toggle"
                                    data-placeholder="--">
                                <?php
                                    $wardLabel = '--';
                                    if (!empty($currentWard)) {
                                        $wardLabel = htmlspecialchars($currentWard, ENT_QUOTES, 'UTF-8');
                                    }
                                    echo $wardLabel;
                                ?>
                            </button>
                            <div class="custom-select-menu" role="listbox">
                                <div class="custom-select-option" role="option" data-value="" aria-disabled="true">
                                    <?= htmlspecialchars($messages['profile_edit_select_district_first'] ?? 'Vui lòng chọn Quận/Huyện trước', ENT_QUOTES, 'UTF-8') ?>
                                </div>
                            </div>
                            <input type="hidden"
                                   name="address_ward"
                                   id="profile-ward-input"
                                   value="<?= htmlspecialchars($currentWard, ENT_QUOTES, 'UTF-8') ?>">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-district-input"><?= htmlspecialchars($messages['profile_label_address_district'] ?? 'Quận/Huyện', ENT_QUOTES, 'UTF-8') ?></label>
                    <?php $currentDistrict = get_user_raw('QuanHuyen_TT'); ?>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M3 12l18-9-9 18-2-7z"/><path d="M12 12l-2-7"/></svg>
                        </span>
                        <div class="custom-select" 
                             id="profile-district-select"
                             data-msg-select-province="<?= htmlspecialchars($messages['profile_edit_select_province_first'] ?? 'Vui lòng chọn Tỉnh/Thành phố trước', ENT_QUOTES, 'UTF-8') ?>"
                             data-msg-loading="<?= htmlspecialchars($messages['profile_edit_loading'] ?? 'Đang tải...', ENT_QUOTES, 'UTF-8') ?>"
                             data-msg-no-data="<?= htmlspecialchars($messages['profile_edit_no_data'] ?? 'Không có dữ liệu', ENT_QUOTES, 'UTF-8') ?>"
                             data-msg-error="<?= htmlspecialchars($messages['profile_edit_load_error'] ?? 'Lỗi khi tải dữ liệu', ENT_QUOTES, 'UTF-8') ?>">
                            <button type="button"
                                    class="custom-select-toggle"
                                    data-placeholder="--">
                                <?php
                                    $districtLabel = '--';
                                    if (!empty($currentDistrict)) {
                                        $districtLabel = htmlspecialchars($currentDistrict, ENT_QUOTES, 'UTF-8');
                                    }
                                    echo $districtLabel;
                                ?>
                            </button>
                            <div class="custom-select-menu" role="listbox">
                                <div class="custom-select-option" role="option" data-value="" aria-disabled="true">
                                    <?= htmlspecialchars($messages['profile_edit_select_province_first'] ?? 'Vui lòng chọn Tỉnh/Thành phố trước', ENT_QUOTES, 'UTF-8') ?>
                                </div>
                            </div>
                            <input type="hidden"
                                   name="address_district"
                                   id="profile-district-input"
                                   value="<?= htmlspecialchars($currentDistrict, ENT_QUOTES, 'UTF-8') ?>">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-province-input"><?= htmlspecialchars($messages['profile_label_address_province'] ?? 'Tỉnh/Thành phố', ENT_QUOTES, 'UTF-8') ?></label>
                    <?php $currentProvince = get_user_raw('Tinh_TT'); ?>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M21 16V8l-9-5-9 5v8l9 5 9-5z"/><path d="M3.3 7.7 12 13l8.7-5.3"/><path d="M12 22V13"/></svg>
                        </span>
                        <div class="custom-select" id="profile-province-select">
                            <button type="button"
                                    class="custom-select-toggle"
                                    data-placeholder="--">
                                <?php
                                    $label = '--';
                                    if (!empty($currentProvince)) {
                                        $label = htmlspecialchars($currentProvince, ENT_QUOTES, 'UTF-8');
                                    }
                                    echo $label;
                                ?>
                            </button>
                            <div class="custom-select-menu" role="listbox">
                                <?php if (!empty($provinceOptions)): ?>
                                    <?php foreach ($provinceOptions as $province): ?>
                                        <div class="custom-select-option"
                                             role="option"
                                             data-value="<?= htmlspecialchars($province, ENT_QUOTES, 'UTF-8') ?>">
                                            <?= htmlspecialchars($province, 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_province'] ?? 'Chưa có dữ liệu', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden"
                                   name="address_province"
                                   id="profile-province-input"
                                   value="<?= htmlspecialchars($currentProvince, ENT_QUOTES, 'UTF-8') ?>">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-new-ward-input"><?= htmlspecialchars($messages['profile_label_new_address_ward'] ?? 'Phường/Xã (mới)', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><circle cx="12" cy="10" r="3"/><path d="M19 20v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><path d="M12 2v3"/><path d="M5 5l1.5 1.5"/><path d="M19 5l-1.5 1.5"/></svg>
                        </span>
                        <input type="text" id="profile-new-ward-input" name="new_address_ward" value="<?= htmlspecialchars(get_user_raw('PhuongXaN_TT'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-new-province-input"><?= htmlspecialchars($messages['profile_label_new_address_province'] ?? 'Tỉnh/Thành phố (mới)', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M4 6h16v12H4z"/><path d="M2 10h20"/><path d="M12 6v12"/></svg>
                        </span>
                        <input type="text" id="profile-new-province-input" name="new_address_province" value="<?= htmlspecialchars(get_user_raw('TinhN_TT'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-email-input"><?= htmlspecialchars($messages['profile_label_email'] ?? 'Địa chỉ Email', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M4 4h16v16H4z"/><polyline points="22,6 12,13 2,6"/></svg>
                        </span>
                        <input type="email" id="profile-email-input" name="email" value="<?= htmlspecialchars(get_user_raw('Email'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-phone-input"><?= htmlspecialchars($messages['profile_label_phone'] ?? 'Điện thoại liên hệ', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M22 16.92V21a2 2 0 0 1-2.18 2A19.79 19.79 0 0 1 3 5.18 2 2 0 0 1 5 3h4.09a1 1 0 0 1 1 .75L11.91 7a1 1 0 0 1-.27.95l-2 2.05a16 16 0 0 0 6.32 6.32l2.05-2a1 1 0 0 1 .95-.27l3.24.81a1 1 0 0 1 .75 1z"/></svg>
                        </span>
                        <input type="tel" id="profile-phone-input" name="phone" value="<?= htmlspecialchars(get_user_raw('So_dien_thoai'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-row">
                    <label for="profile-bhxh-input"><?= htmlspecialchars($messages['profile_label_bhxh'] ?? 'Mã số BHXH', ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="input-wrap">
                        <span class="icon">
                            <svg viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                        </span>
                        <input type="text" id="profile-bhxh-input" name="bhxh" value="<?= htmlspecialchars(get_user_raw('Maso_BHXH'), ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="form-actions full">
                    <button type="button" class="btn btn-secondary" data-profile-cancel><?= htmlspecialchars($messages['profile_edit_cancel'] ?? 'Hủy', ENT_QUOTES, 'UTF-8') ?></button>
                    <button type="submit" class="btn btn-primary"><?= htmlspecialchars($messages['profile_edit_save'] ?? 'Lưu thay đổi', ENT_QUOTES, 'UTF-8') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var changeBtn = document.querySelector('.change-avatar-btn');
    var fileInput = document.getElementById('avatar-file-input');
    var uploadForm = document.getElementById('avatar-upload-form');

    if (changeBtn && fileInput && uploadForm) {
        changeBtn.addEventListener('click', function () {
            fileInput.click();
        });

        fileInput.addEventListener('change', function () {
            if (fileInput.files.length > 0) {
                uploadForm.submit();
            }
        });
    }

    var profileEditBtn = document.querySelector('[data-profile-edit]');
    var profileModal = document.getElementById('profile-edit-modal');
    var profileEditForm = document.getElementById('profile-edit-form');

    function openProfileModal() {
        if (!profileModal) return;
        profileModal.style.display = 'flex';
        profileModal.removeAttribute('aria-hidden');
        profileModal.setAttribute('aria-hidden', 'false');
        profileModal.classList.add('show');
        var firstField = profileModal.querySelector('input, textarea, select');
        if (firstField) {
            try {
                firstField.focus();
            } catch (_) {}
        }
    }

    function closeProfileModal() {
        if (!profileModal) return;
        profileModal.classList.remove('show');
        profileModal.setAttribute('aria-hidden', 'true');
        profileModal.style.display = 'none';
    }

    if (profileEditBtn && profileModal) {
        profileEditBtn.addEventListener('click', function() {
            openProfileModal();
        });
    }

    if (profileModal) {
        profileModal.addEventListener('click', function(event) {
            if (event.target === profileModal) {
                closeProfileModal();
            }
        });

        var closeBtn = profileModal.querySelector('[data-modal-close]');
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                closeProfileModal();
            });
        }

        var cancelBtn = profileModal.querySelector('[data-profile-cancel]');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', function(event) {
                event.preventDefault();
                closeProfileModal();
            });
        }

        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape' && profileModal.classList.contains('show')) {
                closeProfileModal();
            }
        });
    }

    function updateProfileDisplay(displayData) {
        if (!displayData || typeof displayData !== 'object') return;
        var mapping = {
            'birthdate': 'profile-birthdate',
            'gender': 'profile-gender',
            'cccd': 'profile-cccd',
            'cccd_issue_date': 'profile-cccd-issue-date',
            'cmnd': 'profile-cmnd',
            'marital_status': 'profile-marital-status',
            'full_address': 'profile-address',
            'new_address': 'profile-new-address',
            'email': 'profile-email',
            'phone': 'profile-phone',
            'bhxh': 'profile-bhxh'
        };

        Object.keys(mapping).forEach(function(key) {
            var el = document.getElementById(mapping[key]);
            if (!el) {
                return;
            }
            var value = displayData[key];
            el.textContent = value && value.trim ? value.trim() : (value || 'N/A');
        });
    }

    function updateFormValues(rawData) {
        if (!profileEditForm || !rawData) return;
        Object.keys(rawData).forEach(function(key) {
            var field = profileEditForm.querySelector('[name="' + key + '"]');
            if (!field) return;
            if (field.tagName === 'TEXTAREA') {
                field.value = rawData[key] || '';
            } else {
                field.value = rawData[key] || '';
            }
        });
    }

    (function setupProfileProvinceSelect() {
        var custom = document.getElementById('profile-province-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('profile-province-input');
        if (!toggle || !menu || !hidden) return;

        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var closeOnScroll = null;
        var closeOnResize = null;
        var anchorParent = null;
        var anchorNext = null;
        var isPortaled = false;

        function mountMenu() {
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }

        function unmountMenu() {
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) {
                    anchorParent.insertBefore(menu, anchorNext);
                } else {
                    anchorParent.appendChild(menu);
                }
            }
            isPortaled = false;
        }

        function positionMenu() {
            var r = toggle.getBoundingClientRect();
            var 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 (closeOnScroll) {
                window.removeEventListener('scroll', closeOnScroll, true);
                closeOnScroll = null;
            }
            if (closeOnResize) {
                window.removeEventListener('resize', closeOnResize);
                closeOnResize = null;
            }
        }

        (function initLabel() {
            var current = hidden.value ? hidden.value.trim() : '';
            if (!current) {
                toggle.textContent = placeholder;
                return;
            }
            var matched = null;
            var options = menu.querySelectorAll('.custom-select-option');
            options.forEach(function(opt) {
                if (opt.getAttribute('data-value') === current) {
                    matched = opt;
                }
            });
            toggle.textContent = matched ? matched.textContent.trim() : current;
        })();

        toggle.addEventListener('click', function(e) {
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                custom.classList.add('open');
                closeOnScroll = function(ev) {
                    if (menu.contains(ev.target)) return;
                    closeAll();
                };
                closeOnResize = function() {
                    closeAll();
                };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });

        menu.addEventListener('click', function(e) {
            var opt = e.target.closest('.custom-select-option');
            if (!opt || opt.hasAttribute('aria-disabled')) return;
            e.stopPropagation();
            var value = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim() || placeholder;
            var oldValue = hidden.value;
            hidden.value = value;
            toggle.textContent = label;

            var all = menu.querySelectorAll('.custom-select-option');
            all.forEach(function(item) {
                item.classList.toggle('is-selected', item === opt);
            });

            if (oldValue !== value) {
                var changeEvent = new Event('change', { bubbles: true });
                var inputEvent = new Event('input', { bubbles: true });
                hidden.dispatchEvent(changeEvent);
                hidden.dispatchEvent(inputEvent);
            }

            closeAll();
        });

        menu.addEventListener('wheel', function(e) {
            e.stopPropagation();
        }, { passive: true });
        menu.addEventListener('touchmove', function(e) {
            e.stopPropagation();
        }, { passive: true });
        menu.addEventListener('mousedown', function(e) {
            e.stopPropagation();
        });

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

    (function setupProfileDistrictSelect() {
        var custom = document.getElementById('profile-district-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('profile-district-input');
        var provinceInput = document.getElementById('profile-province-input');
        if (!toggle || !menu || !hidden || !provinceInput) return;

        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var msgSelectProvince = custom.getAttribute('data-msg-select-province') || 'Vui lòng chọn Tỉnh/Thành phố trước';
        var msgLoading = custom.getAttribute('data-msg-loading') || 'Đang tải...';
        var msgNoData = custom.getAttribute('data-msg-no-data') || 'Không có dữ liệu';
        var msgError = custom.getAttribute('data-msg-error') || 'Lỗi khi tải dữ liệu';

        var closeOnScroll = null;
        var closeOnResize = null;
        var anchorParent = null;
        var anchorNext = null;
        var isPortaled = false;
        var currentProvince = '';

        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 (closeOnScroll) {
                window.removeEventListener('scroll', closeOnScroll, true);
                closeOnScroll = null;
            }
            if (closeOnResize) {
                window.removeEventListener('resize', closeOnResize);
                closeOnResize = null;
            }
        }

        function showMessage(message) {
            menu.innerHTML = '<div class="custom-select-option" role="option" data-value="" aria-disabled="true">' + message + '</div>';
        }

        function loadDistricts(province, resetSelection) {
            province = province ? province.trim() : '';
            if (!province) {
                showMessage(msgSelectProvince);
                if (resetSelection !== false) {
                    var oldValue = hidden.value;
                    hidden.value = '';
                    toggle.textContent = placeholder;
                    if (oldValue !== '') {
                        var changeEvent = new Event('change', { bubbles: true });
                        var inputEvent = new Event('input', { bubbles: true });
                        hidden.dispatchEvent(changeEvent);
                        hidden.dispatchEvent(inputEvent);
                    }
                }
                currentProvince = '';
                return;
            }

            if (province === currentProvince && resetSelection === false) {
                return;
            }
            currentProvince = province;

            showMessage(msgLoading);

            var previousValue = hidden.value ? hidden.value.trim() : '';
            var previousLabel = toggle.textContent.trim();

            fetch('modules/get_districts.php?province=' + encodeURIComponent(province), {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                return response.json();
            })
            .then(function(data) {
                menu.innerHTML = '';
                if (data.success && Array.isArray(data.districts) && data.districts.length > 0) {
                    data.districts.forEach(function(name) {
                        var value = (name || '').trim();
                        if (!value) {
                            return;
                        }
                        var opt = document.createElement('div');
                        opt.className = 'custom-select-option';
                        opt.setAttribute('role', 'option');
                        opt.setAttribute('data-value', value);
                        opt.textContent = value;
                        if (previousValue && value === previousValue) {
                            opt.classList.add('is-selected');
                        }
                        menu.appendChild(opt);
                    });

                    if (previousValue) {
                        var found = Array.prototype.some.call(menu.children, function(item) {
                            return item.getAttribute && item.getAttribute('data-value') === previousValue;
                        });
                        if (found) {
                            hidden.value = previousValue;
                            toggle.textContent = previousLabel || previousValue;
                        } else if (resetSelection !== false) {
                            var oldValue = hidden.value;
                            hidden.value = '';
                            toggle.textContent = placeholder;
                            if (oldValue !== '') {
                                var changeEvent = new Event('change', { bubbles: true });
                                var inputEvent = new Event('input', { bubbles: true });
                                hidden.dispatchEvent(changeEvent);
                                hidden.dispatchEvent(inputEvent);
                            }
                        }
                    } else if (resetSelection !== false) {
                        var oldValue = hidden.value;
                        hidden.value = '';
                        toggle.textContent = placeholder;
                        if (oldValue !== '') {
                            var changeEvent = new Event('change', { bubbles: true });
                            var inputEvent = new Event('input', { bubbles: true });
                            hidden.dispatchEvent(changeEvent);
                            hidden.dispatchEvent(inputEvent);
                        }
                    }
                } else {
                    showMessage(data && data.message ? data.message : msgNoData);
                    if (resetSelection !== false) {
                        var oldValue = hidden.value;
                        hidden.value = '';
                        toggle.textContent = placeholder;
                        if (oldValue !== '') {
                            var changeEvent = new Event('change', { bubbles: true });
                            var inputEvent = new Event('input', { bubbles: true });
                            hidden.dispatchEvent(changeEvent);
                            hidden.dispatchEvent(inputEvent);
                        }
                    }
                }
            })
            .catch(function(error) {
                console.error('Error loading districts:', error);
                showMessage(msgError);
                if (resetSelection !== false) {
                    var oldValue = hidden.value;
                    hidden.value = '';
                    toggle.textContent = placeholder;
                    if (oldValue !== '') {
                        var changeEvent = new Event('change', { bubbles: true });
                        var inputEvent = new Event('input', { bubbles: true });
                        hidden.dispatchEvent(changeEvent);
                        hidden.dispatchEvent(inputEvent);
                    }
                }
            });
        }

        // Initialize label
        (function initLabel() {
            var current = hidden.value ? hidden.value.trim() : '';
            if (!current) {
                toggle.textContent = placeholder;
            } else {
                toggle.textContent = current;
            }
        })();

        // Load initial districts if province is preset
        var initialProvince = provinceInput.value ? provinceInput.value.trim() : '';
        if (initialProvince) {
            loadDistricts(initialProvince, false);
        } else {
            showMessage(msgSelectProvince);
        }

        provinceInput.addEventListener('change', function() {
            var province = provinceInput.value ? provinceInput.value.trim() : '';
            loadDistricts(province, true); // This will reset district value
            // Reset ward immediately when province changes
            var wardSelect = document.getElementById('profile-ward-select');
            var wardInput = document.getElementById('profile-ward-input');
            var wardToggle = wardSelect ? wardSelect.querySelector('.custom-select-toggle') : null;
            if (wardSelect && wardInput && wardToggle) {
                var wardPlaceholder = wardToggle.getAttribute('data-placeholder') || '--';
                wardInput.value = '';
                wardToggle.textContent = wardPlaceholder;
                var wardMenu = wardSelect.querySelector('.custom-select-menu');
                if (wardMenu) {
                    var msgSelectDistrict = wardSelect.getAttribute('data-msg-select-district') || 'Vui lòng chọn Quận/Huyện trước';
                    wardMenu.innerHTML = '<div class="custom-select-option" role="option" data-value="" aria-disabled="true">' + msgSelectDistrict + '</div>';
                }
            }
        });

        toggle.addEventListener('click', function(e) {
            e.stopPropagation();
            var province = provinceInput.value ? provinceInput.value.trim() : '';
            if (!province) {
                showMessage(msgSelectProvince);
                return;
            }
            var willOpen = !custom.classList.contains('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                custom.classList.add('open');
                closeOnScroll = function(ev) {
                    if (menu.contains(ev.target)) return;
                    closeAll();
                };
                closeOnResize = function() {
                    closeAll();
                };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });

        menu.addEventListener('click', function(e) {
            var opt = e.target.closest('.custom-select-option');
            if (!opt || opt.hasAttribute('aria-disabled')) return;
            e.stopPropagation();
            var value = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim() || placeholder;
            var oldValue = hidden.value;
            hidden.value = value;
            toggle.textContent = label;

            var all = menu.querySelectorAll('.custom-select-option');
            all.forEach(function(item) {
                item.classList.toggle('is-selected', item === opt);
            });

            if (oldValue !== value) {
                var changeEvent = new Event('change', { bubbles: true });
                var inputEvent = new Event('input', { bubbles: true });
                hidden.dispatchEvent(changeEvent);
                hidden.dispatchEvent(inputEvent);
            }

            closeAll();
        });

        menu.addEventListener('wheel', function(e) {
            e.stopPropagation();
        }, { passive: true });
        menu.addEventListener('touchmove', function(e) {
            e.stopPropagation();
        }, { passive: true });
        menu.addEventListener('mousedown', function(e) {
            e.stopPropagation();
        });

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

    (function setupProfileWardSelect() {
        var custom = document.getElementById('profile-ward-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('profile-ward-input');
        var districtInput = document.getElementById('profile-district-input');
        if (!toggle || !menu || !hidden || !districtInput) return;

        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var msgSelectDistrict = custom.getAttribute('data-msg-select-district') || 'Vui lòng chọn Quận/Huyện trước';
        var msgLoading = custom.getAttribute('data-msg-loading') || 'Đang tải...';
        var msgNoData = custom.getAttribute('data-msg-no-data') || 'Không có dữ liệu';
        var msgError = custom.getAttribute('data-msg-error') || 'Lỗi khi tải dữ liệu';

        var closeOnScroll = null;
        var closeOnResize = null;
        var anchorParent = null;
        var anchorNext = null;
        var isPortaled = false;
        var currentDistrict = '';

        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 (closeOnScroll) {
                window.removeEventListener('scroll', closeOnScroll, true);
                closeOnScroll = null;
            }
            if (closeOnResize) {
                window.removeEventListener('resize', closeOnResize);
                closeOnResize = null;
            }
        }

        function showMessage(message) {
            menu.innerHTML = '<div class="custom-select-option" role="option" data-value="" aria-disabled="true">' + message + '</div>';
        }

        function loadWards(district, resetSelection) {
            district = district ? district.trim() : '';
            if (!district) {
                showMessage(msgSelectDistrict);
                if (resetSelection !== false) {
                    hidden.value = '';
                    toggle.textContent = placeholder;
                }
                currentDistrict = '';
                return;
            }

            if (district === currentDistrict && resetSelection === false) {
                return;
            }
            currentDistrict = district;

            showMessage(msgLoading);

            var previousValue = hidden.value ? hidden.value.trim() : '';
            var previousLabel = toggle.textContent.trim();

            fetch('modules/get_wards.php?district=' + encodeURIComponent(district), {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                return response.json();
            })
            .then(function(data) {
                menu.innerHTML = '';
                if (data.success && Array.isArray(data.wards) && data.wards.length > 0) {
                    data.wards.forEach(function(name) {
                        var value = (name || '').trim();
                        if (!value) {
                            return;
                        }
                        var opt = document.createElement('div');
                        opt.className = 'custom-select-option';
                        opt.setAttribute('role', 'option');
                        opt.setAttribute('data-value', value);
                        opt.textContent = value;
                        if (previousValue && value === previousValue) {
                            opt.classList.add('is-selected');
                        }
                        menu.appendChild(opt);
                    });

                    if (previousValue) {
                        var found = Array.prototype.some.call(menu.children, function(item) {
                            return item.getAttribute && item.getAttribute('data-value') === previousValue;
                        });
                        if (found) {
                            hidden.value = previousValue;
                            toggle.textContent = previousLabel || previousValue;
                        } else if (resetSelection !== false) {
                            hidden.value = '';
                            toggle.textContent = placeholder;
                        }
                    } else if (resetSelection !== false) {
                        hidden.value = '';
                        toggle.textContent = placeholder;
                    }
                } else {
                    showMessage(data && data.message ? data.message : msgNoData);
                    if (resetSelection !== false) {
                        hidden.value = '';
                        toggle.textContent = placeholder;
                    }
                }
            })
            .catch(function(error) {
                console.error('Error loading wards:', error);
                showMessage(msgError);
                if (resetSelection !== false) {
                    hidden.value = '';
                    toggle.textContent = placeholder;
                }
            });
        }

        // Initialize label
        (function initLabel() {
            var current = hidden.value ? hidden.value.trim() : '';
            if (!current) {
                toggle.textContent = placeholder;
            } else {
                toggle.textContent = current;
            }
        })();

        // Load initial wards if district is preset
        var initialDistrict = districtInput.value ? districtInput.value.trim() : '';
        if (initialDistrict) {
            loadWards(initialDistrict, false);
        } else {
            showMessage(msgSelectDistrict);
        }

        districtInput.addEventListener('change', function() {
            var district = districtInput.value ? districtInput.value.trim() : '';
            loadWards(district, true); // resetSelection = true will reset ward value
        });

        // Expose function to reset ward select from outside
        window.profileWardSelectLoader = function(resetSelection) {
            var district = districtInput.value ? districtInput.value.trim() : '';
            if (district) {
                loadWards(district, resetSelection === true);
            } else {
                showMessage(msgSelectDistrict);
                if (resetSelection === true) {
                    hidden.value = '';
                    toggle.textContent = placeholder;
                }
            }
        };

        toggle.addEventListener('click', function(e) {
            e.stopPropagation();
            var district = districtInput.value ? districtInput.value.trim() : '';
            if (!district) {
                showMessage(msgSelectDistrict);
                return;
            }
            var willOpen = !custom.classList.contains('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                custom.classList.add('open');
                closeOnScroll = function(ev) {
                    if (menu.contains(ev.target)) return;
                    closeAll();
                };
                closeOnResize = function() {
                    closeAll();
                };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });

        menu.addEventListener('click', function(e) {
            var opt = e.target.closest('.custom-select-option');
            if (!opt || opt.hasAttribute('aria-disabled')) return;
            e.stopPropagation();
            var value = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim() || placeholder;
            var oldValue = hidden.value;
            hidden.value = value;
            toggle.textContent = label;

            var all = menu.querySelectorAll('.custom-select-option');
            all.forEach(function(item) {
                item.classList.toggle('is-selected', item === opt);
            });

            if (oldValue !== value) {
                var changeEvent = new Event('change', { bubbles: true });
                var inputEvent = new Event('input', { bubbles: true });
                hidden.dispatchEvent(changeEvent);
                hidden.dispatchEvent(inputEvent);
            }

            closeAll();
        });

        menu.addEventListener('wheel', function(e) {
            e.stopPropagation();
        }, { passive: true });
        menu.addEventListener('touchmove', function(e) {
            e.stopPropagation();
        }, { passive: true });
        menu.addEventListener('mousedown', function(e) {
            e.stopPropagation();
        });

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

    if (profileEditForm) {
        profileEditForm.addEventListener('submit', function(event) {
            event.preventDefault();
            var formData = new FormData(profileEditForm);

            fetch('modules/profile_update.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(payload) {
                var successMessage = profileEditForm.getAttribute('data-success-message') || 'Cập nhật hồ sơ thành công.';
                var errorMessage = profileEditForm.getAttribute('data-error-message') || 'Không thể cập nhật hồ sơ.';

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

                if (payload && payload.success) {
                    updateProfileDisplay(payload.data && payload.data.display ? payload.data.display : {});
                    if (payload.data && payload.data.raw) {
                        updateFormValues(payload.data.raw);
                    }
                    if (window.showToast) {
                        window.showToast('success', '<div class="success-header">' + successTitle + '</div>' + (payload.message || successMessage));
                    } else {
                        alert(payload.message || successMessage);
                    }
                    closeProfileModal();
                } else {
                    var message = (payload && payload.message) ? payload.message : errorMessage;
                    if (window.showToast) {
                        window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + message);
                    } else {
                        alert(message);
                    }
                }
            })
            .catch(function(error) {
                console.error('Profile update error:', error);
                var fallbackError = profileEditForm.getAttribute('data-error-message') || 'Không thể cập nhật hồ sơ.';
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                if (window.showToast) {
                    window.showToast('error', '<div class="error-header">' + errorTitle + '</div>' + fallbackError);
                } else {
                    alert(fallbackError);
                }
            });
        });
    }

    function setupProfileDatePickers() {
        if (!profileModal) return;

        var dateIcons = profileModal.querySelectorAll('.date-icon[data-target]');
        dateIcons.forEach(function(icon) {
            icon.addEventListener('click', function() {
                var targetId = icon.getAttribute('data-target');
                if (!targetId) return;
                var targetInput = document.getElementById(targetId);
                if (targetInput) {
                    try {
                        targetInput.focus();
                        targetInput.showPicker();
                    } catch (err) {
                        try {
                            targetInput.click();
                        } catch (_) {}
                    }
                }
            });
        });

        var dateInputs = profileModal.querySelectorAll('input[type="date"]');
        dateInputs.forEach(function(input) {
            input.addEventListener('click', function() {
                try {
                    input.focus();
                    input.showPicker();
                } catch (err) {
                    // fallback to native click
                }
            });

            input.addEventListener('focus', function() {
                try {
                    setTimeout(function() {
                        if (document.activeElement === input) {
                            input.showPicker();
                        }
                    }, 80);
                } catch (err) {
                    // fallback to native behavior
                }
            });
        });
    }

    setupProfileDatePickers();
});
</script>
