<?php

namespace App\Controllers;

use App\Models\User_model;

class Auth extends BaseController
{
    public function login()
    {
        $data = [
            'setting' => $this->appSetting(),
            'title' => 'Login Page'
        ];
        return view('Admin/Auth/login', $data);
    }
    public function dologin()
    {
        // Validasi input
        $rules = [
            'username' => 'required',
            'password' => 'required'
        ];

        if (!$this->validate($rules)) {
            // Jika validasi gagal, kembalikan pesan kesalahan validasi
            $errors = $this->validator->getErrors();
            return json_encode(['success' => false, 'message' => $errors]);
        } else {
            // Jika validasi berhasil, lakukan proses autentikasi
            $username = $this->request->getPost('username');
            $password = $this->request->getPost('password') ?? "";

            // Ambil data pengguna dari database berdasarkan username
            $userModel = new User_model();
            $user = $userModel->where('username', $username)->first();

            if ($user) {
                // Verifikasi password
                if (password_verify($password, $user['password'])) {
                    // Autentikasi berhasil
                    $session = session();
                    $sessionData = [
                        'user_id' => $user['id'],
                        'username' => $user['username'],
                        'nama' => $user['nama'],
                        'role' => $user['role'],
                        // Tambahkan data lain yang perlu disimpan di sesi
                    ];
                    $session->set($sessionData);
                    $this->addLogs('Berhasil login aplikasi');
                    return $this->response->setJSON(['success' => true, 'message' => 'Login successful.']);
                } else {
                    // Autentikasi gagal, password tidak cocok
                    return $this->response->setJSON(['success' => false, 'message' => 'Invalid password']);
                }
            } else {
                // Autentikasi gagal, pengguna tidak ditemukan
                return $this->response->setJSON(['success' => false, 'message' => 'User not found']);
            }
        }
    }

    public function register(): string
    {

        return view('Admin/Auth/register');
    }
    public function logout()
    {
        $session = session();
        $session->destroy();
        return redirect()->to('auth/login');
    }
}
