<?php

namespace App\Models;

use Config\Database;

class RoleUser extends BaseModel
{
    protected static $table = 'role_user';

    public $id;
    public $user_id;
    public $role_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 role_user 
                    SET user_id = :user_id, 
                        role_id = :role_id, 
                        active = :active
                    WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':user_id' => $this->user_id,
                ':role_id' => $this->role_id,
                ':active' => $this->active
            ]);
        } else {
            $query = "INSERT INTO role_user (user_id, role_id, active)
                    VALUES (:user_id, :role_id, :active)";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':user_id' => $this->user_id,
                ':role_id' => $this->role_id,
                ':active' => $this->active
            ]);
            $this->id = $db->lastInsertId();
        }
    }
}
