<?php

namespace App\Models;

use PDO;
use Config\Database;

class User extends BaseModel
{
    protected static $table = 'users';

    public $id;
    public $username;
    public $password;
    public $role;
    public $active;
    public $deleted_at;
    public $profile_picture;

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

        if (!empty($data['password']) && empty($data['id'])) {
            $this->password = password_hash($data['password'], PASSWORD_BCRYPT);
        }
    }

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

        if (isset($this->id)) {
            $query = "UPDATE users SET username = :username, password = :password, role = :role, active = :active, profile_picture = :profile_picture WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':id', $this->id);
        } else {
            $query = "INSERT INTO users (username, password, role, active, profile_picture) VALUES (:username, :password, :role, :active, :profile_picture)";
            $stmt = $db->prepare($query);
        }

        $stmt->bindParam(':username', $this->username);
        $stmt->bindParam(':password', $this->password);
        $stmt->bindParam(':role', $this->role);
        $stmt->bindParam(':active', $this->active, PDO::PARAM_INT);
        $stmt->bindParam(':profile_picture', $this->profile_picture);

        if ($stmt->execute()) {
            if (!isset($this->id)) {
                $this->id = $db->lastInsertId();
            }
            return $this->id;
        }
        return false;
    }
}
