<?php

namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    public function index()
    {
        // Jika sudah login, tendang langsung ke dashboard
        if (session()->get('isLoggedIn')) {
            return redirect()->to('/dashboard');
        }
        return view('auth/login');
    }

    public function proses_login()
    {
        $userM = new UserModel();
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

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

        if ($user) {
            // Verifikasi password yang di-hash
            if (password_verify($password, $user['password'])) {
                // Set Session
                $sessData = [
                    'id_user'      => $user['id_user'],
                    'username'     => $user['username'],
                    'nama_lengkap' => $user['nama_lengkap'],
                    'role'         => $user['role'],
                    'isLoggedIn'   => true
                ];
                session()->set($sessData);
                return redirect()->to('/dashboard');
            } else {
                return redirect()->to('/auth')->with('error', 'Password yang Anda masukkan salah!');
            }
        } else {
            return redirect()->to('/auth')->with('error', 'Username tidak ditemukan!');
        }
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/auth');
    }

    // FUNGSI RAHASIA: Untuk membuat akun pertama kali
    // Akses URL ini sekali saja: http://localhost:8080/auth/setup_admin
    public function setup_admin()
    {
        $userM = new UserModel();
        // Cek apakah admin sudah ada
        if ($userM->countAll() == 0) {
            $userM->insert([
                'username'     => 'admin',
                'password'     => password_hash('admin123', PASSWORD_DEFAULT),
                'nama_lengkap' => 'Administrator Sari Rasa',
                'role'         => 'admin'
            ]);
            echo "Akun berhasil dibuat! <br> Username: <b>admin</b> <br> Password: <b>admin123</b> <br> <a href='" . base_url('auth') . "'>Login Sekarang</a>";
        } else {
            echo "Akun admin sudah ada di database. Silakan langsung login.";
        }
    }

    // Fungsi untuk Registrasi User Baru (Eksekusi via Postman: POST)
    public function register()
    {
        $userM = new UserModel();

        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');
        $nama     = $this->request->getPost('nama_lengkap');
        $role     = $this->request->getPost('role');

        // Validasi sederhana
        if (!$username || !$password) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Username dan Password wajib diisi']);
        }

        $data = [
            'username'     => $username,
            'password'     => password_hash($password, PASSWORD_DEFAULT),
            'nama_lengkap' => $nama ?? 'User Baru',
            'role'         => $role ?? 'pengurus'
        ];

        if ($userM->insert($data)) {
            return $this->response->setJSON(['status' => 'success', 'message' => 'User berhasil didaftarkan']);
        } else {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Gagal mendaftarkan user']);
        }
    }

    // Fungsi "Pintu Belakang" untuk reset password admin yang lupa (Eksekusi via GET/Postman)
    // URL: http://localhost:8080/auth/reset_admin?pass=passwordbaru
    public function reset_admin()
    {
        $userM = new UserModel();
        $newPass = $this->request->getGet('pass');

        if (!$newPass) return "Tambahkan parameter ?pass=... di URL";

        $admin = $userM->where('username', 'admin')->first();

        if ($admin) {
            $userM->update($admin['id_user'], [
                'password' => password_hash($newPass, PASSWORD_DEFAULT)
            ]);
            return "Password admin berhasil direset menjadi: " . $newPass;
        } else {
            return "User admin tidak ditemukan.";
        }
    }
}
