<?php

namespace App\Repositories;

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

class AreaGroupTypeRepository
{
    public function findByAreaAndGroupType($area_id, $group_type_id)
    {
        $db = Database::getConnection();
        $query = "SELECT * FROM area_group_types WHERE area_id = :area_id AND group_type_id = :group_type_id LIMIT 1";
        $stmt = $db->prepare($query);
        $stmt->execute([
            ':area_id' => $area_id,
            ':group_type_id' => $group_type_id
        ]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($result) {
            $areaGroupType = new AreaGroupType();
            $areaGroupType->id = $result['id'];
            $areaGroupType->area_id = $result['area_id'];
            $areaGroupType->group_type_id = $result['group_type_id'];
            $areaGroupType->active = $result['active'];
            $areaGroupType->deleted_at = $result['deleted_at'];
            return $areaGroupType;
        }

        return null;
    }

    public function exists($area_id, $group_type_id)
    {
        $db = Database::getConnection();
        $query = "SELECT COUNT(*) FROM area_group_types WHERE area_id = :area_id AND group_type_id = :group_type_id";
        $stmt = $db->prepare($query);
        $stmt->execute([
            ':area_id' => $area_id,
            ':group_type_id' => $group_type_id
        ]);
        return $stmt->fetchColumn() > 0;
    }

    public function assign($area_id, $group_type_id)
    {
        $db = Database::getConnection();
        $query = "INSERT INTO area_group_types (area_id, group_type_id) VALUES (:area_id, :group_type_id)";
        $stmt = $db->prepare($query);
        return $stmt->execute([
            ':area_id' => $area_id,
            ':group_type_id' => $group_type_id
        ]);
    }

    public function hasGroups($area_group_type_id)
    {
        $db = Database::getConnection();
        $query = "SELECT COUNT(*) FROM `groups` WHERE area_group_type_id = :area_group_type_id AND deleted_at IS NULL";
        $stmt = $db->prepare($query);
        $stmt->execute([':area_group_type_id' => $area_group_type_id]);
        return $stmt->fetchColumn() > 0;
    }
}