<?php
/**
 * Main Authentication Class
 */
class DGA_Auth {
    
    public function __construct() {
        add_action('init', array($this, 'init'));
        add_action('wp_logout', array($this, 'logout'));
        add_filter('authenticate', array($this, 'authenticate_user'), 10, 3);
    }
    
    public function init() {
        // Start session if not already started
        if (!session_id()) {
            session_start();
        }
    }
    
    /**
     * Authenticate user with OTP
     */
    public function authenticate_user($user, $username, $password) {
        // Skip if not our authentication method
        if (isset($_POST['dga_auth_type']) && $_POST['dga_auth_type'] === 'otp') {
            return $this->authenticate_with_otp();
        }
        
        return $user;
    }
    
    /**
     * Authenticate user using OTP
     */
    private function authenticate_with_otp() {
        $mobile = sanitize_text_field($_POST['mobile']);
        $otp = sanitize_text_field($_POST['otp']);
        
        if (empty($mobile) || empty($otp)) {
            return new WP_Error('invalid_credentials', __('Mobile number and OTP are required.', 'donyaye-game'));
        }
        
        // Verify OTP
        if (!$this->verify_otp($mobile, $otp)) {
            return new WP_Error('invalid_otp', __('Invalid or expired OTP.', 'donyaye-game'));
        }
        
        // Check if user exists
        $user = $this->get_user_by_mobile($mobile);
        
        if (!$user) {
            // User doesn't exist, create new account
            $user = $this->create_user_account($mobile);
        }
        
        if (is_wp_error($user)) {
            return $user;
        }
        
        // Mark OTP as used
        $this->mark_otp_used($mobile, $otp);
        
        return $user;
    }
    
    /**
     * Verify OTP code
     */
    public function verify_otp($mobile, $otp) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'dga_otp_codes';
        
        $result = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name 
            WHERE mobile = %s 
            AND otp_code = %s 
            AND expires_at > NOW() 
            AND used = 0 
            ORDER BY created_at DESC 
            LIMIT 1",
            $mobile,
            $otp
        ));
        
        return $result !== null;
    }
    
    /**
     * Mark OTP as used
     */
    public function mark_otp_used($mobile, $otp) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'dga_otp_codes';
        
        $wpdb->update(
            $table_name,
            array('used' => 1),
            array('mobile' => $mobile, 'otp_code' => $otp),
            array('%d'),
            array('%s', '%s')
        );
    }
    
    /**
     * Get user by mobile number
     */
    public function get_user_by_mobile($mobile) {
        $users = get_users(array(
            'meta_key' => 'mobile_number',
            'meta_value' => $mobile,
            'number' => 1
        ));
        
        return !empty($users) ? $users[0] : false;
    }
    
    /**
     * Create new user account
     */
    public function create_user_account($mobile, $user_data = array()) {
        $default_data = array(
            'first_name' => '',
            'last_name' => '',
            'national_code' => '',
            'birth_date' => ''
        );
        
        $user_data = wp_parse_args($user_data, $default_data);
        
        // Generate username from mobile
        $username = 'user_' . $mobile;
        $email = $mobile . '@donyaye-game.local';
        
        // Check if username exists
        $counter = 1;
        $original_username = $username;
        while (username_exists($username)) {
            $username = $original_username . '_' . $counter;
            $counter++;
        }
        
        // Create user
        $user_id = wp_create_user($username, wp_generate_password(), $email);
        
        if (is_wp_error($user_id)) {
            return $user_id;
        }
        
        // Set user role
        $user = new WP_User($user_id);
        $user->set_role('customer');
        
        // Update user meta
        wp_update_user(array(
            'ID' => $user_id,
            'first_name' => $user_data['first_name'],
            'last_name' => $user_data['last_name'],
            'display_name' => trim($user_data['first_name'] . ' ' . $user_data['last_name'])
        ));
        
        // Add custom meta
        update_user_meta($user_id, 'mobile_number', $mobile);
        update_user_meta($user_id, 'national_code', $user_data['national_code']);
        update_user_meta($user_id, 'birth_date', $user_data['birth_date']);
        update_user_meta($user_id, 'registration_date', current_time('mysql'));
        
        return get_user_by('id', $user_id);
    }
    
    /**
     * Complete user registration with additional data
     */
    public function complete_registration($mobile, $user_data) {
        $user = $this->get_user_by_mobile($mobile);
        
        if (!$user) {
            return new WP_Error('user_not_found', __('User not found.', 'donyaye-game'));
        }
        
        // Update user data
        wp_update_user(array(
            'ID' => $user->ID,
            'first_name' => $user_data['first_name'],
            'last_name' => $user_data['last_name'],
            'display_name' => trim($user_data['first_name'] . ' ' . $user_data['last_name'])
        ));
        
        // Update custom meta
        update_user_meta($user->ID, 'national_code', $user_data['national_code']);
        update_user_meta($user->ID, 'birth_date', $user_data['birth_date']);
        
        return $user;
    }
    
    /**
     * Logout user
     */
    public function logout() {
        // Clear any custom session data
        if (session_id()) {
            session_destroy();
        }
    }
    
    /**
     * Check if user is logged in
     */
    public function is_user_logged_in() {
        return is_user_logged_in();
    }
    
    /**
     * Get current user
     */
    public function get_current_user() {
        return wp_get_current_user();
    }
    
    /**
     * Get user mobile number
     */
    public function get_user_mobile($user_id = null) {
        if (!$user_id) {
            $user_id = get_current_user_id();
        }
        
        return get_user_meta($user_id, 'mobile_number', true);
    }
} 