<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal memproses permintaan.', 'errors' => []];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) {
    http_response_code(401);
    $response['message'] = 'Sesi berakhir. Silakan login kembali.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in update_profile_settings.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

try {
    $userId = $_SESSION['user_id'];
    $action = sanitize_input($_POST['action'] ?? '');
    $auth = new Auth($pdo);

    if ($action === 'update_info') {
        $fullName = sanitize_input($_POST['full_name'] ?? null);
        $phoneNumber = sanitize_input($_POST['phone_number'] ?? null);
        $errors = [];

        if ($phoneNumber !== null && $phoneNumber !== '' && !preg_match('/^[0-9]{10,15}$/', $phoneNumber)) {
            $errors['phone_number'] = 'Format nomor handphone tidak valid (hanya angka, 10-15 digit).';
        }

        if (!empty($errors)) {
            http_response_code(400);
            $response['message'] = 'Periksa kembali input Anda.';
            $response['errors'] = $errors;
        } else {
            $updateData = [
                'full_name' => $fullName ?: null,
                'phone_number' => $phoneNumber ?: null 
            ];

            if ($auth->updateProfile($userId, $updateData)) {
                $response['success'] = true;
                $response['message'] = 'Informasi profil berhasil diperbarui.';
                if (isset($updateData['full_name'])) {
                    $_SESSION['user_fullname'] = $updateData['full_name'];
                }
            } else {
                http_response_code(500);
                $response['message'] = 'Gagal memperbarui informasi profil karena kesalahan server.';
            }
        }

    } elseif ($action === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmNewPassword = $_POST['confirm_new_password'] ?? '';
        $errors = [];

        if (empty($currentPassword)) {
            $errors['current_password'] = 'Password saat ini wajib diisi.';
        }
        if (empty($newPassword)) {
            $errors['new_password'] = 'Password baru wajib diisi.';
        } elseif (strlen($newPassword) < 6) {
            $errors['new_password'] = 'Password baru minimal harus 6 karakter.';
        }
        if (empty($confirmNewPassword)) {
            $errors['confirm_new_password'] = 'Konfirmasi password baru wajib diisi.';
        } elseif ($newPassword !== $confirmNewPassword) {
            $errors['confirm_new_password'] = 'Konfirmasi password baru tidak cocok.';
        }

        if (!empty($errors)) {
            http_response_code(400);
            $response['message'] = 'Periksa kembali input Anda.';
            $response['errors'] = $errors;
        } else {
            $updateResult = $auth->updatePassword($userId, $currentPassword, $newPassword);

            if ($updateResult === true) {
                $response['success'] = true;
                $response['message'] = 'Password berhasil diganti.';
            } elseif ($updateResult === 'invalid_current_password') {
                http_response_code(400);
                $response['message'] = 'Password saat ini salah.';
                $response['errors']['current_password'] = 'Password saat ini salah.';
            } else { 
                http_response_code(500);
                $response['message'] = 'Gagal mengganti password karena kesalahan server.';
            }
        }

    } else {
        http_response_code(400);
        $response['message'] = 'Aksi tidak valid.';
    }

} catch (\PDOException $e) {
    error_log("Update Profile Settings DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("Update Profile Settings General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
