<?php

namespace App\Models;

use Core\Model;

class Mahasiswa extends Model
{
    protected $table = 'tb_mahasiswa';

    public function findByNim($nim)
    {
        $stmt = $this->query("SELECT * FROM {$this->table} WHERE nim = ?", [$nim]);
        return $stmt->fetch();
    }

    public function updateByNim($nim, $data)
    {
        if (empty($data)) {
            return false;
        }

        $fields = [];
        $values = [];

        foreach ($data as $key => $value) {
            $fields[] = "$key = ?";
            $values[] = $value;
        }

        $values[] = $nim;

        $sql = "UPDATE {$this->table} SET " . implode(', ', $fields) . " WHERE nim = ?";
        return $this->query($sql, $values);
    }

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

    public function findByUsername($username)
    {
        return $this->findByNim($username);
    }

    public function searchWilayah($keyword, $levelWil)
    {
        $sql = "SELECT k.id_wil, k.nm_wil AS kecamatan, kab.nm_wil AS kabupaten
                FROM tb_wilayah k
                JOIN tb_wilayah kab ON kab.id_wil = k.id_induk_wilayah
                WHERE k.id_level_wil = ?
                  AND k.nm_wil LIKE ?
                LIMIT 10";
        $stmt = $this->query($sql, [$levelWil, "%$keyword%"]);
        return $stmt->fetchAll();
    }

    public function findWilayahById($idWil)
    {
        $sql = "SELECT k.id_wil, k.nm_wil AS kecamatan, kab.nm_wil AS kabupaten
                FROM tb_wilayah k
                JOIN tb_wilayah kab ON kab.id_wil = k.id_induk_wilayah
                WHERE k.id_wil = ?";
        $stmt = $this->query($sql, [$idWil]);
        return $stmt->fetch();
    }

}
