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

class Password_reset extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        $this->load->model('Password_reset_model');
        $this->load->library('form_validation');
        $this->load->library('email');
        $this->load->library('session');
        $this->load->helper('string');
        $this->load->helper('url');
    }

    /**
     * Halaman form untuk meminta reset password
     */
    public function index() {
        $data['title'] = 'Reset Password';
        $this->load->view('auth/password_reset_request', $data);
    }

    /**
     * Proses permintaan reset password
     */
    public function request() {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        
        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('password-reset');
        }

        $email = $this->input->post('email');
        $user = $this->User_model->get_user_by_email($email);

        if (!$user) {
            $this->session->set_flashdata('error', 'Email tidak ditemukan dalam sistem.');
            redirect('password-reset');
        }

        // Generate token
        $token = bin2hex(random_bytes(32));
        $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));

        // Simpan token ke database
        $this->Password_reset_model->create_reset_token($email, $token, $expires_at);

        // Kirim email
        $this->send_reset_email($email, $token);

        $this->session->set_flashdata('success', 'Link reset password telah dikirim ke email Anda.');
        redirect('password-reset');
    }

    /**
     * Halaman form untuk password baru
     */
    public function reset($token = null) {
        if (!$token) {
            show_404();
        }

        $reset_data = $this->Password_reset_model->get_valid_token($token);
        
        if (!$reset_data) {
            $this->session->set_flashdata('error', 'Token reset password tidak valid atau sudah kadaluarsa.');
            redirect('password-reset');
        }

        $data['title'] = 'Password Baru';
        $data['token'] = $token;
        $this->load->view('auth/password_reset_form', $data);
    }

    /**
     * Proses update password baru
     */
    public function update() {
        $this->form_validation->set_rules('token', 'Token', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|matches[confirm_password]');
        $this->form_validation->set_rules('confirm_password', 'Konfirmasi Password', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('password-reset/reset/' . $this->input->post('token'));
        }

        $token = $this->input->post('token');
        $password = $this->input->post('password');

        $reset_data = $this->Password_reset_model->get_valid_token($token);
        
        if (!$reset_data) {
            $this->session->set_flashdata('error', 'Token reset password tidak valid atau sudah kadaluarsa.');
            redirect('password-reset');
        }

        // Update password
        $hashed_password = password_hash($password, PASSWORD_BCRYPT);
        $this->User_model->update_user_by_email($reset_data->email, ['password_hash' => $hashed_password]);

        // Tandai token sebagai sudah digunakan
        $this->Password_reset_model->mark_token_used($token);

        $this->session->set_flashdata('success', 'Password berhasil diubah. Silakan login dengan password baru Anda.');
        redirect('auth/login');
    }

    /**
     * Kirim email reset password
     */
    private function send_reset_email($email, $token) {
        $config = [
            'protocol' => 'smtp',
            'smtp_host' => 'smtp.gmail.com',
            'smtp_port' => 587,
            'smtp_user' => 'your-email@gmail.com', // Ganti dengan email Anda
            'smtp_pass' => 'your-app-password',    // Ganti dengan app password Anda
            'smtp_crypto' => 'tls',
            'mailtype' => 'html',
            'charset' => 'utf-8',
            'newline' => "\r\n"
        ];

        $this->email->initialize($config);

        $reset_link = site_url('password-reset/reset/' . $token);

        $message = "
            <h2>Reset Password</h2>
            <p>Anda telah meminta untuk reset password. Silakan klik link di bawah ini untuk mengatur ulang password Anda:</p>
            <p><a href='{$reset_link}' style='background-color: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Reset Password</a></p>
            <p>Link ini akan kadaluarsa dalam 1 jam.</p>
            <p>Jika Anda tidak meminta reset password, abaikan email ini.</p>
        ";

        $this->email->from($config['smtp_user'], 'Klimaks');
        $this->email->to($email);
        $this->email->subject('Reset Password - Klimaks');
        $this->email->message($message);

        return $this->email->send();
    }
}
