<?php

namespace App\Models;

use Config\Database;
use Exception;
use PDO;

class Group extends BaseModel
{
    protected static $table = 'groups';

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

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

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

    public function getAreaGroupType()
    {
        return AreaGroupType::find($this->area_group_type_id);
    }
}
