<?php

namespace App\Models;

use Core\Model;

class User extends Model
{
    protected $table = 'tb_user'; // nama tabel login

    /**
     * Ambil semua data user
     */
    public function all()
    {
        return $this->query("SELECT * FROM {$this->table}")->fetchAll();
    }

    /**
     * Cari user berdasarkan ID
     */
    public function find($id)
    {
        $stmt = $this->query("SELECT * FROM {$this->table} WHERE id_user = ?", [$id]);
        return $stmt->fetch();
    }

    /**
     * Cari user berdasarkan username (untuk login)
     */
    public function findByUsername($username)
    {
        $stmt = $this->query("SELECT * FROM {$this->table} WHERE username = ?", [$username]);
        return $stmt->fetch();
    }

    /**
     * Tambah user baru
     */
    public function create($data)
    {
        $sql = "INSERT INTO {$this->table} (nama, username, password, level) VALUES (?, ?, ?, ?)";
        return $this->query($sql, [
            $data['nama'],
            $data['username'],
            md5($data['password']), // atau password_hash jika tidak pakai md5
            $data['level']
        ]);
    }

    /**
     * Update data user
     */
    public function update($id, $data)
    {
        $sql = "UPDATE {$this->table} SET nama = ?, username = ?, level = ? WHERE id_user = ?";
        return $this->query($sql, [
            $data['nama'],
            $data['username'],
            $data['level'],
            $id
        ]);
    }

    /**
     * Hapus user
     */
    public function delete($id)
    {
        return $this->query("DELETE FROM {$this->table} WHERE id_user = ?", [$id]);
    }
}
