<?php

namespace App\Modules\Auth\Services;

use App\Modules\Auth\Repositories\AuthRepository;
use DateTime;

class AuthService
{
    private AuthRepository $repository;

    public function __construct()
    {
        $this->repository = new AuthRepository();
    }

    public function register(array $data): array
    {
        if ($this->repository->findByEmail($data['email'])) {
            return [
                'success' => false,
                'message' => 'Email already exists.'
            ];
        }

        if (!$this->isAdult($data['date_of_birth'])) {
            return [
                'success' => false,
                'message' => 'You must be at least 18 years old to register.'
            ];
        }

        $role = $data['role'] === 'driver' ? 'driver' : 'passenger';

        $created = $this->repository->create([
            'name' => trim($data['name']),
            'gender' => $data['gender'],
            'date_of_birth' => $data['date_of_birth'],
            'email' => trim($data['email']),
            'phone' => trim($data['phone'] ?? ''),
            'password' => $data['password'],
            'role' => $role,
            'avatar' => $this->defaultAvatar($data['gender']),
            'verification_status' => $role === 'driver' ? 'pending' : 'verified',
            'verification_note' => $role === 'driver' ? 'Pending driver verification' : 'Verified passenger',
        ]);

        return [
            'success' => $created,
            'message' => $created ? 'Account created successfully.' : 'Something went wrong.'
        ];
    }


    public function login(string $email, string $password): bool
    {
        $user = $this->repository->findByEmail($email);

        if (!$user) {
            return false;
        }

        if (!password_verify($password, $user['password'])) {
            return false;
        }

        $_SESSION['user_id'] = $user['id'];

        return true;
    }
    private function isAdult(string $dateOfBirth): bool
    {
        $birthDate = new DateTime($dateOfBirth);
        $today = new DateTime();

        return $today->diff($birthDate)->y >= 18;
    }

    private function defaultAvatar(string $gender): string
    {
        return match ($gender) {
            'female' => 'https://i.pravatar.cc/150?img=47',
            'male' => 'https://i.pravatar.cc/150?img=52',
            default => 'https://i.pravatar.cc/150?img=10',
        };
    }
}