<?php

namespace App\Models;

use Config\Database;
use Exception;
use PDO;

class Subgroup extends BaseModel
{
    protected static $table = 'subgroups';

    public $id;
    public $group_id;
    public $abbreviation;
    public $description;
    public $active;
    public $deleted_at;

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

    public function save()
    {
        try {
            $db = Database::getConnection();
            if ($this->id) {
                $query = "UPDATE `subgroups` SET group_id = :group_id, abbreviation = :abbreviation, description = :description, active = :active WHERE id = :id";
                $stmt = $db->prepare($query);
                $stmt->execute([
                    ':id' => $this->id,
                    ':group_id' => $this->group_id,
                    ':abbreviation' => $this->abbreviation,
                    ':description' => $this->description,
                    ':active' => $this->active
                ]);
            } else {
                $query = "INSERT INTO `subgroups` (group_id, abbreviation, description, active) VALUES (:group_id, :abbreviation, :description, :active)";
                $stmt = $db->prepare($query);
                $stmt->execute([
                    ':group_id' => $this->group_id,
                    ':abbreviation' => $this->abbreviation,
                    ':description' => $this->description,
                    ':active' => $this->active
                ]);
                $this->id = $db->lastInsertId();
            }
        } catch (Exception $e) {
            $area = $this->getArea();
            $_SESSION['message'] = "Error: " . $e->getMessage();
            $_SESSION['message_type'] = "danger";
            header("Location: /areas/$area->id/show-groups");
            exit;
        }
    }

    public function getGroup()
    {
        return Group::find($this->group_id);
    }

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

}
