<?php

namespace App\Repositories;

use App\Models\PersonType;
use Config\Database;
use PDO;

class PersonTypeRepository
{
    public function findByDescription($description)
    {
        $db = Database::getConnection();
        $query = "SELECT * FROM person_types WHERE description = :description LIMIT 1";
        $stmt = $db->prepare($query);
        $stmt->execute([':description' => $description]);
        
        $personType = $stmt->fetch();
        return $personType ? new PersonType($personType) : null;
    }

    public function getByUserId($userId)
    {
        $db = Database::getConnection();

        $stmt = $db->prepare("SELECT id FROM comunity_users WHERE user_id = ?");
        $stmt->execute([$userId]);
        $comunityUser = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$comunityUser) {
            return [];
        }

        $stmt = $db->prepare("
            SELECT pt.* 
            FROM person_types pt
            INNER JOIN users_person_types upt ON pt.id = upt.person_type_id
            WHERE upt.comunity_user_id = ?
        ");
        $stmt->execute([$comunityUser['id']]);

        $personTypes = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $personType = new PersonType();
            foreach ($row as $key => $value) {
                $personType->$key = $value;
            }
            $personTypes[] = $personType;
        }

        return $personTypes;
    }
}