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

class Forgot_password extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin/Admin_model');
        $this->load->library('session');
        $this->load->helper(array('url', 'form', 'security'));
        $this->load->library('email');
        
        // Setup konfigurasi email
        $this->setup_email_config();
    }
    
    /**
     * Setup konfigurasi email
     */
    private function setup_email_config()
    {
        // Coba load dari config file
        if (file_exists(APPPATH . 'config/email.php')) {
            $this->load->config('email', TRUE);
            $config = $this->config->item('email');
        } else {
            // Konfigurasi default untuk Gmail
            $config = [
                'protocol' => 'smtp',
                'smtp_host' => 'ssl://smtp.gmail.com',
                'smtp_port' => 465,
                'smtp_user' => 'rizqywahyu59@gmail.com',
                'smtp_pass' => 'abcdefghijklmnop',
                'mailtype' => 'html',
                'charset' => 'utf-8',
                'newline' => "\r\n",
                'crlf' => "\r\n",
                'wordwrap' => TRUE,
                'smtp_timeout' => 30
            ];
        }
        
        $this->email->initialize($config);
    }

    /**
     * Halaman form lupa password
     */
    public function index()
    {
        // Jika sudah login, redirect ke dashboard
        if ($this->session->userdata('admin_logged_in')) {
            redirect('admin/dashboard');
        }

        $this->load->view('admin/forgot_password');
    }

    /**
     * Proses permintaan reset password
     */
    public function process_request()
    {
        $this->load->library('form_validation');
        
        // Validasi email
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', 'Email tidak valid.');
            redirect('admin/forgot_password');
        }

        $email = $this->input->post('email', true);
        
        // Cek apakah email terdaftar
        $admin = $this->Admin_model->get_by_email($email);
        
        if (!$admin) {
            $this->session->set_flashdata('error', 'Email tidak terdaftar di sistem.');
            redirect('admin/forgot_password');
        }

        // Generate token unik (6 digit angka)
        $reset_token = mt_rand(100000, 999999);
        $token_expiry = date('Y-m-d H:i:s', strtotime('+30 minutes'));

        // Simpan token ke database
        $update_data = [
            'reset_token' => $reset_token,
            'reset_token_expiry' => $token_expiry
        ];
        
        $this->db->where('id', $admin->id);
        
        if ($this->db->update('admin', $update_data)) {
            // Simpan data di session
            $this->session->set_userdata([
                'reset_email' => $email,
                'reset_admin_name' => $admin->nama,
                'reset_code_display' => $reset_token
            ]);
            
            // Coba kirim email (background process)
            $email_sent = $this->send_reset_email($admin->email, $admin->nama, $reset_token);
            
            if (!$email_sent) {
                // Jika email gagal, coba metode alternatif
                $email_sent = $this->send_reset_email_alternative($admin->email, $admin->nama, $reset_token);
            }
            
            // Redirect dengan pesan yang sesuai
            if ($email_sent) {
                $this->session->set_flashdata('success', 
                    '✅ <strong>Kode reset password telah dikirim ke email Anda!</strong><br>
                    <small>Silakan cek inbox atau spam folder di email Anda.</small>');
            } else {
                $this->session->set_flashdata('info', 
                    '📧 <strong>Kode reset password telah dibuat!</strong><br>
                    <small>Kode akan ditampilkan di halaman berikutnya untuk memastikan Anda dapat melanjutkan.</small>');
            }
            
            redirect('admin/forgot_password/verify');
        } else {
            $this->session->set_flashdata('error', 'Terjadi kesalahan sistem. Silakan coba lagi.');
            redirect('admin/forgot_password');
        }
    }

    /**
     * Halaman verifikasi kode OTP
     */
    public function verify()
    {
        // Jika sudah login, redirect ke dashboard
        if ($this->session->userdata('admin_logged_in')) {
            redirect('admin/dashboard');
        }

        // Cek apakah ada email di session
        $email = $this->session->userdata('reset_email');
        if (!$email) {
            redirect('admin/forgot_password');
        }

        $data['email'] = $email;
        $data['admin_name'] = $this->session->userdata('reset_admin_name');
        
        // Ambil kode dari session untuk ditampilkan
        $reset_code_display = $this->session->userdata('reset_code_display');
        if ($reset_code_display) {
            $data['display_code'] = $reset_code_display;
        }
        
        $this->load->view('admin/verify_reset_code', $data);
    }

    /**
     * Proses verifikasi kode OTP
     */
    public function verify_code()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('code', 'Kode', 'required|exact_length[6]|numeric');
        
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('admin/forgot_password/verify');
        }

        $email = $this->input->post('email', true);
        $code = $this->input->post('code', true);

        // Cek admin berdasarkan email
        $admin = $this->Admin_model->get_by_email($email);
        
        if (!$admin) {
            $this->session->set_flashdata('error', 'Email tidak valid.');
            $this->session->set_userdata('reset_email', $email);
            redirect('admin/forgot_password/verify');
        }

        // Cek apakah token cocok dan belum expired
        if (empty($admin->reset_token) || $admin->reset_token !== $code) {
            $this->session->set_flashdata('error', 'Kode reset tidak valid.');
            $this->session->set_userdata('reset_email', $email);
            redirect('admin/forgot_password/verify');
        }

        if (strtotime($admin->reset_token_expiry) < time()) {
            $this->session->set_flashdata('error', 'Kode reset telah kedaluwarsa. Silakan minta kode baru.');
            $this->session->set_userdata('reset_email', $email);
            redirect('admin/forgot_password/verify');
        }

        // Token valid, simpan data di session
        $this->session->set_userdata([
            'verified_email' => $email,
            'verified_code' => $code,
            'reset_admin_id' => $admin->id
        ]);
        
        redirect('admin/forgot_password/reset');
    }

    /**
     * Halaman reset password baru
     */
    public function reset()
    {
        // Cek apakah ada sesi reset yang valid
        if (!$this->session->userdata('verified_email')) {
            redirect('admin/forgot_password');
        }

        $data['email'] = $this->session->userdata('verified_email');
        $this->load->view('admin/reset_password', $data);
    }

    /**
     * Proses reset password
     */
    public function process_reset()
    {
        $this->load->library('form_validation');
        
        // Validasi form
        $this->form_validation->set_rules('password', 'Password', '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('admin/forgot_password/reset');
        }

        $email = $this->session->userdata('verified_email');
        $new_password = $this->input->post('password', true);

        // Cek admin
        $admin = $this->Admin_model->get_by_email($email);
        
        if (!$admin) {
            $this->session->set_flashdata('error', 'Sesi reset password tidak valid.');
            redirect('admin/forgot_password');
        }

        // Update password baru
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        
        $update_data = [
            'password' => $hashed_password,
            'reset_token' => NULL,
            'reset_token_expiry' => NULL
        ];
        
        $this->db->where('id', $admin->id);
        $result = $this->db->update('admin', $update_data);

        if ($result) {
            // Hapus semua session reset
            $this->session->unset_userdata([
                'reset_email', 
                'reset_admin_name', 
                'reset_code_display',
                'verified_email', 
                'verified_code', 
                'reset_admin_id'
            ]);
            
            $this->session->set_flashdata('success', 'Password berhasil direset. Silakan login dengan password baru Anda.');
            redirect('admin/login');
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset password. Silakan coba lagi.');
            redirect('admin/forgot_password/reset');
        }
    }

    /**
     * Kirim email reset password - Metode Utama (CodeIgniter Email Library)
     */
    private function send_reset_email($to_email, $name, $reset_code)
    {
        try {
            // Clear previous email data
            $this->email->clear(TRUE);
            
            // Set email data
            $this->email->from('rizqywahyu59@gmail.com', 'KosCare Admin System');
            $this->email->to($to_email);
            $this->email->subject('Reset Password Admin - KosCare');
            
            // Buat template email
            $message = $this->get_email_template($name, $reset_code);
            $this->email->message($message);
            
            // Kirim email
            if ($this->email->send()) {
                log_message('info', 'Email reset password berhasil dikirim ke: ' . $to_email);
                return TRUE;
            } else {
                return FALSE;
            }
        } catch (Exception $e) {
            log_message('error', 'Email exception: ' . $e->getMessage());
            return FALSE;
        }
    }
    
    /**
     * Kirim email reset password - Metode Alternatif (PHP mail() function)
     */
    private function send_reset_email_alternative($to_email, $name, $reset_code)
    {
        try {
            $subject = 'Reset Password Admin - KosCare';
            $message = $this->get_email_template($name, $reset_code);
            
            // Headers untuk email HTML
            $headers = [
                'MIME-Version: 1.0',
                'Content-type: text/html; charset=utf-8',
                'From: KosCare Admin System <rizqywahyu59@gmail.com>',
                'Reply-To: rizqywahyu59@gmail.com',
                'X-Mailer: PHP/' . phpversion()
            ];
            
            // Kirim menggunakan mail() function
            if (mail($to_email, $subject, $message, implode("\r\n", $headers))) {
                log_message('info', 'Email alternatif berhasil dikirim ke: ' . $to_email);
                return TRUE;
            } else {
                return FALSE;
            }
        } catch (Exception $e) {
            log_message('error', 'Email alternatif exception: ' . $e->getMessage());
            return FALSE;
        }
    }
    
    /**
     * Template email sederhana
     */
    private function get_email_template($name, $code)
    {
        $expiry_time = date('H:i', strtotime('+30 minutes'));
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <style>
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    line-height: 1.6;
                    color: #333;
                    background-color: #f4f4f4;
                    margin: 0;
                    padding: 0;
                }
                .container {
                    max-width: 600px;
                    margin: 0 auto;
                    background: white;
                    border-radius: 10px;
                    overflow: hidden;
                    box-shadow: 0 5px 20px rgba(0,0,0,0.1);
                }
                .header {
                    background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
                    color: white;
                    padding: 30px;
                    text-align: center;
                }
                .header h2 {
                    margin: 0;
                    font-size: 24px;
                }
                .content {
                    padding: 40px;
                }
                .code-box {
                    background: #f8fbff;
                    border: 2px dashed #4a90e2;
                    border-radius: 10px;
                    padding: 25px;
                    text-align: center;
                    margin: 30px 0;
                }
                .reset-code {
                    font-size: 42px;
                    font-weight: bold;
                    letter-spacing: 8px;
                    color: #4a90e2;
                    font-family: 'Courier New', monospace;
                }
                .warning {
                    background: #fff3cd;
                    border-left: 4px solid #ffc107;
                    padding: 15px;
                    border-radius: 5px;
                    margin: 20px 0;
                }
                .footer {
                    text-align: center;
                    padding: 20px;
                    background: #f8f9fa;
                    color: #666;
                    font-size: 12px;
                    border-top: 1px solid #eee;
                }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Reset Password Admin</h2>
                    <p>KosCare Management System</p>
                </div>
                
                <div class='content'>
                    <p>Halo <strong>" . htmlspecialchars($name) . "</strong>,</p>
                    
                    <p>Anda telah meminta reset password untuk akun admin KosCare. Berikut adalah kode reset Anda:</p>
                    
                    <div class='code-box'>
                        <div class='reset-code'>$code</div>
                        <p style='color: #dc3545; margin-top: 10px;'>
                            ⏰ Kode berlaku hingga: $expiry_time
                        </p>
                    </div>
                    
                    <div class='warning'>
                        <p><strong>📋 Petunjuk Penggunaan:</strong></p>
                        <ul>
                            <li>Masukkan kode di atas pada halaman verifikasi reset password</li>
                            <li>Kode hanya dapat digunakan satu kali</li>
                            <li>Jangan bagikan kode ini kepada siapa pun</li>
                            <li>Jika Anda tidak meminta reset password, abaikan email ini</li>
                        </ul>
                    </div>
                    
                    <p>Terima kasih,</p>
                    <p><strong>Tim KosCare</strong></p>
                </div>
                
                <div class='footer'>
                    <p>© " . date('Y') . " KosCare. All rights reserved.</p>
                    <p>Email ini dikirim secara otomatis. Mohon tidak membalas email ini.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    /**
     * Kirim ulang kode OTP
     */
    public function resend_code()
    {
        $email = $this->session->userdata('reset_email');
        
        if (!$email) {
            $this->session->set_flashdata('error', 'Email tidak ditemukan.');
            redirect('admin/forgot_password');
        }

        $admin = $this->Admin_model->get_by_email($email);
        
        if (!$admin) {
            $this->session->set_flashdata('error', 'Email tidak terdaftar.');
            redirect('admin/forgot_password');
        }

        // Generate token baru
        $reset_token = mt_rand(100000, 999999);
        $token_expiry = date('Y-m-d H:i:s', strtotime('+30 minutes'));

        // Update token di database
        $this->db->where('id', $admin->id);
        $this->db->update('admin', [
            'reset_token' => $reset_token,
            'reset_token_expiry' => $token_expiry
        ]);

        // Update kode di session
        $this->session->set_userdata('reset_code_display', $reset_token);
        
        // Coba kirim email
        $email_sent = $this->send_reset_email($admin->email, $admin->nama, $reset_token);
        
        if (!$email_sent) {
            $email_sent = $this->send_reset_email_alternative($admin->email, $admin->nama, $reset_token);
        }
        
        // Pesan yang lebih positif
        if ($email_sent) {
            $this->session->set_flashdata('success', 
                '✅ <strong>Kode baru telah dikirim ke email Anda!</strong><br>
                <small>Silakan cek inbox atau spam folder.</small>');
        } else {
            $this->session->set_flashdata('info', 
                '🔄 <strong>Kode baru telah dibuat!</strong><br>
                <small>Kode telah diperbarui dan ditampilkan di bawah.</small>');
        }

        redirect('admin/forgot_password/verify');
    }

    /**
     * Cancel reset process
     */
    public function cancel()
    {
        // Hapus semua session reset
        $this->session->unset_userdata([
            'reset_email', 
            'reset_admin_name', 
            'reset_code_display',
            'verified_email', 
            'verified_code', 
            'reset_admin_id'
        ]);
        redirect('admin/login');
    }
    
    /**
     * Debug email configuration
     */
    public function test_email($email = 'test@example.com')
    {
        echo "<h2>Testing Email Configuration</h2>";
        echo "<p>Target email: $email</p>";
        
        // Test 1: Check email library
        echo "<h3>1. Testing CodeIgniter Email Library</h3>";
        
        $this->email->clear(TRUE);
        $this->email->from('rizqywahyu59@gmail.com', 'Test System');
        $this->email->to($email);
        $this->email->subject('Test Email from KosCare');
        $this->email->message('This is a test email sent at ' . date('Y-m-d H:i:s'));
        
        if ($this->email->send()) {
            echo "✅ Email sent successfully using CodeIgniter Email Library!<br>";
            echo $this->email->print_debugger();
        } else {
            echo "❌ Failed to send email using CodeIgniter<br>";
            echo $this->email->print_debugger(['headers', 'subject', 'body']);
        }
        
        echo "<hr><h3>2. Testing PHP mail() function</h3>";
        
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/plain; charset=utf-8',
            'From: Test System <rizqywahyu59@gmail.com>'
        ];
        
        if (mail($email, 'Test PHP mail()', 'Test message', implode("\r\n", $headers))) {
            echo "✅ PHP mail() function works!<br>";
        } else {
            echo "❌ PHP mail() function failed<br>";
        }
        
        echo "<hr><h3>3. System Information</h3>";
        echo "PHP Version: " . phpversion() . "<br>";
        echo "CI Version: " . CI_VERSION . "<br>";
        echo "Server: " . $_SERVER['SERVER_SOFTWARE'] . "<br>";
        
        echo "<hr><p><a href='" . site_url('admin/forgot_password') . "'>Kembali ke Forgot Password</a></p>";
    }
    
    /**
     * Test kode tanpa email (untuk development)
     */
    public function test_process()
    {
        $email = 'admin@admin.com'; // Ganti dengan email yang ada di database
        echo "<h2>Testing Reset Password Process</h2>";
        echo "<p>Testing email: $email</p>";
        
        // Simulasikan POST request
        $_POST['email'] = $email;
        
        // Panggil process_request
        ob_start();
        $this->process_request();
        $output = ob_get_clean();
        
        echo "<hr><h3>Process Output:</h3>";
        echo $output;
        
        echo "<hr><p><a href='" . site_url('admin/forgot_password') . "'>Kembali ke Forgot Password</a></p>";
    }
}