<?php

namespace App\Controllers;

use App\Models\PenggunaModel;
use CodeIgniter\RESTful\ResourceController;

class Auth extends ResourceController
{
    protected $format = 'json';

    public function login()
    {
        $model = new PenggunaModel();
        
        // Mengambil data JSON dari Flutter
        $json = $this->request->getJSON();
        
        if (!$json) {
            return $this->fail('Data tidak ditemukan', 400);
        }

        $username = $json->username;
        $password = $json->password;

        // Cari user berdasarkan username
        $user = $model->where('username', $username)->first();

        if ($user) {
            // Cek password (masih plain text sesuai data dummy '123')
            if ($password === $user['password']) {
                $response = [
                    'status'   => 200,
                    'error'    => null,
                    'messages' => [
                        'success' => 'Login Berhasil'
                    ],
                    'data' => [
                        'id_pengguna'  => $user['id_pengguna'],
                        'nama_lengkap' => $user['nama_lengkap'],
                        'username'     => $user['username'],
                        'peran'        => $user['peran']
                    ]
                ];
                return $this->respond($response);
            } else {
                return $this->fail('Password salah', 401);
            }
        } else {
            return $this->fail('Username tidak ditemukan', 404);
        }
    }
}