<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\Controller;

class Auth extends Controller
{
    public function __construct()
    {
        helper(['form', 'url']);
        $this->userModel = new UserModel();
        $this->session = session();
    }

    // === Login Page ===
    public function login()
    {
        return view('auth/login');
    }

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

    // === Proses Login ===
    public function doLogin()
    {
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $user = $this->userModel->getByEmail($email);

        if ($user && password_verify($password, $user['password'])) {
            $this->session->set([
                'user_id' => $user['id'],
                'user_name' => $user['nama'],
                'user_email' => $user['email'],
                'user_role' => $user['role'],
                'logged_in' => true
            ]);
            return redirect()->to('/');
        } else {
            return redirect()->back()->with('error', 'Email atau password salah!');
        }
    }

    // === Proses Register ===
    public function doRegister()
    {
        $data = [
            'nama' => $this->request->getPost('nama'),
            'email' => $this->request->getPost('email'),
            'role' => 'user', // default
            'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT)
        ];

        // Cek duplikasi email
        if ($this->userModel->getByEmail($data['email'])) {
            return redirect()->back()->with('error', 'Email sudah terdaftar!');
        }

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

    // === Logout ===
    public function logout()
    {
        $this->session->destroy();
        return redirect()->to('/login');
    }
}
