<?php

namespace App\Models;

use PDO;
use Config\Database;

class GroupType extends BaseModel
{
    protected static $table = 'group_types';

    public $id;
    public $abbreviation;
    public $description;
    public $active;
    public $deleted_at;
    public array $groups = [];

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->active = $data['active'] ?? 1;
    }

    public function save()
    {
        $db = Database::getConnection();
        if ($this->id) {
            $query = "UPDATE group_types SET abbreviation = :abbreviation, description = :description, active = :active WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':abbreviation' => $this->abbreviation,
                ':description' => $this->description,
                ':active' => $this->active
            ]);
        } else {
            $query = "INSERT INTO group_types (abbreviation, description, active) VALUES (:abbreviation, :description, :active)";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':abbreviation' => $this->abbreviation,
                ':description' => $this->description,
                ':active' => $this->active
            ]);
            $this->id = $db->lastInsertId();
        }
    }

    public function getAreas()
    {
        $db = Database::getConnection();
        $query = "SELECT a.* FROM areas a 
                  INNER JOIN area_group_types agt ON a.id = agt.area_id
                  WHERE agt.group_type_id = :group_type_id AND agt.deleted_at IS NULL";
        $stmt = $db->prepare($query);
        $stmt->execute([':group_type_id' => $this->id]);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    public function getGroups()
    {
        $db = Database::getConnection();
        $query = "SELECT g.* FROM groups g 
                  INNER JOIN area_group_types agt ON g.area_group_type_id = agt.id
                  WHERE agt.group_type_id = :group_type_id";
        $stmt = $db->prepare($query);
        $stmt->execute([':group_type_id' => $this->id]);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    public function getAreaGroupTypes()
    {
        $db = Database::getConnection();
        $query = "SELECT * FROM area_group_types WHERE group_type_id = :group_type_id AND deleted_at IS NULL";
        $stmt = $db->prepare($query);
        $stmt->execute([':group_type_id' => $this->id]);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }
}
