<?php
namespace App\Controllers;

use App\Services\AuthService;
use App\Utils\Sanitizer;

class AuthController extends ApiController
{
    private $authService;

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

    public function login()
    {
        try {
            // Support both 'email' and 'username' fields (login form uses 'username' which is actually display_name)
            $email = Sanitizer::sanitize($_POST['email'] ?? $_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            
            if (empty($email) || empty($password)) {
                $this->errorResponse('نام کاربری و رمز عبور الزامی است');
            }
            
            $result = $this->authService->login($email, $password);
            
            if ($result['success']) {
                // Set name in session for display
                $_SESSION['name'] = $result['user']['display_name'] ?? ($result['user']['first_name'] . ' ' . $result['user']['last_name']);
                $this->successResponse(['user' => $result['user']], 'ورود موفقیت‌آمیز بود');
            } else {
                $this->errorResponse($result['message']);
            }
        } catch (\Exception $e) {
            \App\Utils\Logger::logError("Login error", $e, [
                'email' => $_POST['email'] ?? $_POST['username'] ?? '',
                'post_data' => $_POST
            ]);
            $this->errorResponse('خطا در ورود: ' . $e->getMessage());
        }
    }

    public function logout()
    {
        $this->authService->logout();
        $this->successResponse([], 'خروج موفقیت‌آمیز بود');
    }
}

