<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\HTTP\ResponseInterface;

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

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

    /**
     * Show registration page
     */
    public function register()
    {
        return view('register');
    }

    /**
     * Process registration and send OTP
     */
    public function processRegister()
    {
        $validation = \Config\Services::validation();

        $rules = [
            'name'      => 'required|min_length[3]',
            'email'     => 'required|valid_email|is_unique[users.email]',
            'mobile'    => 'required|min_length[10]',
            'password'  => 'required|min_length[6]',
            'address'   => 'required',
            'pin_code'  => 'required',
            'user_type' => 'required|in_list[seller,buyer]'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $validation->getErrors());
        }

        $data = [
            'name'      => $this->request->getPost('name'),
            'email'     => $this->request->getPost('email'),
            'mobile'    => $this->request->getPost('mobile'),
            'password'  => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'address'   => $this->request->getPost('address'),
            'pin_code'  => $this->request->getPost('pin_code'),
            'user_type' => $this->request->getPost('user_type'),
        ];

        // Insert user
        $userId = $this->userModel->insert($data);

        if ($userId) {
            // Generate OTP
            $otp = $this->userModel->generateOTP($userId);

            // Send OTP via email
            if ($this->sendOTPEmail($data['email'], $data['name'], $otp)) {
                session()->set('registration_email', $data['email']);
                return redirect()->to('/verify-otp')
                    ->with('success', 'OTP sent to your email. Please verify.');
            } else {
                return redirect()->back()
                    ->with('error', 'Failed to send OTP. Please try again.');
            }
        }

        return redirect()->back()
            ->with('error', 'Registration failed. Please try again.');
    }

    /**
     * Show login page (OTP request)
     */
    public function login()
    {
        return view('login_otp');
    }

    /**
     * Send OTP to existing user
     */
    public function sendLoginOTP()
    {
        $email = $this->request->getPost('email');

        if (!$email) {
            return redirect()->back()
                ->with('error', 'Please enter your email.');
        }

        $user = $this->userModel->getUserByEmail($email);

        if (!$user) {
            return redirect()->back()
                ->with('error', 'Email not registered. Please register first.');
        }

        // Generate OTP
        $otp = $this->userModel->generateOTP($user['id']);

        // Send OTP via email
        if ($this->sendOTPEmail($email, $user['name'], $otp)) {
            session()->set('login_email', $email);
            return redirect()->to('/verify-otp')
                ->with('success', 'OTP sent to your email.');
        }

        return redirect()->back()
            ->with('error', 'Failed to send OTP. Please try again.');
    }

    /**
     * Process password login (email + password)
     */
    public function processPasswordLogin()
    {
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        if (!$email || !$password) {
            return redirect()->back()->with('error', 'Please enter email and password.');
        }

        $user = $this->userModel->verifyPassword($email, $password);

        if ($user) {
            // Debug log
            log_message('info', 'Login successful for: ' . $email . ', Role: ' . ($user['role'] ?? $user['user_type']));
            
            // Set session data
            $sessionData = [
                'user_id'   => $user['id'],
                'user_name' => $user['name'],
                'name' => $user['name'],
                'user_email' => $user['email'],
                'email' => $user['email'],
                'user_type' => $user['user_type'],
                'role' => $user['role'] ?? $user['user_type'],
                'reliability_score' => $user['reliability_score'] ?? 0,
                'isLoggedIn' => true,
                'logged_in' => true
            ];
            
            session()->set($sessionData);

            log_message('info', 'Session set successfully for user: ' . $user['id']);

            // Redirect based on role directly
            $role = $user['role'] ?? $user['user_type'];
            
            if ($role === 'super_admin') {
                return redirect()->to('/superadmin/dashboard')->with('success', 'Welcome Super Admin!');
            } elseif ($role === 'admin') {
                return redirect()->to('/admin/dashboard')->with('success', 'Welcome Admin!');
            } elseif ($role === 'delivery') {
                return redirect()->to('/delivery/dashboard')->with('success', 'Welcome Delivery!');
            } elseif ($role === 'seller' || $user['user_type'] === 'seller') {
                return redirect()->to('/seller/dashboard')->with('success', 'Welcome Seller!');
            } else {
                // For buyers
                return redirect()->to('/buyer')->with('success', 'Welcome!');
            }
        }

        log_message('warning', 'Failed login attempt for: ' . $email);
        return redirect()->back()->with('error', 'Invalid email or password.');
    }

    /**
     * Show OTP verification page
     */
    public function verifyOTP()
    {
        $email = session()->get('registration_email') ?? session()->get('login_email');

        if (!$email) {
            return redirect()->to('/login');
        }

        return view('verify_otp', ['email' => $email]);
    }

    /**
     * Process OTP verification
     */
    public function processVerifyOTP()
    {
        $email = session()->get('registration_email') ?? session()->get('login_email');
        $otp = $this->request->getPost('otp');

        if (!$email || !$otp) {
            return redirect()->back()
                ->with('error', 'Invalid request.');
        }

        $user = $this->userModel->verifyOTP($email, $otp);

        if ($user) {
            // Set session
            session()->set([
                'user_id'   => $user['id'],
                'user_name' => $user['name'],
                'name' => $user['name'],
                'user_email' => $user['email'],
                'email' => $user['email'],
                'user_type' => $user['user_type'],
                'role' => $user['role'] ?? $user['user_type'],
                'reliability_score' => $user['reliability_score'] ?? 0,
                'isLoggedIn' => true,
                'logged_in' => true
            ]);

            // Clear temporary session
            session()->remove(['registration_email', 'login_email']);

            return redirect()->to('/dashboard')
                ->with('success', 'Login successful!');
        }

        return redirect()->back()
            ->with('error', 'Invalid or expired OTP.');
    }

    /**
     * Logout
     */
    public function logout()
    {
        session()->destroy();
        return redirect()->to('/')->with('success', 'Logged out successfully.');
    }

    /**
     * Send OTP via email
     */
    private function sendOTPEmail($to, $name, $otp)
    {
        $emailConfig = config('Email');
        $fromEmail = $emailConfig->fromEmail ?? 'noreply@flexmarket.com';
        $fromName  = $emailConfig->fromName ?? 'Flex Market';
        $this->email->setFrom($fromEmail, $fromName);
        $this->email->setTo($to);
        $this->email->setSubject('Your OTP for Flex Market');

        $message = "
            <html>
            <body>
                <h2>Hello {$name},</h2>
                <p>Your OTP for Flex Market verification is:</p>
                <h1 style='color: #ffc107; font-size: 36px; letter-spacing: 5px;'>{$otp}</h1>
                <p>This OTP will expire in 10 minutes.</p>
                <p>If you didn't request this, please ignore this email.</p>
                <br>
                <p>Best regards,<br>Flex Market Team</p>
            </body>
            </html>
        ";

        $this->email->setMessage($message);
        $this->email->setMailType('html');

        $sent = $this->email->send();

        // Always capture debugger output for diagnosis (can be removed later)
        $debug = $this->email->printDebugger(['headers', 'subject', 'body', 'protocol']);
        $logPath = WRITEPATH . 'logs/email_debug_' . date('Ymd_His') . '.log';
        @file_put_contents($logPath, ($sent ? "SENT\n" : "FAILED\n") . $debug);

        // Also write to CodeIgniter log
        if (function_exists('log_message')) {
            log_message($sent ? 'info' : 'error', "Email send result: " . ($sent ? 'SENT' : 'FAILED') . ". Debug saved to: {$logPath}");
            log_message($sent ? 'info' : 'error', $debug);
        }

        return $sent;
    }

    /**
     * Dashboard (protected) - redirects to appropriate dashboard based on role
     */
    public function dashboard()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login')->with('error', 'Please login first.');
        }

        $role = session()->get('role') ?: session()->get('user_type');
        
        // Redirect based on user role
        if ($role === 'super_admin') {
            return redirect()->to('/superadmin/dashboard');
        } elseif ($role === 'admin') {
            return redirect()->to('/admin/dashboard');
        } elseif ($role === 'delivery') {
            return redirect()->to('/delivery/dashboard');
        } elseif ($role === 'seller' || session()->get('user_type') === 'seller') {
            return redirect()->to('/seller/dashboard');
        } else {
            // For buyers, redirect to browse
            return redirect()->to('/buyer');
        }
    }
}
