<?php
/**
 * FRE3 PRO - Corporate Service Engine
 * Version: 1.8.4 - Enhanced Access Security
 */

// --- 1. ASSETS & PERFORMANCE ---
function fre3_assets_setup() {
    osc_enqueue_script('jquery');
}
osc_add_hook('init', 'fre3_assets_setup');

function fre3_unified_performance($tag, $handle = null, $src = null) {
    if ($handle && strpos($handle, '8dde82d') !== false) {
        return str_replace(' src', ' defer src', $tag);
    }
    return $tag;
}
if(function_exists('add_filter')) { 
    add_filter('script_loader_tag', 'fre3_unified_performance', 10, 3); 
}

// --- 2. SEO & TITLES ---
function fre3_seo_title($title = '') {
    if (osc_is_ad_page()) {
        $item = osc_item();
        return (isset($item['s_title'])) ? $item['s_title'] : $title;
    }
    return $title;
}
osc_add_filter('meta_title_filter', 'fre3_seo_title');

// --- 3. PRO STATUS CHECK ---
function fre3_is_pro($user_id = null) {
    if($user_id == null) { $user_id = osc_logged_user_id(); }
    if(!$user_id) return false;
    $user = User::newInstance()->findByPrimaryKey($user_id);
    return (is_array($user) && isset($user['b_company']) && $user['b_company'] == 1);
}

// --- 4. NAIRA CURRENCY ---
function fre3_price_format($price = null) {
    if ($price === null || $price === '' || $price == 0) {
        return __('Price on Request', 'fre3');
    }
    return '₦' . number_format($price / 1000000, 0, '.', ',');
}

// --- 5. CLEAN MESSAGES ---
function fre3_custom_flash_filter($text, $section) {
    $core_msg_1 = 'The user has been created. An activation email has been sent';
    $core_msg_2 = 'Registration successful! Please check your email.';
    $core_msg_3 = 'The user doesn\'t exist';

    if (strpos($text, $core_msg_1) !== false || strpos($text, $core_msg_2) !== false) {
        return 'Registration successful! Please check your email/spam to activate your account.';
    }
    if (strpos($text, $core_msg_3) !== false) {
        return 'Login failed: The user account does not exist.';
    }
    return $text;
}
osc_add_filter('flash_message_text', 'fre3_custom_flash_filter', 10, 2);

// --- 6. RANDOMIZATION LOGIC ---
function fre3_get_random_search_items() {
    if (View::newInstance()->_exists('search')) {
        $mSearch = View::newInstance()->_get('search');
    } else {
        $mSearch = Search::newInstance();
        View::newInstance()->_exportVariableToView('search', $mSearch);
    }
    $mSearch->reconnect();
    $items = $mSearch->doSearch();
    if (!is_array($items)) { $items = iterator_to_array($items); }
    shuffle($items);
    View::newInstance()->_exportVariableToView('items', $items);
    return $items;
}

function fre3_random_latest_items($items) {
    if (osc_is_home_page()) { shuffle($items); }
    return $items;
}
osc_add_filter('latest_items_extra', 'fre3_random_latest_items');

// --- 7. ACCESS & REDIRECTS (TRAFFIC GUARD) ---
function fre3_after_login_redirection() {
    $user_id = osc_logged_user_id();
    $user_data = User::newInstance()->findByPrimaryKey($user_id);
    $redirect_url = (isset($user_data['b_company']) && $user_data['b_company'] == 1) ? osc_user_dashboard_url() : osc_base_url() . 'invoice/dashboard';
    osc_redirect_to($redirect_url);
    exit;
}
osc_add_hook('after_login', 'fre3_after_login_redirection');

/**
 * GLOBAL TRAFFIC GUARD: Prevents manual URL bypass
 * Stops non-company users from accessing /user/dashboard via manual link
 */
function fre3_traffic_guard() {
    $location = Rewrite::newInstance()->get_location();
    $section  = Rewrite::newInstance()->get_section();

    // Check if the user is trying to reach the default user dashboard area
    if ($location == 'user' && ($section == 'dashboard' || $section == 'items' || $section == 'profile')) {
        if (osc_is_web_user_logged_in() && !fre3_is_pro()) {
            osc_redirect_to(osc_base_url() . 'invoice/dashboard');
            exit;
        }
    }
}
osc_add_hook('init', 'fre3_traffic_guard');

function fre3_restrict_post_ad() {
    if (Rewrite::newInstance()->get_location() == 'item' && Rewrite::newInstance()->get_section() == 'item_add') {
        if (osc_is_web_user_logged_in() && !fre3_is_pro()) {
            osc_add_flash_error_message(__('Access Denied: Only Company accounts can post ads.', 'fre3'));
            osc_redirect_to(osc_base_url() . 'invoice/dashboard');
            exit;
        }
    }
}
osc_add_hook('init', 'fre3_restrict_post_ad');

// --- 8. WEBP ENGINE ---
function fre3_convert_to_webp($resource) {
    $path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '.' . $resource['s_extension'];
    $webp_path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '.webp';
    if (file_exists($path)) {
        $info = getimagesize($path);
        $mime = $info['mime'];
        if ($mime == 'image/jpeg' || $mime == 'image/jpg') { $image = imagecreatefromjpeg($path); }
        elseif ($mime == 'image/png') { 
            $image = imagecreatefrompng($path);
            imagepalettetotruecolor($image);
        } else { return; }
        if($image) {
            imagewebp($image, $webp_path, 85);
            imagedestroy($image);
            @chmod($webp_path, 0644);
        }
    }
}
osc_add_hook('uploaded_file', 'fre3_convert_to_webp');

