<?php
/**
 * OTP Service
 * Handles OTP generation, storage, and verification
 */

require_once('onesignal-api.php');

class OTPService {
    private $db;
    private $rateLimit;
    private $rateWindow;
    
    public function __construct() {
        $this->rateLimit = $GLOBALS['OTP_RATE_LIMIT'];
        $this->rateWindow = $GLOBALS['OTP_RATE_WINDOW'];
    }
    
    /**
     * Generate and send OTP
     * 
     * @param string $email User's email
     * @return array [success, message, otp]
     */
    public function generateAndSendOTP($email) {
        // Validate email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return [false, 'Invalid email format', null];
        }
        
        // Check rate limit
        if (!checkRateLimit($email)) {
            return [false, 'Too many OTP requests. Please try again in ' . ($this->rateWindow / 60) . ' minutes.', null];
        }
        
        // Send OTP via OneSignal
        return onesignal_sendOTP($email);
    }
    
    /**
     * Verify OTP
     * 
     * @param string $email User's email
     * @param string $otp OTP to verify
     * @return array [success, message, token]
     */
    public function verifyOTP($email, $otp) {
        // Verify OTP
        list($success, $message) = onesignal_verifyOTP($email, $otp);
        
        if (!$success) {
            return [false, $message, null];
        }
        
        // Get user data
        $user = mysql_get('members', null, "email = '" . mysqli_real_escape_string(mysqli(), $email) . "'");
        
        if (!$user) {
            // Create new user if doesn't exist
            $user = $this->createUser($email);
        }
        
        // Generate JWT token
        $token = onesignal_generateToken($user);
        
        return [true, 'OTP verified successfully', $token];
    }
    
    /**
     * Create new user
     * 
     * @param string $email User's email
     * @return array User data
     */
    private function createUser($email) {
        $userData = [
            'email' => $email,
            'createdDate' => 'NOW()',
            'updatedDate' => 'NOW()',
            'status' => 'active'
        ];
        
        $userId = mysql_insert('members', $userData, true);
        return mysql_get('members', $userId);
    }
    
    /**
     * Clean expired OTPs
     */
    public function cleanExpiredOTPs() {
        mysql_query("DELETE FROM otp_verification WHERE expiry < NOW() OR used = 1");
    }
} 