<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\AuthModel;

class Auth extends Controller
{
    public function login()
    {
        // Tampilkan form login
        return view('templates/login');
    }
    public function register()
    {
        // Tampilkan form pendaftaran
        return view('register');
    }
    public function processLogin()
    {
        // Ambil input dari form login
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('userPassword');

        // Validasi input (bisa ditambahkan)
        
        // Cek autentikasi
        $authModel = new AuthModel();
        $user = $authModel->authenticate($username, $password);

        if ($user) {
            // Autentikasi berhasil, simpan sesi pengguna

            session()->set('user_id', $user['id']);
            session()->set('user_username', $user['username']);

        
            // Redirect ke halaman setelah login
            return redirect()->to('/');
        } else {
            return $this->response->setJSON('error', 'username atau kata sandi salah.');
            
        }
    }

    public function logout()
    {
        // Hapus sesi pengguna
        session()->remove('user_id');
        session()->remove('user_username');

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