<?php

namespace App\Models;

use PDO;
use Config\Database;

class Area extends BaseModel
{
    protected static $table = 'areas';

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

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

    public function save()
    {
        $db = Database::getConnection();
        if ($this->id) {
            $query = "UPDATE areas 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 areas (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 getGroupTypes()
    {
        $db = Database::getConnection();
        $query = "SELECT gt.* FROM group_types gt 
                  INNER JOIN area_group_types agt ON gt.id = agt.group_type_id
                  WHERE agt.area_id = :area_id AND agt.deleted_at IS NULL";
        $stmt = $db->prepare($query);
        $stmt->execute([':area_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.area_id = :area_id";
        $stmt = $db->prepare($query);
        $stmt->execute([':area_id' => $this->id]);

        $groups = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $group = new Group();
            foreach ($row as $key => $value) {
                $group->$key = $value;
            }
            $groups[] = $group;
        }

        return $groups;
    }
}
