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

class Forgot_password extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('user/User_model');
        $this->load->library('session');
        $this->load->helper(array('url', 'form', 'security'));
    }
    
    /**
     * Halaman form lupa password
     */
    public function forgot_password() {
        if ($this->session->userdata('user_logged_in')) {
            redirect('user/dashboard');
        }
        
        $data['title'] = 'Lupa Password';
        $this->load->view('user/forgot_password', $data);
    }
    
    /**
     * Proses permintaan reset password
     */
    public function process_forgot_password() {
        $this->load->library('form_validation');
        
        // Validasi input
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('user/forgot_password');
        }
        
        $email = $this->input->post('email', TRUE);
        
        // Cek apakah email terdaftar
        if (!$this->User_model->email_exists($email)) {
            $this->session->set_flashdata('error', 'Email tidak terdaftar dalam sistem.');
            redirect('user/forgot_password');
        }
        
        // Generate OTP (6 digit angka)
        $otp = mt_rand(100000, 999999);
        
        // Simpan OTP ke database dengan expiry 10 menit
        $expiry = date('Y-m-d H:i:s', strtotime('+10 minutes'));
        
        $this->db->where('email', $email);
        $this->db->update('penghuni', [
            'reset_token' => $otp,
            'reset_token_expiry' => $expiry
        ]);
        
        // SKIP EMAIL UNTUK DEVELOPMENT
        $this->session->set_userdata('reset_email', $email);
        $this->session->set_flashdata('success', 'Kode OTP: <strong>' . $otp . '</strong> (Simpan untuk verifikasi)');
        redirect('user/reset_password/verify');
    }
    
    /**
     * Halaman verifikasi OTP
     */
    public function verify() {
        if (!$this->session->userdata('reset_email')) {
            redirect('user/forgot_password');
        }
        
        $data['email'] = $this->session->userdata('reset_email');
        $data['title'] = 'Verifikasi OTP';
        $this->load->view('user/verify_otp', $data);
    }
    
    /**
     * Proses verifikasi OTP
     */
    public function verify_otp() {
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('otp', 'Kode OTP', 'required|exact_length[6]|numeric');
        
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('user/reset_password/verify');
        }
        
        $otp = $this->input->post('otp', TRUE);
        $email = $this->session->userdata('reset_email');
        
        // Validasi OTP
        $this->db->where('email', $email);
        $this->db->where('reset_token', $otp);
        $this->db->where('reset_token_expiry >=', date('Y-m-d H:i:s'));
        $query = $this->db->get('penghuni');
        
        if ($query->num_rows() > 0) {
            redirect('user/reset_password');
        } else {
            $this->session->set_flashdata('error', 'Kode OTP tidak valid atau sudah kadaluarsa.');
            redirect('user/reset_password/verify');
        }
    }
    
    /**
     * Halaman reset password - DIPERBAIKI
     */
    public function reset_password() {
        if (!$this->session->userdata('reset_email')) {
            redirect('user/forgot_password');
        }
        
        $email = $this->session->userdata('reset_email');
        $user = $this->User_model->get_by_email($email);
        
        $data = [
            'title' => 'Reset Password',
            'user' => $user
        ];
        
        $this->load->view('user/reset_password', $data);
    }
    
    /**
     * Proses reset password baru
     */
    public function process_reset_password() {
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('password', 'Password Baru', 'required|min_length[6]');
        $this->form_validation->set_rules('confirm_password', 'Konfirmasi Password', 'required|matches[password]');
        
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('user/reset_password');
        }
        
        $email = $this->session->userdata('reset_email');
        $password = $this->input->post('password', TRUE);
        
        // Hash password baru
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        // Update password dan clear token
        $this->db->where('email', $email);
        $success = $this->db->update('penghuni', [
            'password' => $hashed_password,
            'reset_token' => NULL,
            'reset_token_expiry' => NULL
        ]);
        
        if ($success) {
            $this->session->unset_userdata('reset_email');
            $this->session->set_flashdata('success', 'Password berhasil direset. Silakan login dengan password baru.');
            redirect('user/login');
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset password. Silakan coba lagi.');
            redirect('user/reset_password');
        }
    }
    
    /**
     * Resend OTP
     */
    public function resend_otp() {
        $email = $this->session->userdata('reset_email');
        
        if (!$email) {
            redirect('user/forgot_password');
        }
        
        // Generate OTP baru
        $otp = mt_rand(100000, 999999);
        $expiry = date('Y-m-d H:i:s', strtotime('+10 minutes'));
        
        $this->db->where('email', $email);
        $this->db->update('penghuni', [
            'reset_token' => $otp,
            'reset_token_expiry' => $expiry
        ]);
        
        $this->session->set_flashdata('success', 'OTP baru: ' . $otp);
        redirect('user/reset_password/verify');
    }
}