<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Cron extends App_Controller
{
    public function index($key = '')
    {
        update_option('cron_has_run_from_cli', 1);
        log_message("error", "[CRON_NEW] New Cron.php file loaded - timestamp: " . time());

        if (defined('APP_CRON_KEY') && (APP_CRON_KEY != $key)) {
            header('HTTP/1.0 401 Unauthorized');
            die('Passed cron job key is not correct. The cron job key should be the same like the one defined in APP_CRON_KEY constant.');
        }

        $last_cron_run                  = get_option('last_cron_run');
        log_message("error", "[CRON_DEBUG] last_cron_run=" . $last_cron_run . ", time=" . time() . ", seconds=" . $seconds);
        $seconds = hooks()->apply_filters('cron_functions_execute_seconds', 300);

        if ($last_cron_run == '' || (time() > ($last_cron_run + $seconds))) {
            $this->load->model('cron_model');
            $this->cron_model->run();
            
            // Process password sync queue directly
            log_message('error', '[CRON_PWD] Starting password sync processing');
            $core_helper = APPPATH . 'modules/perfex_saas/helpers/perfex_saas_core_helper.php';
            if (file_exists($core_helper)) {
                log_message('error', '[CRON_PWD] Core helper file found, loading...');
                require_once($core_helper);
                if (function_exists('perfex_saas_process_password_sync_queue')) {
                    log_message('error', '[CRON_PWD] Function exists, calling...');
                    try {
                        perfex_saas_process_password_sync_queue();
                        log_message('error', '[CRON_PWD] Password sync completed successfully');
                    } catch (Exception $e) {
                        log_message('error', '[CRON_PWD] Error: ' . $e->getMessage());
                    }
                } else {
                    log_message('error', '[CRON_PWD] Function perfex_saas_process_password_sync_queue not found');
                }
            } else {
                log_message('error', '[CRON_PWD] Core helper file not found at: ' . $core_helper);
            }
        }
    }
}
