<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class Auth extends BaseController
{
    public function index()
    {
        return view('auth/login');
    }

    public function login()
    {
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        $userModel = new UserModel();

        $user = $userModel
            ->where('username', $username)
            ->first();

        if (!$user) {
            return redirect()->back()->with('error', 'Username tidak ditemukan.');
        }

        if (!password_verify($password, $user['password'])) {
            return redirect()->back()->with('error', 'Password salah.');
        }

        session()->set([
            'id_user'   => $user['id'],
            'username'  => $user['username'],
            'nama'      => $user['nama'],
            'role'      => $user['role'] ?? 'petugas',
            'isLoggedIn'=> true,
        ]);

        // Redirect sesuai role
        if (($user['role'] ?? 'petugas') === 'petugas') {
            return redirect()->to('/dashboard');
        }

        return redirect()->to('/katalog');
    }

    public function register()
    {
        return view('auth/register');
    }

    public function storeRegister()
    {
        $nama     = $this->request->getPost('nama');
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');
        $role     = $this->request->getPost('role');

        // Hanya izinkan guru & siswa registrasi sendiri
        if (!in_array($role, ['guru', 'siswa'])) {
            return redirect()->back()->with('error', 'Jenis pendaftaran tidak valid.');
        }

        $userModel = new UserModel();

        // Cek username sudah dipakai
        $existing = $userModel
            ->where('username', $username)
            ->first();

        if ($existing) {
            return redirect()->back()->with('error', 'Username sudah digunakan. Silakan gunakan username lain.');
        }

        if (strlen($password) < 6) {
            return redirect()->back()->with('error', 'Password minimal 6 karakter.');
        }

$data = [
            'nama'      => $nama,
            'username'  => $username,
            'password'  => password_hash($password, PASSWORD_DEFAULT),
        ];

        // Coba simpan role. Jika kolom role belum ada di database (migrasi belum
        // dijalankan), simpan tanpa role agar tidak error saat registrasi.
        try {
            $data['role'] = $role;
            $userModel->save($data);
        } catch (\Exception $e) {
            unset($data['role']);
            $userModel->save($data);
        }

        return redirect()->to('/login')->with('success', 'Registrasi berhasil! Silakan login.');
    }

    public function logout()
    {
        session()->destroy();

        return redirect()->to('/login');
    }
}
