<?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')->with('login_success', 'Selamat datang kembali, <b>' . $user['nama_lengkap'] . '</b>!');
        }
        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')->with('login_success', 'Selamat datang kembali, <b>' . $user['nama_lengkap'] . '</b>!');
            } 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.";
        }
    }
    
    // Halaman Form Minta Reset (Input Surel)
    public function lupa_password()
    {
        return view('auth/lupa_password');
    }

    // Memproses Validasi Surel & Membuat Token Simulasi
    public function kirim_token_simulasi()
    {
        $userM = new \App\Models\UserModel();
        $surel = $this->request->getPost('surel');

        // Cari user berdasarkan surel yang diinput
        $user = $userM->where('surel', $surel)->first();

        if (!$user) {
            return redirect()->to('/auth/lupa_password')->with('error', 'Alamat surel tidak ditemukan dalam sistem!');
        }

        // Generate Token Acak Unik & Atur Kedaluwarsa (30 Menit)
        $token = bin2hex(random_bytes(16));
        $expiry = date('Y-m-d H:i:s', strtotime('+30 minutes'));

        // Simpan token ke database
        $userM->update($user['id_user'], [
            'reset_token'  => $token,
            'token_expiry' => $expiry
        ]);

        // Buat Link Reset Kombinasi Token
        $linkReset = base_url('auth/form_reset?token=' . $token);

        // Kunci Utama: Tampilkan link langsung di layar sebagai simulasi email
        return redirect()->to('/auth/lupa_password')->with('simulasi_email', $linkReset);
    }

    // Halaman Form Input Password Baru (Dipanggil dari Link Token)
    public function form_reset()
    {
        $userM = new \App\Models\UserModel();
        $token = $this->request->getGet('token');

        // Validasi ketersediaan token dan pastikan belum kedaluwarsa
        $user = $userM->where('reset_token', $token)
                      ->where('token_expiry >=', date('Y-m-d H:i:s'))
                      ->first();

        if (!$user) {
            return redirect()->to('/auth/lupa_password')->with('error', 'Tautan tidak valid atau sudah kedaluwarsa! Silakan minta tautan baru.');
        }

        $data = [
            'title' => 'Reset Password Akun',
            'token' => $token
        ];

        return view('auth/reset_password', $data);
    }

    // Memperbarui Password Lama dengan yang Baru
    public function proses_reset()
    {
        $userM = new \App\Models\UserModel();
        $token = $this->request->getPost('token');
        $passwordBaru = $this->request->getPost('password_baru');

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

        if (!$user) {
            return redirect()->to('/auth/lupa_password')->with('error', 'Gagal memproses reset. Token tidak dikenali.');
        }

        // Update password baru & bersihkan token agar tidak bisa dipakai ulang
        $userM->update($user['id_user'], [
            'password'     => password_hash($passwordBaru, PASSWORD_DEFAULT),
            'reset_token'  => null,
            'token_expiry' => null
        ]);

        return redirect()->to('/auth')->with('success', 'Password Anda <b>berhasil diperbarui</b>! Silakan login kembali.');
    }
    
}
