<?php

declare(strict_types=1);

namespace App\Modules\Auth;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Session;

/**
 * SettingsController — Authenticated User Settings HTTP Handler
 *
 * Handles showing the user settings / change password form and processing
 * password update requests across all portals.
 *
 * @package Inveetaire
 * @ref     RC-003
 */
class SettingsController extends BaseController
{
    private AuthService $authService;

    public function __construct()
    {
        parent::__construct();
        $this->authService = new AuthService();
    }

    /**
     * Display the settings page (Change Password).
     *
     * @param Request $request
     * @return void
     */
    public function edit(Request $request): void
    {
        $role = (string) Session::get('role_snapshot');
        
        // Dynamically set layout based on current portal role
        $this->layout = ($role === 'super_admin') ? 'admin' : (($role === 'crew') ? 'crew' : 'couple');

        $this->render('auth/settings', [
            'title'   => 'Account Settings',
            'errors'  => Session::get('errors') ?? [],
            'success' => Session::get('success') ?? null,
        ]);

        Session::set('errors', null);
        Session::set('success', null);
    }

    /**
     * Process password change request.
     *
     * @param Request $request
     * @return void
     */
    public function update(Request $request): void
    {
        $userId          = (int) Session::get('auth_user_id');
        $currentPassword = (string) $request->post('current_password', '');
        $newPassword     = (string) $request->post('new_password', '');
        $confirmPassword = (string) $request->post('confirm_password', '');
        $clientIp        = (string) $request->getIp();
        $role            = (string) Session::get('role_snapshot');

        $prefix = ($role === 'super_admin') ? '/app/admin' : (($role === 'crew') ? '/app/crew' : '/app/couple');

        $result = $this->authService->changePassword($userId, $currentPassword, $newPassword, $confirmPassword, $clientIp);

        if (!$result['success']) {
            $this->flash('error', $result['message']);
            Session::set('errors', ['system' => $result['message']]);
            $this->redirect($prefix . '/settings');
            return;
        }

        $this->flash('success', $result['message']);
        Session::set('success', $result['message']);
        $this->redirect($prefix . '/settings');
    }
}
