<?php

namespace App\Controllers;

use App\Models\ModelUser;
use App\Models\SettingsModel;

class Auth extends BaseController
{
    protected $modelUser;
    protected $session;

    public function __construct()
    {
        helper(['form']);
        $this->modelUser = new ModelUser();
        $this->session = session();
    }

    public function login()
    {
        // Jika sudah login, redirect ke dashboard
        if ($this->session->get('isLoggedIn')) {
            return redirect()->to(base_url('home'));
        }

        return view('auth/login');
    }
    public function signUp()
    {
        // Jika sudah login, redirect ke dashboard
        if ($this->session->get('isLoggedIn')) {
            return redirect()->to(base_url('home'));
        }

        return view('auth/sign_up');
    }

    public function tambahdata()
    {

        $validation = \Config\Services::validation();

        // Aturan Validasi
        $rules = [
            'firstname'         => 'required|min_length[3]',
            'nohape'            => [
                'rules'  => 'required|regex_match[/^08[0-9]{10}$/]|is_unique[users.nohape]',
                'errors' => [
                    'required'    => 'Nomor HP harus diisi.',
                    'regex_match' => 'Nomor HP harus diawali dengan 08 dan berjumlah 12 angka.',
                    'is_unique'   => 'Nomor HP sudah terdaftar, gunakan nomor lain.'
                ]
            ],
            'email'             => [
                'rules'  => 'required|valid_email|is_unique[users.email]',
                'errors' => [
                    'required'    => 'Email harus diisi.',
                    'valid_email' => 'Format email tidak valid.',
                    'is_unique'   => 'Email sudah digunakan, gunakan email lain.'
                ]
            ],
            'password'          => 'required|min_length[6]',
            'confirm_password'  => [
                'rules'  => 'required|matches[password]',
                'errors' => [
                    'required' => 'Konfirmasi password harus diisi.',
                    'matches'  => 'Konfirmasi password tidak sesuai dengan password.'
                ]
            ],
            'foto'              => 'mime_in[foto,image/jpg,image/jpeg,image/png]|max_size[foto,2048]'
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => $validation->getErrors()
            ]);
        }

        // Upload Foto
        $foto = $this->request->getFile('foto');
        $fotoName = null;
        if ($foto && $foto->isValid() && !$foto->hasMoved()) {
            $fotoName = $foto->getRandomName();
            $foto->move('public/assets/images/faces', $fotoName);
        }

        // Simpan Data ke Database
        $data = [
            'firstname'  => $this->request->getPost('firstname'),
            'nohape'     => $this->request->getPost('nohape'),
            'email'      => $this->request->getPost('email'),
            'password'   => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'level'      => 'operator',
            'foto'       => $fotoName,
            'status'     => 'nonaktif',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        if ($this->modelUser->insert($data)) {
            return $this->response->setJSON([
                'success' => true,
                'message' => 'Pendaftaran berhasil! Silakan Tunggu! Administrator sedang Memvalidasi.'
            ]);
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal menyimpan data.'
            ]);
        }
    }

    public function processLogin()
    {
        $rules = [
            'email'    => 'required|valid_email',
            'password' => 'required'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('validation', $this->validator);
        }

        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');

        // Cek user di tabel `users`
        $user = $this->modelUser->where('email', $email)->first();

        if (!$user) {
            return redirect()->back()->with('error', 'Email tidak ditemukan.');
        }

        if (!password_verify($password, $user['password'])) {
            return redirect()->back()->with('error', 'Password salah.');
        }

        // Set session
        $this->session->set([
            'id_user'    => $user['id_user'],
            'email'      => $user['email'],
            'nama'       => $user['nama'],
            'role'       => $user['role'],
            'isLoggedIn' => true
        ]);

        // Redirect langsung ke /home
        return redirect()->to(base_url('home'));
    }

    public function getSettingsNoLevel()
    {
        $settingsModel = new SettingsModel();
        $settings = $settingsModel->first(); // Ambil 1 data saja // Ambil satu record dari tabel settings

        if ($settings) {
            return $this->response->setJSON([
                'success' => true,
                'settings' => [
                    'nama_aplikasi' => $settings['nama_aplikasi'],
                    'logo' => base_url('/public/assets/images/faces') . '/' . $settings['logo']
                ]
            ]);
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Settings not found!'
            ]);
        }
    }

    public function logout()
    {

        session()->destroy();
        return redirect()->to(base_url('auth/login'))->with('success', 'Anda telah logout.');
    }
}
