<?php

namespace App\Models;

use PDO;
use Config\Database;

class ResponseType extends BaseModel
{
    protected static $table = 'response_types';

    public $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()
    {
        $db = Database::getConnection();
        if ($this->id) {
            $query = "UPDATE response_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 response_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 static function getIdByName($description) {
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT id FROM response_types WHERE description = :description");
        $stmt->bindParam(':description', $description, PDO::PARAM_STR);
        $stmt->execute();
        return $stmt->fetchColumn();
    }
}