<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Response;
use App\Core\Session;
use App\Services\UserService;
use InvalidArgumentException;

final class ProfileController extends Controller
{
    public function __construct(private ?UserService $service = null) { $this->service ??= new UserService(); }

    public function show(): Response
    {
        $id = Auth::id();
        if ($id === null) return Response::redirect('/crm/public/login');
        $user = $this->service->profile($id);
        return $this->view('profile/index', ['pageTitle' => 'My Profile', 'pageDescription' => 'Manage your account details and security.', 'user' => $user, 'csrf' => Csrf::token(), 'message' => Session::pull('profile_message'), 'error' => Session::pull('profile_error')]);
    }

    public function email(): Response
    {
        Csrf::verify((string) ($_POST['_csrf'] ?? ''));
        $id = Auth::id() ?? 0;
        try { $this->service->updateEmail($id, (string) ($_POST['email'] ?? ''), (string) ($_POST['current_password'] ?? '')); Session::put('profile_message', 'Email address updated successfully.'); }
        catch (InvalidArgumentException $e) { Session::put('profile_error', $e->getMessage()); }
        return Response::redirect('/crm/public/profile');
    }

    public function password(): Response
    {
        Csrf::verify((string) ($_POST['_csrf'] ?? ''));
        $id = Auth::id() ?? 0;
        try { $this->service->updatePassword($id, (string) ($_POST['current_password'] ?? ''), (string) ($_POST['new_password'] ?? ''), (string) ($_POST['password_confirmation'] ?? '')); Session::put('profile_message', 'Password changed successfully.'); }
        catch (InvalidArgumentException $e) { Session::put('profile_error', $e->getMessage()); }
        return Response::redirect('/crm/public/profile');
    }
}
