<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Email\Email;

class ForgotPassword extends BaseController
{
    protected $userModel;
    protected $email;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->email = \Config\Services::email();
    }

    /**
     * Display the forgot password form
     *
     * @return string
     */
    public function index()
    {
        return view('forgot_password');
    }

    /**
     * Process the forgot password form
     *
     * @return ResponseInterface
     */
    public function sendOtp()
    {
        // Validate input
        $rules = [
            'email' => 'required|valid_email',
        ];

        if (!$this->validate($rules)) {
            return view('forgot_password', [
                'validation' => $this->validator,
            ]);
        }

        // Get input data
        $email = $this->request->getPost('email');

        // Find user by email
        $user = $this->userModel->findByEmail($email);

        if (!$user) {
            session()->setFlashdata('error', 'No account found with that email address.');
            return redirect()->back()->withInput();
        }

        // Generate 6-digit OTP
        $otp = rand(100000, 999999);

        // Set expiration time (30 minutes from now)
        $expiresAt = date('Y-m-d H:i:s', strtotime('+30 minutes'));

        // Update user with OTP
        $this->userModel->updateOtp($user['id'], $otp, $expiresAt);

        // Send OTP via email
        $emailSent = $this->sendOtpEmail($email, $otp);

        if (!$emailSent) {
            session()->setFlashdata('error', 'Failed to send OTP email. Please try again.');
            return redirect()->back()->withInput();
        }

        // Store email in session for later verification
        session()->set('reset_email', $email);

        // Set success message
        session()->setFlashdata('success', 'OTP has been sent to your email address.');

        // Redirect to OTP verification page
        return redirect()->to('/forgot-password/verify-otp');
    }

    /**
     * Send OTP via email
     *
     * @param string $email
     * @param string $otp
     * @return bool
     */
    private function sendOtpEmail($email, $otp)
    {
        $this->email->setTo($email);
        $this->email->setSubject('Password Reset OTP - Labourdnhdd CMS');
        $this->email->setMessage($this->getOtpEmailTemplate($otp));

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

    /**
     * Get OTP email template
     *
     * @param string $otp
     * @return string
     */
    private function getOtpEmailTemplate($otp)
    {
        $template = '
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #5EC9F8 0%, #3A82D4 50%, #214D8C 100%); color: white; padding: 20px; text-align: center; }
                .content { background: #f9f9f9; padding: 30px; border: 1px solid #ddd; }
                .otp { font-size: 32px; font-weight: bold; color: #3A82D4; text-align: center; margin: 30px 0; }
                .footer { text-align: center; margin-top: 20px; color: #666; font-size: 12px; }
                .logo { max-width: 150px; margin: 0 auto 20px; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <img src="cid:labourdnhdd_logo" alt="Labourdnhdd Logo" class="logo">
                    <h1>Labourdnhdd - CMS</h1>
                    <p>Companies Management System</p>
                </div>
                <div class="content">
                    <h2>Password Reset Request</h2>
                    <p>Hello,</p>
                    <p>You have requested to reset your password for your Labourdnhdd Companies Management System account. Please use the following OTP code to proceed with the password reset process:</p>
                    <div class="otp">' . $otp . '</div>
                    <p>This OTP will expire in 30 minutes. If you did not request this password reset, please ignore this email.</p>
                    <p>Thank you,<br>The Labourdnhdd Team</p>
                </div>
                <div class="footer">
                    <p>This is an automated message. Please do not reply to this email.</p>
                    <p>&copy; ' . date('Y') . ' Labourdnhdd - Companies Management System. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>';

        return $template;
    }

    /**
     * Display the OTP verification form
     *
     * @return string
     */
    public function verifyOtp()
    {
        // Check if we have a reset email in session
        if (!session()->get('reset_email')) {
            return redirect()->to('/forgot-password');
        }

        return view('verify_otp');
    }

    /**
     * Process the OTP verification
     *
     * @return ResponseInterface
     */
    public function processOtp()
    {
        // Check if we have a reset email in session
        if (!session()->get('reset_email')) {
            return redirect()->to('/forgot-password');
        }

        // Validate input
        $rules = [
            'otp' => 'required|exact_length[6]',
        ];

        if (!$this->validate($rules)) {
            return view('verify_otp', [
                'validation' => $this->validator,
            ]);
        }

        // Get input data
        $otp = $this->request->getPost('otp');

        // Get user by email
        $email = session()->get('reset_email');
        $user = $this->userModel->findByEmail($email);

        if (!$user) {
            session()->setFlashdata('error', 'User not found.');
            return redirect()->to('/forgot-password');
        }

        // Check if OTP matches and is not expired
        if ($user['otp'] != $otp) {
            session()->setFlashdata('error', 'Invalid OTP. Please try again.');
            return redirect()->back()->withInput();
        }

        // Check if OTP is expired
        if (strtotime($user['otp_expires_at']) < time()) {
            session()->setFlashdata('error', 'OTP has expired. Please request a new one.');
            return redirect()->to('/forgot-password');
        }

        // OTP is valid, redirect to reset password page
        return redirect()->to('/forgot-password/reset-password');
    }

    /**
     * Display the reset password form
     *
     * @return string
     */
    public function resetPassword()
    {
        // Check if we have a reset email in session
        if (!session()->get('reset_email')) {
            return redirect()->to('/forgot-password');
        }

        return view('reset_password');
    }

    /**
     * Process the password reset
     *
     * @return ResponseInterface
     */
    public function updatePassword()
    {
        // Check if we have a reset email in session
        if (!session()->get('reset_email')) {
            return redirect()->to('/forgot-password');
        }

        // Validate input
        $rules = [
            'password' => 'required|min_length[8]',
            'confirm_password' => 'required|matches[password]',
        ];

        if (!$this->validate($rules)) {
            return view('reset_password', [
                'validation' => $this->validator,
            ]);
        }

        // Get input data
        $password = $this->request->getPost('password');

        // Get user by email
        $email = session()->get('reset_email');
        $user = $this->userModel->findByEmail($email);

        if (!$user) {
            session()->setFlashdata('error', 'User not found.');
            return redirect()->to('/forgot-password');
        }

        // Debug: Log before password update
        log_message('debug', 'Updating password for user ID: ' . $user['id']);
        
        // Update password
        $this->userModel->updatePassword($user['id'], $password);
        
        // Debug: Log after password update
        log_message('debug', 'Password updated. New password hash: ' . password_hash($password, PASSWORD_DEFAULT));

        // Clear OTP
        $this->userModel->clearOtp($user['id']);

        // Send password change notification
        $this->sendPasswordChangeNotification($user);

        // Clear session data
        session()->remove('reset_email');

        // Set success message
        session()->setFlashdata('success', 'Password successfully reset. You can now login with your new password.');

        // Redirect to login page
        return redirect()->to('/login');
    }
    
    /**
     * Send password change notification email
     *
     * @param array $user
     * @return void
     */
    private function sendPasswordChangeNotification($user)
    {
        $this->email->setTo($user['email']);
        $this->email->setSubject('Password Changed Successfully - Labourdnhdd CMS');
        $this->email->setMessage($this->getPasswordChangeEmailTemplate($user));
        $this->email->send();
    }
    
    /**
     * Get password change email template
     *
     * @param array $user
     * @return string
     */
    private function getPasswordChangeEmailTemplate($user)
    {
        $template = '
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #5EC9F8 0%, #3A82D4 50%, #214D8C 100%); color: white; padding: 20px; text-align: center; }
                .content { background: #f9f9f9; padding: 30px; border: 1px solid #ddd; }
                .footer { text-align: center; margin-top: 20px; color: #666; font-size: 12px; }
                .logo { max-width: 150px; margin: 0 auto 20px; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <img src="cid:labourdnhdd_logo" alt="Labourdnhdd Logo" class="logo">
                    <h1>Labourdnhdd - CMS</h1>
                    <p>Companies Management System</p>
                </div>
                <div class="content">
                    <h2>Password Changed Successfully</h2>
                    <p>Hello ' . htmlspecialchars($user['username']) . ',</p>
                    <p>Your password for your Labourdnhdd Companies Management System account has been successfully changed on ' . date('Y-m-d H:i:s') . '.</p>
                    <p>If you did not initiate this change, please <a href="' . base_url('/forgot-password') . '">reset your password</a> immediately.</p>
                    <p>For security reasons, we recommend:</p>
                    <ul>
                        <li>Using a strong, unique password</li>
                        <li>Enabling two-factor authentication if available</li>
                        <li>Regularly updating your passwords</li>
                    </ul>
                    <p>Thank you,<br>The Labourdnhdd Team</p>
                </div>
                <div class="footer">
                    <p>This is an automated message. Please do not reply to this email.</p>
                    <p>&copy; ' . date('Y') . ' Labourdnhdd - Companies Management System. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>';

        return $template;
    }
}