<?php

require_once __DIR__ . '/BaseController.php';
require_once __DIR__ . '/../models/UserModel.php';
require_once __DIR__ . '/../models/OtpModel.php';
require_once __DIR__ . '/../helpers/WhatsAppService.php';

class AuthController extends BaseController
{

    private $userModel;
    private $otpModel;
    private $whatsAppService;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = new UserModel();
        $this->otpModel = new OtpModel();
        $this->whatsAppService = new WhatsAppService();
    }

    /**
     * User registration
     */
    public function register()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['nama_lengkap', 'telepon', 'email', 'password']);

            // Validate data format
            $validationRules = [
                'email' => 'email',
                'telepon' => 'phone'
            ];
            $data = $this->validateAndSanitize($data, $validationRules);

            // Validate password length
            if (strlen($data['password']) < 6) {
                Response::validationError('Password must be at least 6 characters long');
            }

            // Check if phone or email already exists
            if ($this->userModel->phoneExists($data['telepon'])) {
                Response::validationError('Phone number already registered');
            }

            if ($this->userModel->emailExists($data['email'])) {
                Response::validationError('Email already registered');
            }

            // Prepare user data
            $userData = [
                'nama_lengkap' => $data['nama_lengkap'],
                'telepon' => $data['telepon'],
                'email' => $data['email'],
                'password' => $data['password'],
                'alamat' => $data['alamat'] ?? '',
                'provinsi' => $data['provinsi'] ?? '',
                'kota' => $data['kota'] ?? '',
                'kecamatan' => $data['kecamatan'] ?? '',
                'kelurahan' => $data['kelurahan'] ?? ''
            ];

            $userId = $this->userModel->createUser($userData);

            if ($userId) {
                Response::success('User registered successfully', [
                    'user_id' => $userId,
                    'message' => 'Registration successful'
                ]);
            } else {
                Response::error('Failed to register user');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * User login
     */
    public function login()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();

            $emailOrPhone = $data['emailOrPhone'] ?? '';
            $username = $data['username'] ?? '';
            $password = $data['password'] ?? '';

            // Validate input
            if (empty($emailOrPhone) && empty($username)) {
                Response::validationError('Email/phone/username is required');
            }

            if (empty($password)) {
                Response::validationError('Password is required');
            }

            // Find user
            $user = null;
            $loginIdentifier = !empty($emailOrPhone) ? $emailOrPhone : $username;

            if (!empty($emailOrPhone)) {
                $user = $this->userModel->findByEmailOrPhone($emailOrPhone);
            } else {
                $user = $this->userModel->findByUsername($username);
            }

            if (!$user) {
                Response::unauthorized('Invalid login credentials');
            }

            // Verify password
            $passwordValid = false;
            if (password_verify($password, $user['password'])) {
                $passwordValid = true;
            } else {
                // Check if it's old plain text password (for backward compatibility)
                if ($user['password'] === $password) {
                    $passwordValid = true;
                    // Update to hashed password
                    $this->userModel->updatePassword($user['id'], $password);
                }
            }

            if (!$passwordValid) {
                Response::unauthorized('Invalid login credentials');
            }

            // Prepare user data for response (exclude password)
            $userResponse = [
                'id' => (int) $user['id'],
                'nama_lengkap' => $user['nama_lengkap'],
                'email' => $user['email'],
                'telepon' => $user['telepon'],
                'username' => $user['username'],
                'alamat' => $user['alamat'],
                'provinsi' => $user['provinsi'],
                'kota' => $user['kota'],
                'kecamatan' => $user['kecamatan'],
                'kelurahan' => $user['kelurahan'],
                'foto_profil' => $user['foto_profil'],
                'created_at' => $user['created_at'],
                'updated_at' => $user['updated_at']
            ];

            Response::success('Login successful', [
                'user' => $userResponse,
                'message' => 'Welcome back!'
            ]);
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Send OTP for login
     */
    public function sendLoginOtp()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['phone']);

            $phone = trim($data['phone']);

            if (!$this->validatePhone($phone)) {
                Response::validationError('Invalid phone number format');
            }

            // Check if user exists
            $user = $this->userModel->findByPhone($phone);
            if (!$user) {
                Response::notFound('Phone number not registered');
            }

            // Generate OTP using old method (update user table)
            $otp = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);

            // Update OTP in user table
            $result = $this->userModel->updateOtp($phone, $otp);

            if ($result) {
                // Send OTP via WhatsApp
                $whatsAppResult = $this->whatsAppService->sendOTP($phone, $otp);

                if ($whatsAppResult['success']) {
                    Response::success('OTP sent successfully', [
                        'message' => 'OTP has been sent to your WhatsApp',
                        'phone' => $phone
                    ]);
                } else {
                    Response::error('Failed to send OTP via WhatsApp');
                }
            } else {
                Response::error('Failed to generate OTP');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Verify OTP for login
     */
    public function verifyLoginOtp()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['phone', 'otp']);

            $phone = trim($data['phone']);
            $otp = trim($data['otp']);

            if (!$this->validatePhone($phone)) {
                Response::validationError('Invalid phone number format');
            }

            // Verify OTP using old method (check user table)
            $user = $this->userModel->verifyOtp($phone, $otp);

            if ($user) {
                // Clear OTP
                $this->userModel->clearOtp($phone);

                // Prepare user data for response (exclude password and OTP)
                $userResponse = [
                    'id' => (int) $user['id'],
                    'nama_lengkap' => $user['nama_lengkap'],
                    'email' => $user['email'],
                    'telepon' => $user['telepon'],
                    'username' => $user['username'],
                    'alamat' => $user['alamat'],
                    'provinsi' => $user['provinsi'],
                    'kota' => $user['kota'],
                    'kecamatan' => $user['kecamatan'],
                    'kelurahan' => $user['kelurahan'],
                    'foto_profil' => $user['foto_profil'],
                    'created_at' => $user['created_at'],
                    'updated_at' => $user['updated_at']
                ];

                Response::success('OTP verified successfully', [
                    'user' => $userResponse,
                    'message' => 'Login successful'
                ]);
            } else {
                Response::unauthorized('Invalid OTP or phone number');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Send registration OTP
     */
    public function sendRegistrationOtp()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['phone']);

            $phone = trim($data['phone']);
            $purpose = $data['purpose'] ?? 'registration';

            if (!$this->validatePhone($phone)) {
                Response::validationError('Invalid phone number format');
            }

            // For registration, check if phone is already registered
            if ($purpose === 'registration' && $this->userModel->phoneExists($phone)) {
                Response::validationError('Phone number already registered');
            }

            // Generate OTP using new OTP system
            $otpResult = $this->otpModel->generateOtp($phone, $purpose);

            if ($otpResult) {
                // Send OTP via WhatsApp
                $whatsAppResult = $this->whatsAppService->sendOTP($phone, $otpResult['otp']);

                if ($whatsAppResult['success']) {
                    Response::success('OTP sent successfully', [
                        'message' => 'OTP has been sent to your WhatsApp',
                        'phone' => $phone,
                        'expires_at' => $otpResult['expires_at']
                    ]);
                } else {
                    Response::error('Failed to send OTP via WhatsApp');
                }
            } else {
                Response::error('Failed to generate OTP');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Verify registration OTP
     */
    public function verifyRegistrationOtp()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['phone', 'otp']);

            $phone = trim($data['phone']);
            $otp = trim($data['otp']);
            $purpose = $data['purpose'] ?? 'registration';

            if (!$this->validatePhone($phone)) {
                Response::validationError('Invalid phone number format');
            }

            // Verify OTP using new OTP system
            $verificationResult = $this->otpModel->verifyOtp($phone, $otp, $purpose);

            if ($verificationResult['success']) {
                Response::success($verificationResult['message'], [
                    'phone' => $phone,
                    'verified' => true
                ]);
            } else {
                Response::unauthorized($verificationResult['message']);
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Generic OTP verification
     */
    public function verifyOtp()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['phone', 'otp']);

            $phone = trim($data['phone']);
            $otp = trim($data['otp']);
            $purpose = $data['purpose'] ?? 'verification';

            if (!$this->validatePhone($phone)) {
                Response::validationError('Invalid phone number format');
            }

            // Verify OTP using new OTP system
            $verificationResult = $this->otpModel->verifyOtp($phone, $otp, $purpose);

            if ($verificationResult['success']) {
                Response::success($verificationResult['message'], [
                    'phone' => $phone,
                    'verified' => true
                ]);
            } else {
                Response::unauthorized($verificationResult['message']);
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }
}
