<?php
class ProfileController extends Controller
{
    public function show(Request $request): void
    {
        $user = Auth::user();
        $this->view('auth/profile', [
            'title' => 'Profile',
            'breadcrumbs' => [['label' => 'Profile']],
            'user' => $user,
        ], 'app');
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid security token'], 403);
            return;
        }

        $validator = new Validator($request->all(), [
            'full_name_en' => 'required|string|max:300',
            'email'        => 'required|email|max:191',
            'phone'        => 'nullable|string|max:20',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $this->db()->update('auth_users', $data, 'id = ?', [Auth::id()]);

        $this->audit('update', 'user', Auth::id(), 'Updated own profile');
        $this->json(['success' => true, 'message' => 'Profile updated successfully']);
    }

    public function showChangePassword(Request $request): void
    {
        $this->view('auth/change_password', [
            'title' => lang('auth.change_password'),
            'breadcrumbs' => [['label' => lang('auth.change_password')]],
        ], 'app');
    }

    public function changePassword(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            if ($request->isAjax()) {
                $this->json(['success' => false, 'message' => 'Invalid security token'], 403);
                return;
            }
            $this->redirect('/change-password');
            return;
        }

        $currentPassword = $request->post('current_password', '');
        $newPassword = $request->post('new_password', '');
        $confirmPassword = $request->post('new_password_confirmation', '');

        $errors = [];
        if (empty($currentPassword)) $errors['current_password'] = ['Current password is required'];
        if (empty($newPassword)) $errors['new_password'] = ['New password is required'];
        if ($newPassword !== $confirmPassword) $errors['new_password_confirmation'] = ['Passwords do not match'];
        if (mb_strlen($newPassword) < (int)Config::get('password_min_length', 8)) {
            $errors['new_password'] = ['Password must be at least ' . Config::get('password_min_length', 8) . ' characters'];
        }

        if (!empty($errors)) {
            if ($request->isAjax()) {
                $this->json(['success' => false, 'errors' => $errors], 422);
                return;
            }
            Session::flash('errors', $errors);
            $this->redirect('/change-password');
            return;
        }

        $user = $this->db()->fetchOne("SELECT password_hash FROM auth_users WHERE id = ?", [Auth::id()]);
        if (!$user || !password_verify($currentPassword, $user['password_hash'])) {
            $msg = 'Current password is incorrect';
            if ($request->isAjax()) {
                $this->json(['success' => false, 'errors' => ['current_password' => [$msg]]], 422);
                return;
            }
            Session::flash('error', $msg);
            $this->redirect('/change-password');
            return;
        }

        $hash = password_hash($newPassword, PASSWORD_BCRYPT, ['cost' => 12]);
        $this->db()->update('auth_users', [
            'password_hash' => $hash,
            'password_changed_at' => date('Y-m-d H:i:s'),
            'must_change_password' => 0,
        ], 'id = ?', [Auth::id()]);

        // Update session
        $sessionUser = Session::get('auth_user');
        $sessionUser['must_change_password'] = 0;
        Session::set('auth_user', $sessionUser);

        $this->audit('update', 'user', Auth::id(), 'Changed own password');

        if ($request->isAjax()) {
            $this->json(['success' => true, 'message' => 'Password changed successfully', 'redirect' => '/dashboard']);
            return;
        }
        Session::flash('alerts', [['type' => 'success', 'message' => 'Password changed successfully']]);
        $this->redirect('/dashboard');
    }
}