<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('User_model', 'user');
        $this->load->library(['session', 'form_validation']);
    }

    /* =========================
     * 🔐 LOGIN PAGE
     * ========================= */
    public function index()
    {
        // Kalau sudah login langsung redirect
        if ($this->session->userdata('logged_in')) {
            $role = $this->session->userdata('role');
            if (in_array($role, ['admin', 'inspector'])) redirect('admin');
            if ($role === 'user') redirect('form');
        }

        $data = [
            'title'   => 'Login - NOKA NOSIN',
            'content' => 'auth/login'
        ];
        $this->load->view('auth/template_auth', $data);
    }

    public function login_process()
    {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        $this->form_validation->set_rules('password', 'Password', 'required|trim');

        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors('<div>', '</div>'));
            redirect('auth');
            return;
        }

        $email    = trim($this->input->post('email', TRUE));
        $password = trim($this->input->post('password', TRUE));

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

        // 🧩 Validasi user
        if (!$user) {
            $this->session->set_flashdata('error', 'Email tidak ditemukan.');
            redirect('auth'); return;
        }
        if ((int)$user['status'] !== 1) {
            $this->session->set_flashdata('error', 'Akun Anda nonaktif. Hubungi admin.');
            redirect('auth'); return;
        }

        // 🧩 Validasi password (support plain & hash)
        $match = ($user['password'] === $password) || password_verify($password, $user['password']);
        if (!$match) {
            $this->session->set_flashdata('error', 'Password salah.');
            redirect('auth'); return;
        }

        // 🧩 Set session login
        $this->session->set_userdata([
            'user_id'   => $user['id'],
            'name'      => $user['name'],
            'email'     => $user['email'],
            'role'      => $user['role'],
            'logged_in' => TRUE
        ]);

        // 🧩 Redirect sesuai role
        switch ($user['role']) {
            case 'admin':
            case 'inspector':
                redirect('admin');
                break;
            case 'user':
                redirect('form');
                break;
            default:
                $this->session->set_flashdata('error', 'Akses ditolak! Role tidak dikenal.');
                redirect('auth');
                break;
        }
    }

    /* =========================
     * 🧾 REGISTER USER BARU
     * ========================= */
    public function register()
    {
        $data = [
            'title'   => 'Registrasi - NOKA NOSIN',
            'content' => 'auth/register'
        ];
        $this->load->view('auth/template_auth', $data);
    }

    public function register_process()
    {
        $this->form_validation->set_rules('name', 'Nama Lengkap', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]|trim');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|trim');

        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors('<div>', '</div>'));
            redirect('auth/register'); return;
        }

        $data = [
            'name'     => strtoupper($this->input->post('name', TRUE)),
            'email'    => strtolower($this->input->post('email', TRUE)),
            'password' => password_hash($this->input->post('password', TRUE), PASSWORD_DEFAULT),
            'role'     => 'user',
            'status'   => 1,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $this->user->register($data);

        $this->session->set_flashdata('success', 'Registrasi berhasil, silakan login.');
        redirect('auth');
    }

    /* =========================
     * 🔄 FORGOT PASSWORD (OTP)
     * ========================= */
    public function forgot_password()
    {
        $data = [
            'title'   => 'Lupa Password - NOKA NOSIN',
            'content' => 'auth/forgot_password'
        ];
        $this->load->view('auth/template_auth', $data);
    }

    public function forgot_process()
    {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors('<div>', '</div>'));
            redirect('auth/forgot_password'); return;
        }

        $email = trim($this->input->post('email', TRUE));
        $user  = $this->user->getByEmail($email);

        if (!$user) {
            $this->session->set_flashdata('error', 'Email tidak terdaftar.');
            redirect('auth/forgot_password'); return;
        }

        $otp = rand(100000, 999999);

        // hapus OTP lama
        $this->db->delete('password_resets', ['email' => $email]);

        // simpan OTP baru
        $this->db->insert('password_resets', [
            'email'      => $email,
            'otp'        => $otp,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        // kirim OTP via email
        $this->load->library('email');
        $this->email->from('noreply@noka-nosin.com', 'NOKA NOSIN');
        $this->email->to($email);
        $this->email->subject('Reset Password - NOKA NOSIN');
        $this->email->message("
            <p>Kode OTP reset password Anda:</p>
            <h2>{$otp}</h2>
            <p>Berlaku selama <b>5 menit</b> sejak dikirim.</p>
        ");

        if ($this->email->send()) {
            $this->session->set_flashdata('success', 'Kode OTP sudah dikirim ke email Anda.');
            redirect('auth/otp/'.urlencode($email));
        } else {
            $this->session->set_flashdata('error', 'Gagal mengirim OTP. Cek konfigurasi SMTP.');
            redirect('auth/forgot_password');
        }
    }

    public function otp($email)
    {
        $data = [
            'title'   => 'Verifikasi OTP - NOKA NOSIN',
            'email'   => urldecode($email),
            'content' => 'auth/verify_otp'
        ];
        $this->load->view('auth/template_auth', $data);
    }

    public function otp_process()
    {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        $this->form_validation->set_rules('otp', 'OTP', 'required|numeric|exact_length[6]|trim');
        $this->form_validation->set_rules('password', 'Password Baru', 'required|min_length[4]|trim');

        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors('<div>', '</div>'));
            redirect('auth/otp/'.$this->input->post('email', TRUE)); return;
        }

        $email    = trim($this->input->post('email', TRUE));
        $otp      = trim($this->input->post('otp', TRUE));
        $password = trim($this->input->post('password', TRUE));

        $reset = $this->db->get_where('password_resets', [
            'email' => $email,
            'otp'   => $otp
        ])->row_array();

        if (!$reset) {
            $this->session->set_flashdata('error', 'OTP tidak valid.');
            redirect('auth/otp/'.$email); return;
        }

        // Cek expiry (5 menit)
        if (time() - strtotime($reset['created_at']) > 300) {
            $this->db->delete('password_resets', ['email' => $email]);
            $this->session->set_flashdata('error', 'OTP kadaluarsa, silakan kirim ulang.');
            redirect('auth/forgot_password'); return;
        }

        // Update password
        $this->user->updatePassword($email, password_hash($password, PASSWORD_DEFAULT));

        // Hapus OTP biar one-time
        $this->db->delete('password_resets', ['email' => $email]);

        $this->session->set_flashdata('success', 'Password berhasil diperbarui, silakan login.');
        redirect('auth');
    }

   

/* =========================
     * 🚪 RESET PAssword
     * ========================= */
public function reset_process()
{
    $email = trim($this->input->post('email', TRUE));
    $password = trim($this->input->post('password', TRUE));

    $user = $this->user->getByEmail($email);
    if (!$user) {
        $this->session->set_flashdata('error', 'Email tidak ditemukan.');
        redirect('auth/reset_password'); return;
    }

    $this->user->updatePassword($email, password_hash($password, PASSWORD_DEFAULT));
    $this->session->set_flashdata('success', 'Password berhasil direset.');
    redirect('auth');
}


    /* =========================
     * 🚪 LOGOUT
     * ========================= */
    public function logout()
    {
        $this->session->sess_destroy();
        redirect('auth');
    }
}
