<?php

namespace App\Models;

use Config\Database;
use PDO;

class UserPersonType extends BaseModel
{
    protected static $table = 'users_person_types';

    public $id;
    public $comunity_user_id;
    public $person_type_id;
    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 users_person_types SET 
                        comunity_user_id = :comunity_user_id, 
                        person_type_id = :person_type_id, 
                        active = :active, 
                        deleted_at = :deleted_at 
                    WHERE id = :id";

            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':comunity_user_id' => $this->comunity_user_id,
                ':person_type_id' => $this->person_type_id,
                ':active' => $this->active,
                ':deleted_at' => $this->deleted_at
            ]);

            return $this->id;
        } else {
            $query = "INSERT INTO users_person_types 
                        (comunity_user_id, person_type_id, active, deleted_at) 
                    VALUES 
                        (:comunity_user_id, :person_type_id, :active, :deleted_at)";

            $stmt = $db->prepare($query);
            $stmt->execute([
                ':comunity_user_id' => $this->comunity_user_id,
                ':person_type_id' => $this->person_type_id,
                ':active' => $this->active,
                ':deleted_at' => $this->deleted_at
            ]);

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