<?php

namespace App\Controllers\Api;

use App\Models\RuanganModel;
use App\Models\LogAktivitasModel;

class RuanganController extends BaseApiController
{
    protected $ruangan;
    protected $log;

    public function __construct()
    {
        $this->ruangan = new RuanganModel();
        $this->log     = new LogAktivitasModel();
    }

    // ======================
    // GET /ruangan
    // ======================
    public function index()
    {
        return $this->respondSuccess(
            $this->ruangan->orderBy('nama_ruangan', 'ASC')->findAll(),
            'Data ruangan'
        );
    }

    // ======================
    // POST /ruangan
    // ======================
    public function store()
    {
        $data = $this->request->getJSON(true);

        if (empty($data['nama_ruangan'])) {
            return $this->respondError('Nama ruangan wajib diisi', 422);
        }

        $this->ruangan->insert([
            'nama_ruangan'      => $data['nama_ruangan'],
            'penanggung_jawab'  => $data['penanggung_jawab'] ?? null
        ]);

        $this->logAktivitas("Menambahkan ruangan: {$data['nama_ruangan']}");

        return $this->respondSuccess(null, 'Ruangan berhasil ditambahkan');
    }

    // ======================
    // PUT /ruangan/{id}
    // ======================
    public function update($id)
    {
        $data = $this->request->getJSON(true);

        if (!$this->ruangan->find($id)) {
            return $this->respondError('Ruangan tidak ditemukan', 404);
        }

        $this->ruangan->update($id, [
            'nama_ruangan'     => $data['nama_ruangan'] ?? null,
            'penanggung_jawab' => $data['penanggung_jawab'] ?? null
        ]);

        $this->logAktivitas("Mengubah ruangan ID {$id}");

        return $this->respondSuccess(null, 'Ruangan berhasil diperbarui');
    }

    // ======================
    // HELPER LOG
    // ======================
    protected function logAktivitas($aktivitas)
    {
        /** @var object $this->request->user */

        $this->log->insert([
            'id_user' => $this->request->user->id_user,
            'aktivitas' => $aktivitas,
            'waktu' => date('Y-m-d H:i:s')
        ]);
    }
}