<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!defined('LUNA_APP')) {
    define('LUNA_APP', true);
}

header('Content-Type: application/json; charset=utf-8');

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

$currentLocale = $_SESSION['lang'] ?? 'vn';
$messages = load_messages($currentLocale);

function json_response(bool $success, string $message, array $data = [], int $statusCode = 200): void {
    http_response_code($statusCode);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

function format_date_for_storage(?string $value): ?string {
    if (empty($value)) {
        return null;
    }
    try {
        $dt = new DateTime($value);
        return $dt->format('Y-m-d');
    } catch (Throwable $e) {
        return null;
    }
}

function format_date_for_display(?string $value): string {
    if (empty($value)) {
        return 'N/A';
    }
    try {
        $dt = new DateTime($value);
        return $dt->format('d/m/Y');
    } catch (Throwable $e) {
        return $value;
    }
}

function build_address(?string $street, ?string $ward, ?string $district, ?string $province): string {
    $parts = [];
    foreach ([$street, $ward, $district, $province] as $segment) {
        $segment = trim((string)$segment);
        if (!empty($segment)) {
            $parts[] = $segment;
        }
    }
    return !empty($parts) ? implode(', ', $parts) : 'N/A';
}

function build_new_address(?string $street, ?string $ward, ?string $province): string {
    $parts = [];
    foreach ([$street, $ward, $province] as $segment) {
        $segment = trim((string)$segment);
        if (!empty($segment)) {
            $parts[] = $segment;
        }
    }
    return !empty($parts) ? implode(', ', $parts) : 'N/A';
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, $messages['profile_edit_invalid_method'] ?? 'Phương thức không hợp lệ.', [], 405);
}

if (empty($_SESSION['user']['username'])) {
    json_response(false, $messages['profile_edit_unauthorized'] ?? 'Bạn cần đăng nhập để thực hiện thao tác này.', [], 401);
}

$msnv = $_SESSION['user']['username'];

$fieldMap = [
    'Ngaysinh' => ['key' => 'birthdate', 'type' => 'date'],
    'Gioitinh' => ['key' => 'gender'],
    'So_CCCD' => ['key' => 'cccd'],
    'Ngaycap_CCCD' => ['key' => 'cccd_issue_date', 'type' => 'date'],
    'So_CMND' => ['key' => 'cmnd'],
    'Tinhtrang' => ['key' => 'marital_status'],
    'Diachi_TT' => ['key' => 'address_street'],
    'PhuongXa_TT' => ['key' => 'address_ward'],
    'QuanHuyen_TT' => ['key' => 'address_district'],
    'Tinh_TT' => ['key' => 'address_province'],
    'PhuongXaN_TT' => ['key' => 'new_address_ward'],
    'TinhN_TT' => ['key' => 'new_address_province'],
    'Email' => ['key' => 'email'],
    'So_dien_thoai' => ['key' => 'phone'],
    'Maso_BHXH' => ['key' => 'bhxh'],
];

$updates = [];
$params = [];
$rawValues = [];

foreach ($fieldMap as $column => $meta) {
    $formKey = $meta['key'];
    $rawValue = isset($_POST[$formKey]) ? trim((string)$_POST[$formKey]) : '';
    $rawValues[$formKey] = $rawValue;

    if (($meta['type'] ?? '') === 'date') {
        $storedValue = format_date_for_storage($rawValue);
    } else {
        $storedValue = $rawValue !== '' ? $rawValue : null;
    }

    $updates[] = $column . ' = ?';
    $params[] = $storedValue;
}

if (empty($updates)) {
    json_response(false, $messages['profile_edit_no_changes'] ?? 'Không có dữ liệu để cập nhật.', [], 400);
}

$params[] = $msnv;

try {
    $conn = db_connect();
    if (!$conn) {
        throw new RuntimeException('Could not connect to database.');
    }

    $sql = 'UPDATE DataWork SET ' . implode(', ', $updates) . ' WHERE Maso_NV = ?';
    $stmt = sqlsrv_prepare($conn, $sql, $params);

    if ($stmt === false || !sqlsrv_execute($stmt)) {
        $errors = sqlsrv_errors();
        error_log('Profile update failed for ' . $msnv . ': ' . print_r($errors, true));
        throw new RuntimeException('Failed to update profile.');
    }

    sqlsrv_free_stmt($stmt);
    db_disconnect($conn);
} catch (Throwable $e) {
    error_log('Profile update error for ' . $msnv . ': ' . $e->getMessage());
    json_response(false, $messages['profile_edit_error'] ?? 'Không thể cập nhật hồ sơ.', [], 500);
}

$display = [
    'birthdate' => format_date_for_display($rawValues['birthdate'] ?? null),
    'gender' => $rawValues['gender'] ?? 'N/A',
    'cccd' => $rawValues['cccd'] ?? 'N/A',
    'cccd_issue_date' => format_date_for_display($rawValues['cccd_issue_date'] ?? null),
    'cmnd' => $rawValues['cmnd'] ?? 'N/A',
    'marital_status' => $rawValues['marital_status'] ?? 'N/A',
    'full_address' => build_address(
        $rawValues['address_street'] ?? '',
        $rawValues['address_ward'] ?? '',
        $rawValues['address_district'] ?? '',
        $rawValues['address_province'] ?? ''
    ),
    'new_address' => build_new_address(
        $rawValues['address_street'] ?? '',
        $rawValues['new_address_ward'] ?? '',
        $rawValues['new_address_province'] ?? ''
    ),
    'email' => $rawValues['email'] ?? 'N/A',
    'phone' => $rawValues['phone'] ?? 'N/A',
    'bhxh' => $rawValues['bhxh'] ?? 'N/A',
];

$successMessage = $messages['profile_edit_success'] ?? 'Cập nhật hồ sơ thành công.';

json_response(true, $successMessage, [
    'display' => $display,
    'raw' => $rawValues
]);

