<?php

namespace App\Models;

use PDO;
use Config\Database;

class PersonType extends BaseModel
{
    protected static $table = 'person_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 person_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 person_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();
        }
    }

}