<?php

namespace App\Models;

use PDO;
use Config\Database;

class ProcedureRoute extends BaseModel
{
    protected static $table = 'procedure_routes';

    public $id;
    public $procedure_id;
    public $group_id;
    public $subgroup_id;
    public $previous_step_id;
    public $next_step_id;
    public $created_at;
    public $active;
    public $deleted_at;

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

    public function save()
    {
        $db = Database::getConnection();

        if ($this->id) {
            $query = "UPDATE procedure_routes 
                    SET procedure_id = :procedure_id, 
                        group_id = :group_id, 
                        subgroup_id = :subgroup_id, 
                        previous_step_id = :previous_step_id, 
                        next_step_id = :next_step_id, active = :active 
                    WHERE id = :id";

            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':procedure_id' => $this->procedure_id,
                ':group_id' => $this->group_id,
                ':subgroup_id' => $this->subgroup_id,
                ':previous_step_id' => $this->previous_step_id,
                ':next_step_id' => $this->next_step_id,
                ':active' => $this->active,
            ]);
        } else {
            $query = "INSERT INTO procedure_routes 
                    (procedure_id, group_id, subgroup_id, previous_step_id, next_step_id, created_at, active) 
                    VALUES (:procedure_id, :group_id, :subgroup_id, :previous_step_id, :next_step_id, NOW(), :active)";

            $stmt = $db->prepare($query);
            $stmt->execute([
                ':procedure_id' => $this->procedure_id,
                ':group_id' => $this->group_id,
                ':subgroup_id' => $this->subgroup_id,
                ':previous_step_id' => $this->previous_step_id,
                ':next_step_id' => $this->next_step_id,
                ':active' => $this->active,
            ]);

            $this->id = $db->lastInsertId();
        }
    }

    public function procedure()
    {
        return Procedure::find($this->procedure_id);
    }

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

    public function subgroup()
    {
        return Subgroup::find($this->subgroup_id);
    }

    public function areaGroupType()
    {
        $group = $this->group();
        return $group ? AreaGroupType::find($group->area_group_type_id) : null;
    }

    public function area()
    {
        $areaGroupType = $this->areaGroupType();
        return $areaGroupType ? Area::find($areaGroupType->area_id) : null;
    }

    public function groupType()
    {
        $areaGroupType = $this->areaGroupType();
        return $areaGroupType ? GroupType::find($areaGroupType->group_type_id) : null;
    }

}