// --- 9. CORE HELPERS ---
if(!function_exists('zet_param')) {
    function zet_param($name) {
        return osc_get_preference($name, 'fre3_theme');
    }
}

if(!function_exists('zet_location_from_cookies')) {
    function zet_location_from_cookies() {
        $item = array();
        $item['fk_c_country_code'] = Cookie::newInstance()->get_value('sCountry');
        $item['fk_i_region_id'] = Cookie::newInstance()->get_value('sRegion');
        $item['fk_i_city_id'] = Cookie::newInstance()->get_value('sCity');
        return $item;
    }
}

if(!function_exists('zet_get_session')) {
    function zet_get_session($key) {
        return class_exists('Session') ? Session::newInstance()->_get($key) : '';
    }
}

if(!function_exists('zet_ajax_image_upload')) {
    function zet_ajax_image_upload() {
        return osc_get_preference('ajax_upload', 'fre3_theme') == '1' ? true : false;
    }
}
// --- 11. STRICT REGISTRATION GUARD (ANTI-SPAM HARD MODE) ---
function fre3_registration_guard() {
    if (Params::getParam('page') == 'register' && Params::getParam('action') == 'register_post') {
        
        $name  = trim(Params::getParam('s_name'));
        $email = trim(Params::getParam('s_email'));
        $phone = trim(Params::getParam('s_phone'));
        $ip    = osc_get_ip();
        
        $is_invalid = false;
        $reason = '';

        // ============================================
        // 1. CORE BAN RULES (KEEP YOUR ORIGINAL)
        // ============================================
        if (class_exists('BanRule')) {
            $banManager = BanRule::newInstance();

            $emailBans = $banManager->getEmailRules();
            if(is_array($emailBans)) {
                foreach($emailBans as $ban) {
                    if(!empty($ban['s_email']) && strtolower($email) == strtolower($ban['s_email'])) {
                        $is_invalid = true;
                        $reason = 'Access denied: This email is blocked.';
                        break;
                    }
                }
            }

            if (!$is_invalid) {
                $ipBans = $banManager->getIpRules();
                if(is_array($ipBans)) {
                    foreach($ipBans as $ban) {
                        if(!empty($ban['s_ip']) && $ip == $ban['s_ip']) {
                            $is_invalid = true;
                            $reason = 'Access denied: Your IP is blocked.';
                            break;
                        }
                    }
                }
            }
        }

        // ============================================
        // 2. FULL NAME VALIDATION (STRONGER)
        // ============================================
        if (!$is_invalid) {
            if (!preg_match('/^[A-Za-z]{2,}\s+[A-Za-z]{2,}/', $name)) {
                $is_invalid = true;
                $reason = 'Enter valid First & Last name.';
            }
        }

        // ============================================
        // 3. EMAIL WHITELIST
        // ============================================
        if (!$is_invalid) {
            $allowed = array('gmail.com', 'yahoo.com', 'hotmail.com');
            $domain  = strtolower(substr(strrchr($email, "@"), 1));

            if (!in_array($domain, $allowed)) {
                $is_invalid = true;
                $reason = 'Only Gmail, Yahoo, and Hotmail are accepted.';
            }
        }

        // ============================================
        // 4. BLOCK DISPOSABLE EMAILS
        // ============================================
        if (!$is_invalid) {
            $blocked_domains = array(
                'tempmail.com','10minutemail.com','guerrillamail.com',
                'mailinator.com','trashmail.com','yopmail.com'
            );

            $domain  = strtolower(substr(strrchr($email, "@"), 1));
            if (in_array($domain, $blocked_domains)) {
                $is_invalid = true;
                $reason = 'Temporary emails are not allowed.';
            }
        }

        // ============================================
        // 5. SUSPICIOUS EMAIL PATTERN (BOT DETECTION)
        // ============================================
        if (!$is_invalid) {
            if (preg_match('/[0-9]{5,}/', $email)) {
                $is_invalid = true;
                $reason = 'Invalid email format.';
            }
        }

        // ============================================
        // 6. PHONE VALIDATION (KEEP YOURS)
        // ============================================
        if (!$is_invalid) {
            $clean_phone = preg_replace('/[^0-9]/', '', $phone);
            if (!preg_match('/^(234|0)[789][01]\d{8}$/', $clean_phone)) {
                $is_invalid = true;
                $reason = 'Valid Nigerian phone number required.';
            }
        }

        // ============================================
        // 7. RATE LIMIT (ANTI BOT FLOOD)
        // ============================================
        if (!$is_invalid) {
            $file = osc_base_path() . 'oc-content/uploads/fre3_reg_' . md5($ip) . '.txt';
            $now  = time();

            if (file_exists($file)) {
                $last = (int)file_get_contents($file);

                // Block if user tries again within 15 seconds
                if (($now - $last) < 15) {
                    $is_invalid = true;
                    $reason = 'Too many attempts. Please wait 15 seconds.';
                }
            }

            file_put_contents($file, $now);
        }

        // ============================================
        // FINAL BLOCK
        // ============================================
        if ($is_invalid) {
            if(function_exists('osc_add_flash_error_message')) {
                osc_add_flash_error_message(__($reason));
            }

            header('Location: ' . osc_base_url() . 'user/register');
            exit;
        }
    }
}
?>