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

class Login extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $user = $this->admin_m->get_empty_admin();
        if ($user == 1) {
            $this->login();
        } else {
            $this->create();
        }
    }

    public function login()
    {
        $this->redirectUrl('login');
        $data = array();
        $data['page_title'] = "Login";
        $data['page'] = "Login";
        $data['main_content'] = $this->load->view('frontend/login/login', $data, true);
        $this->load->view('frontend/index', $data);
    }





    // ---------------------------------------------------------------
    // Social OAuth 2.0 — Admin/User Login (e.g. Owner)
    // ---------------------------------------------------------------
    public function google_callback()
    {
        $this->_social_callback('google');
    }

    // ── Private: generic admin OAuth flow ────────────────────────────
    private function _social_callback($provider)
    {
        header('Content-Type: application/json');

        $code = $this->input->post('code', true);

        if (empty($code)) {
            echo json_encode(['st' => 0, 'msg' => $this->_err('No authorization code received.')]);
            return;
        }

        $cfg = $this->custom_m->_get_provider_config($provider);
        if (empty($cfg)) {
            echo json_encode(['st' => 0, 'msg' => $this->_err('Unsupported login provider.')]);
            return;
        }

        try {
            $http = new \GuzzleHttp\Client(['timeout' => 15]);

            // 1. Exchange code for access token
            $token = json_decode($http->post($cfg['token_url'], [
                'form_params' => [
                    'code' => $code,
                    'client_id' => $cfg['client_id'],
                    'client_secret' => $cfg['client_secret'],
                    'redirect_uri' => $cfg['redirect_uri'],
                    'grant_type' => $cfg['grant_type'],
                ],
            ])->getBody(), true);

            if (empty($token['access_token'])) {
                throw new \Exception('Could not obtain access token from ' . ucfirst($provider) . '.');
            }

            // 2. Fetch user profile
            $profile = json_decode($http->get($cfg['userinfo_url'], [
                'headers' => ['Authorization' => 'Bearer ' . $token['access_token']],
            ])->getBody(), true);

            // 3. Normalize via field map
            $fm = $cfg['field_map'];
            $social_data = [
                'provider' => $provider,
                'id' => $profile[$fm['id']] ?? null,
                'email' => strtolower($profile[$fm['email']] ?? ''),
                'name' => $profile[$fm['name']] ?? '',
                'picture' => $profile[$fm['picture']] ?? '',
            ];

            if (empty($social_data['id']) || empty($social_data['email'])) {
                throw new \Exception('Could not retrieve user information from ' . ucfirst($provider) . '.');
            }

            // 4. Delegate all auth logic to model
            $result = $this->custom_m->social_login_process_admin($social_data, $this->settings ?? []);

            // site_qr() must run in the controller (it is a controller method)
            if (!empty($result['_run_site_qr'])) {
                $this->site_qr();
                unset($result['_run_site_qr']);
            }

            echo json_encode($result);

        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            log_message('error', ucfirst($provider) . ' OAuth network error: ' . $e->getMessage());
            echo json_encode(['st' => 0, 'msg' => $this->_err('Could not connect to ' . ucfirst($provider) . '. Please check your connection.')]);
        } catch (\Exception $e) {
            log_message('error', ucfirst($provider) . ' OAuth error: ' . $e->getMessage());
            echo json_encode(['st' => 0, 'msg' => $this->_err(htmlspecialchars($e->getMessage()))]);
        }
    }

    // ---------------------------------------------------------------
    // Social OAuth Callbacks — Staff, Customer, Delivery
    // ---------------------------------------------------------------
    //
    // To add a new provider (e.g. Facebook, GitHub):
    //   1. Register its config in custom_m->_get_provider_config()
    //   2. Add a one-line public method:
    //        public function facebook_callback_others() { $this->_social_callback_others('facebook'); }
    // ---------------------------------------------------------------

    public function google_callback_others()
    {
        $this->_social_callback_others('google');
    }


    // ── Private: generic OAuth token exchange + profile fetch + dispatch ─
    private function _social_callback_others($provider)
    {
        header('Content-Type: application/json');

        $post          = $this->input->post(null, true);
        $code          = $post['code'] ?? '';
        $login_type    = $post['type'] ?? '';
        $redirect_page = $post['redirect_page'] ?? '';

        if (empty($code)) {
            echo json_encode(['st' => 0, 'msg' => $this->_err('No authorization code received.')]);
            return;
        }

        $cfg = $this->custom_m->_get_provider_config($provider);
        if (empty($cfg)) {
            echo json_encode(['st' => 0, 'msg' => $this->_err('Unsupported login provider: ' . htmlspecialchars($provider) . '.')]);
            return;
        }

        try {
            $http = new \GuzzleHttp\Client(['timeout' => 15]);

            // 1. Exchange authorization code for access token
            $token = json_decode($http->post($cfg['token_url'], [
                'form_params' => [
                    'code' => $code,
                    'client_id' => $cfg['client_id'],
                    'client_secret' => $cfg['client_secret'],
                    'redirect_uri' => $cfg['redirect_uri'],
                    'grant_type' => $cfg['grant_type'],
                ],
            ])->getBody(), true);

            if (empty($token['access_token'])) {
                throw new \Exception('Could not obtain access token from ' . ucfirst($provider) . '.');
            }

            // 2. Fetch user profile from provider
            $profile = json_decode($http->get($cfg['userinfo_url'], [
                'headers' => ['Authorization' => 'Bearer ' . $token['access_token']],
            ])->getBody(), true);

            // 3. Normalize profile fields using the field map
            $fm = $cfg['field_map'];

            $social_data = [
                'provider' => $provider,
                'id' => $profile[$fm['id']] ?? null,
                'email' => strtolower($profile[$fm['email']] ?? ''),
                'name' => $profile[$fm['name']] ?? '',
                'picture' => $profile[$fm['picture']] ?? '',
            ];

            if (empty($social_data['id']) || empty($social_data['email'])) {
                throw new \Exception('Could not retrieve user information from ' . ucfirst($provider) . '.');
            }

            // 4. Delegate all auth logic to the shared model method
            $result = $this->custom_m->social_login_process($social_data, $login_type, $redirect_page);
            echo json_encode($result);

        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            log_message('error', ucfirst($provider) . ' OAuth network error: ' . $e->getMessage());
            echo json_encode(['st' => 0, 'msg' => $this->_err('Could not connect to ' . ucfirst($provider) . '. Please check your connection.')]);
        } catch (\Exception $e) {
            log_message('error', ucfirst($provider) . ' OAuth error: ' . $e->getMessage());
            echo json_encode(['st' => 0, 'msg' => $this->_err(htmlspecialchars($e->getMessage()))]);
        }
    }

    // ── Alert helpers ────────────────────────────────────────────────────────────

    private function _err(string $msg): string
    {
        return '<div class="alert alert-danger"><i class="fas fa-times-circle"></i> ' . $msg . '</div>';
    }

    private function _warn(string $msg): string
    {
        return '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> ' . $msg . '</div>';
    }

    public function create()
    {
        $data = array();
        $data['page_title'] = "Login";
        $data['page'] = "Login";
        $data['main_content'] = $this->load->view('frontend/login/create_admin', $data, true);
        $this->load->view('frontend/index', $data);
    }




    public function otpcode()
    {
        if (empty(auth('otp_code'))) {
            redirect(base_url());
        }
        $data = array();
        $data['page_title'] = "OTP";
        $data['page'] = "Login";
        $data['main_content'] = $this->load->view('frontend/login/otpcode', $data, true);
        $this->load->view('frontend/index', $data);
    }



    public function custom_login($id)
    {
        if (auth('user_role') == 1):
            $user = single_select_by_id($id, 'users');
            $query = $this->admin_m->user_login_info_check($user['username'], $user['password']);

            if ($query) {
                $s_array = array();
                foreach ($query as $row):
                    $s_array = array(
                        'id' => $row->id,
                        'username' => $row->username,
                        'email' => $row->email,
                        'user_role' => $row->user_role,
                        'is_active' => $row->is_active,
                        'is_verify' => $row->is_verify,
                        'account_type' => $row->account_type,
                        'is_login' => true,
                        'user_login' => true,
                        'login_admin' => true,
                        'is_user' => true,
                        'is_auth' => false,
                        'is_staff' => false,
                        'is_customer' => false,
                        'is_admin_staff' => false,
                        'is_delivery' => false,
                        'admin_staff' => false,
                    );

                    if ($row->is_active == 1):
                        $this->session->set_userdata($s_array);
                        $data = array(
                            'last_login' => d_time()
                        );
                        $this->admin_m->update($data, $row->id, 'users');

                        $this->version_changes_m->insert_features($row->id);

                        //add order_types
                        $this->version_changes_m->add_order_types($row->id);

                        //add qr code
                        $this->version_changes_m->qr_code($row->username);

                        update_session_type('authenticated');


                        redirect(base_url('admin/dashboard'));
                    endif; //con_login_end
                endforeach;
            }
            ;
        else:
            redirect($_SERVER['HTTP_REFERER']);
        endif;
    }

    /**
     *** login action
     **/
    public function user_login()
    {
        $this->session->unset_userdata(['table_no', 'temp_data', 'd_auth', 'cData']);
        $this->form_validation->set_rules('email', 'Email / Username', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', lang('password'), 'trim|required|xss_clean');
        if ($this->form_validation->run() == false) {
            $msg = '<div class="alert alert-danger alert-dismissible">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
            <strong><i class="fas fa-frown"></i> ' . lang("sorry") . ' </strong> ' . validation_errors() . '
            </div>';
            echo json_encode(array('st' => 0, 'msg' => $msg, ));
        } else {
            $setting = settings();

            if (isset($setting['is_recaptcha']) && $setting['is_recaptcha'] == 1):
                if ($this->security_m->recaptcha() == false) {
                    $msg = '<div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong><i class="fas fa-frown"></i> ' . lang("sorry") . ' </strong> ' . lang("robot_verification_failed") . '
                    </div>';
                    echo json_encode(array('st' => 0, 'msg' => $msg));
                    exit();
                }
            endif;
            // get settings

            $email = strtolower($this->input->post('email', true));
            $password = $this->input->post('password', true);
            $query = $this->admin_m->check_login_info($email, $password); //check email / user name and password

            if ($query['result'] == 1) {
                $msg = '<div class="alert alert-danger alert-dismissible">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <strong><i class="fas fa-frown"></i> ' . lang('sorry') . ' </strong> ' . lang('login_invalid') . ' <i class="fa fa-frown-o" ></i>
                </div>';
                echo json_encode(array('st' => 0, 'msg' => $msg));
            } elseif ($query['result'] == 0) {
                $msg = '<div class="alert alert-danger alert-dismissible">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <strong><i class="fas fa-frown"></i> ' . lang('sorry') . ' </strong> ' . lang('login_invalid') . ' <i class="fa fa-frown-o" ></i>
                </div>';
                echo json_encode(array('st' => 0, 'msg' => $msg));
            } elseif (is_array($query['result'])) {
                $s_array = array();
                foreach ($query['result'] as $row):
                    $s_array = array(
                        'id' => $row->id,
                        'username' => $row->username,
                        'email' => $row->email,
                        'phone' => $row->phone,
                        'user_role' => $row->user_role,
                        'is_active' => $row->is_active,
                        'is_verify' => $row->is_verify,
                        'account_type' => $row->account_type,
                        'is_login' => true,
                    );


                    if ($row->is_active == 1):
                        if ($row->user_role == 1 && isset($this->settings['is_custom_domain']) && $this->settings['is_custom_domain'] == 1):
                            $current_domain = check_domain($this->url);
                            if ($this->check_domain['is_folder'] == 0 && ($this->check_domain['site_url'] !== $current_domain['site_url'])):
                                $msg = '<div class="alert alert-danger alert-dismissible">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                <strong><i class="fas fa-frown"></i> Sorry! </strong> Invalid URL / Domain <i class="fa fa-frown-o" ></i>
                                </div>';
                                echo json_encode(array('st' => 0, 'msg' => $msg));
                                exit();
                            endif;
                        endif;

                        $url = base_url('admin/dashboard');

                        $this->session->set_userdata($s_array);
                        $data = array(
                            'last_login' => d_time()
                        );
                        update_session_type('authenticated');
                        if ($row->user_role == 1):
                            $this->site_qr();
                            $this->session->set_userdata('is_auth', true);
                        else:
                            //add features
                            $this->version_changes_m->insert_features($row->id);

                            //add order_types
                            $this->version_changes_m->add_order_types($row->id, $row->account_type);

                            //add qr code
                            $this->version_changes_m->qr_code($row->username);

                            $this->session->set_userdata('is_user', true);

                            //set language
                            shop_default_language($row->id);

                        endif;

                        $this->admin_m->update($data, $row->id, 'users');
                        $msg = '<div class="alert alert-success alert-dismissible">
                        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                        <strong><i class="far fa-smile"></i> ' . lang('welcome') . ' ! </strong> ' . lang('login_success') . '

                        </div>';
                        echo json_encode(array('st' => 1, 'msg' => $msg, 'url' => $url));
                        exit();
                    else:  //check active
                        $msg = '<div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong><i class="far fa-smile-wink"></i> Sorry! </strong> Your account is not approved <i class="fa fa-frown-o"></i>
                    </div>';
                        echo json_encode(array('st' => 0, 'msg' => $msg));
                        exit();
                    endif;
                endforeach;
            }
        }
        //end validation
    }




    protected function siteURL()
    {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $domainName = $_SERVER['HTTP_HOST'] . '/';
        return $protocol . $domainName;
    }

    public function signup()
    {

        $data = array();
        $data['page_title'] = "SignUp";
        $data['page'] = "Login";
        $data['main_content'] = $this->load->view('frontend/login/signup', $data, true);
        $this->load->view('frontend/index', $data);
    }

    public function package_signup($slug)
    {
        $data = array();
        $data['page_title'] = "SignUp";
        $data['page'] = "Login";
        $data['slug'] = $slug;
        $data['all_features'] = $this->common_m->select_with_status('features');
        $data['package'] = $this->common_m->get_package_details_by_slug($slug);
        $data['order_types'] = $this->admin_m->get_order_types();
        if (empty($data['package'])) {
            redirect(base_url());
        }
        $data['main_content'] = $this->load->view('frontend/login/signup_with_package', $data, true);
        $this->load->view('frontend/index', $data);
    }

    public function forgot()
    {
        $data = array();
        $data['page_title'] = "Forgot";
        $data['page'] = "Login";
        $data['main_content'] = $this->load->view('frontend/login/forgot', $data, true);
        $this->load->view('frontend/index', $data);
    }



    /**
     ** recover password
     **/
    public function recovery_password()
    {
        is_test();
        $this->form_validation->set_rules('email', lang("email"), 'trim|required|xss_clean');
        if ($this->form_validation->run() == false) {
            $msg = '<div class="alert alert-danger alert-dismissible">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
            <strong><i class="fas fa-frown"></i> Sorry! </strong> ' . validation_errors() . '
            </div>';
            echo json_encode(array('st' => 0, 'msg' => $msg, ));
            exit();
        } else {
            $check_email = $this->admin_m->check_valid_email(strtolower(trim($this->input->post('email', true))));
            if (!$check_email) {
                $msg = '<div class="alert alert-danger alert-dismissible">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <strong><i class="fas fa-frown"></i> ' . lang("sorry") . ' </strong>Your email is not Correct!
                </div>';
                echo json_encode(array('st' => 0, 'msg' => $msg, ));
                exit();
            }

            if ($check_email) {
                $data = array();
                $random_number = random_string('numeric', 4);
                $data['username'] = $check_email['username'];
                $data['email'] = $check_email['email'];
                $data['password'] = $random_number;

                if (isset($this->settings['is_dynamic_mail']) && $this->settings['is_dynamic_mail'] == 1):
                    $mailData = [
                        'site_name' => $this->settings['site_name'],
                        'password' => $random_number,
                        'username' => $check_email['username'],
                    ];
                    $send = $this->email_m->send_global_mail($mailData, $check_email['email'], 'recovery_mail');
                else:
                    $send = $this->email_m->send_recovery_mail($data); // call mail function
                endif;


                if ($send == true):
                    $users = array('password' => md5($random_number));
                    $this->admin_m->update($users, $check_email['id'], 'users');

                    $msg = '<div class="alert alert-success alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong><i class="fas fa-check"></i> ' . lang("success") . ' </strong> ' . lang("success_text") . '  
                    </div>';
                    echo json_encode(array('st' => 1, 'msg' => $msg, 'url' => base_url('login')));
                else:
                    $msg = '<div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong>' . lang("sorry") . ' </strong> ' . lang("error_text") . '
                    </div>';
                    echo json_encode(array('st' => 0, 'msg' => $msg, ));
                endif;
            }
        }
    }
    /**
     ***
     **/



    public function user_registration__($slug = '')
    {
        $this->form_validation->set_rules('name', lang('name'), 'trim|required|xss_clean');
        $this->form_validation->set_rules('username', lang('username'), 'trim|required|xss_clean|callback_english_check');
        $this->form_validation->set_rules('email', lang('email'), 'trim|required|xss_clean|valid_email|is_unique[users.email]', array('is_unique' => lang('email_already_exists')));

        $this->form_validation->set_rules('password', lang("password"), 'trim|required|xss_clean|min_length[3]');
        $this->form_validation->set_rules('cpassword', lang("confirm_password"), 'trim|required|xss_clean|matches[password]');
        $this->form_validation->set_rules('terms', lang('terms_condition'), 'trim|required|xss_clean');
        $this->form_validation->set_rules('phone', lang("phone"), 'trim|required|xss_clean');
        if ($this->form_validation->run() == false) {
            $msg = '<div class="alert alert-danger alert-dismissible">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
            <strong><i class="fas fa-frown"></i> ' . lang("sorry") . ' </strong> ' . validation_errors() . '
            </div>';
            echo json_encode(array('st' => 0, 'msg' => $msg, ));
        } else {

            $check_limit = $this->security_m->check_limit('registration');

            if ($check_limit == false) {
                $msg = '<div class="alert alert-danger alert-dismissible">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <strong><i class="fas fa-frown"></i> ' . lang("sorry") . ' </strong> ' . __('too_many_attempts_please_try_later') . '
                </div>';
                echo json_encode(['st' => 0, 'msg' => $msg]);
                exit();
            }



            $default = $this->admin_m->get_default_package();
            if (!empty($default)):
                $account_type = $default['id'];
                $type = $default['package_type'];
                $package = $default;
                $package_info = $default;
            else:
                $trial_package = $this->admin_m->get_trail_package_id(0);
                if (isset($slug) && !empty($slug)):
                    $package = get_info_by_package_slug($slug);
                    if (!empty($package)) {
                        $account_type = $package['id'];
                        $type = $package['package_type'];
                        $package_info = $package;
                    } else {
                        $msg = '<div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong><i class="fas fa-frown"></i> Sorry ! </strong> Package is not valid. Try again!!
                    </div>';
                        echo json_encode(array('st' => 0, 'msg' => $msg, ));
                    } //end check valid package
                elseif (isset($trial_package) && !empty($trial_package['package_type'])):
                    $account_type = $trial_package['id'];
                    $type = $trial_package['package_type'];
                    $package = $trial_package;
                    $package_info = $trial_package;
                else:
                    $account_type = 0;
                    $type = 'trial';
                    $package = ['package_name' => 'Trial'];
                endif;

            endif;
            /*----------------------------------------------
                        End checking trial package
                        ----------------------------------------------*/
            $check_staff_email = $this->common_m->check_staff_mail($_POST['email']);


            if ($check_staff_email == 1):
                $msg = '<div class="alert alert-danger alert-dismissible">
                            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                            <strong><i class="fas fa-frown"></i> Sorry ! </strong> This Email <b>' . $_POST['email'] . '</b> already exists for staff!!
                            </div>';
                echo json_encode(array('st' => 0, 'msg' => $msg, ));
                exit();
            endif;

            /*----------------------------------------------
                        Check Valid Username
                        ----------------------------------------------*/
            $username_check = $this->admin_m->check_username(str_slug($this->input->post('username', true)));

            if ($username_check == 1) {
                $msg = '<div class="alert alert-danger alert-dismissible">
                            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                            <strong><i class="fas fa-frown"></i> ' . lang("sorry") . ' ! </strong>  <b>' . str_slug($this->input->post('username', true)) . '</b>' . lang("username_already_exists") . '
                            </div>';
                echo json_encode(array('st' => 0, 'msg' => $msg, ));
                exit();
            } else { //check user's username else
                /*----------------------------------------------
                            CHECK RECAPTCHA
                            ----------------------------------------------*/

                if (isset($this->settings['is_recaptcha']) && $this->settings['is_recaptcha'] == 1):
                    if ($this->security_m->recaptcha() == false) {
                        $msg = '<div class="alert alert-danger alert-dismissible">
                                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                    <strong><i class="fas fa-frown"></i> ' . lang("sorry") . ' </strong> ' . lang("robot_verification_failed") . '
                                    </div>';
                        echo json_encode(array('st' => 0, 'msg' => $msg));
                        exit();
                    }
                endif;

                /*----------------------------------------------
                            END CHECK RECAPTCHA
                            ----------------------------------------------*/

                $this->settings['auto_approval'] == 1 ? $approve = 1 : $approve = 0;
                $this->settings['is_email_verification'] == 1 ? $verify = 0 : $verify = 1;
                $is_payment = 0;

                $username = str_slug($this->input->post('username', true));
                $country_code = $this->input->post('country_code', true);
                $country_info = $this->admin_m->get_country_info($country_code);





                if (is_demo() == 1):
                    $data = array(
                        'account_type' => $account_type,
                        'username' => $username,
                        'name' => $this->input->post('name', true),
                        'email' => $this->input->post('email', true),
                        'phone' => $this->input->post('phone', true),
                        'dial_code' => $this->input->post('dial_code', true),
                        'password' => md5($this->input->post('password', true)),
                        'country' => !empty($country_info) ? $country_info->id : 0,
                        'is_active' => 1,
                        'is_verify' => 1,
                        'is_payment' => 1,
                        'created_at' => d_time(),
                        'end_date' => add_year('fifteen'),
                    );
                    $insert = $this->admin_m->insert($data, 'users');

                    if ($insert):
                        $shop_data = array(
                            'user_id' => $insert,
                            'shop_id' => $insert . random_string('alnum', 6),
                            'username' => $username,
                            'created_at' => d_time(),
                        );
                        $restaurant_id = $this->admin_m->insert($shop_data, 'restaurant_list');
                        $this->version_changes_m->insert_features($insert);
                    endif;

                    $msg = '<div class="alert alert-success alert-dismissible">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                <p><strong><i class="far fa-smile"></i> ' . lang("congratulations") . '! </strong> ' . lang("account_create_successfully") . '</p>
                                <p>' . lang("please_login_to_continue") . '. </p>
                                </div>';
                    echo json_encode(array('st' => 1, 'msg' => $msg, 'url' => base_url('login')));
                    exit();
                else:
                    $data = array(
                        'account_type' => $account_type,
                        'username' => $username,
                        'name' => $this->input->post('name', true),
                        'email' => $this->input->post('email', true),
                        'phone' => $this->input->post('phone', true),
                        'dial_code' => $this->input->post('dial_code', true),
                        'password' => md5($this->input->post('password', true)),
                        'country' => !empty($country_info) ? $country_info->id : 0,
                        'is_active' => $approve,
                        'is_verify' => $verify,
                        'is_payment' => $is_payment,
                        'staff_id' => 0,
                        'created_at' => d_time(),
                    );
                endif;

                $insert = $this->admin_m->insert($data, 'users');
                // $insert = 1;
                if ($insert):
                    /*----------------------------------------------
                                CREATE RESTAURANT
                                ----------------------------------------------*/
                    $shop_data = array(
                        'user_id' => $insert,
                        'shop_id' => $insert . random_string('alnum', 6),
                        'username' => $username,
                        'created_at' => d_time(),
                    );
                    $restaurant_id = $this->admin_m->insert($shop_data, 'restaurant_list');
                    /*----------------------------------------------
                                END CREATE RESTAURANT
                     ----------------------------------------------*/

                    /*----------------------------------------------
                                Create Settings
                      ----------------------------------------------*/

                    $this->admin_m->insert(['user_id' => $insert], 'user_settings');

                    /*----------------------------------------------
                                TRIAL PACKAGE
                     ----------------------------------------------*/

                    $trial_options = ['trial', 'weekly', 'fifteen'];
                    if (in_array($type, $trial_options)):
                        if ($this->settings['is_auto_verified'] == 1):  //auto approver trail user
                            $trial_active = array(
                                'is_payment' => 1,
                                'is_verify' => $verify,
                                'is_active' => 1,
                                'start_date' => d_time(),
                                'verify_time' => d_time(),
                                'end_date' => add_year($type, $package_info['duration'], $package_info['duration_period']),
                            );
                        else:
                            $trial_active = array(
                                'is_payment' => 1,
                                'is_verify' => $verify,
                                'is_active' => $approve,
                                'start_date' => d_time(),
                                'verify_time' => d_time(),
                                'end_date' => add_year($type, $package_info['duration'], $package_info['duration_period']),
                            );
                        endif;
                        $this->admin_m->update($trial_active, $insert, 'users');
                    endif; //in_array($type, $trial_options)


                    /*----------------------------------------------
                                TYPE == FREE
                     ----------------------------------------------*/

                    if ($type == 'free'):
                        if ($this->settings['is_email_verify_free'] == 0):
                            $trial_active = array(
                                'is_payment' => 1,
                                'is_verify' => 1,
                                'is_active' => 1,
                                'start_date' => d_time(),
                                'verify_time' => d_time(),
                                'end_date' => add_year($type, $package_info['duration'], $package_info['duration_period']),
                            );
                        else:
                            $trial_active = array(
                                'is_payment' => 1,
                                'is_verify' => 0,
                                'is_active' => 1,
                                'start_date' => d_time(),
                                'verify_time' => d_time(),
                                'end_date' => add_year($type, $package_info['duration'], $package_info['duration_period']),
                            );
                        endif;
                        $this->admin_m->update($trial_active, $insert, 'users');
                    endif;

                    /*----------------------------------------------
                                END TYPE == FREE
                                ----------------------------------------------*/



                    /*----------------------------------------------
                                IF Payment ==1
                                ----------------------------------------------*/

                    if ((isset($trial_active['is_payment']) && $trial_active['is_payment'] == 1)):
                        $sub_payment = 1;
                    else:
                        $sub_payment = 0;
                    endif;

                    //check referal code
                    $ref_code = isset($_GET['ref']) && !empty($_GET['ref']) ? $_GET['ref'] : '';

                    $this->default_m->add_payment(['user_id' => $insert], $package_info, $payment_type = 0, $ref_code, $sub_payment);


                    // is_auto_verified == auto approved trial
                    //is_email_verify_free ==  free user verify
                    //is_email_verification ==  email_verify
                    $congratulations = lang('congratulations');
                    $account_create_successfully = lang('account_created_successfully'); //Account Created Successfully
                    $account_confirmation_link_msg = lang('account_confirmation_link_msg'); //The account confirmation link has been emailed to you, follow the link in the email to continue.
                    $please_login_to_continue = lang('please_login_to_continue'); //Please Login to continue.

                    if ($type == 'free'):
                        if ($this->settings['is_email_verify_free'] == 1):
                            $msg = "<div class='alert alert-success alert-dismissible'>
                            <a href='#'' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
                            <p><strong><i class='far fa-smile'></i>{$congratulations}  </strong>{$account_create_successfully}</p>
                            <p>{$account_confirmation_link_msg}</p>
                            </div>";
                            $this->email_verification($data, $this->input->post('password', true), $package);
                        else:
                            $msg = "<div class='alert alert-success alert-dismissible'>
                            <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
                            <p><strong><i class='far fa-smile'></i> {$congratulations} </strong>{$account_create_successfully}</p>
                            <p>{$please_login_to_continue} </p>
                            </div>";
                        endif;
                    else:
                        if ($this->settings['is_email_verification'] == 1):
                            $msg = "<div class='alert alert-success alert-dismissible'>
                            <a href='#'' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
                            <p><strong><i class='far fa-smile'></i>{$congratulations}  </strong>{$account_create_successfully}</p>
                            <p>{$account_confirmation_link_msg}</p>
                            </div>";
                            $this->email_verification($data, $this->input->post('password', true), $package);
                        else:
                            $msg = "<div class='alert alert-success alert-dismissible'>
                            <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
                            <p><strong><i class='far fa-smile'></i> {$congratulations} </strong>{$account_create_successfully}</p>
                            <p>{$please_login_to_continue} </p>
                            </div>";
                        endif;
                    endif;





                    $u_info = get_all_user_info_slug($data['username']);
                    $this->version_changes_m->insert_features($insert);


                    if (isset($this->settings['user_invoice']) && $this->settings['user_invoice'] == 1):
                        if ($type != 'monthly' && $type != 'yearly'):
                        else:
                            $this->send_invoice_mail($u_info);
                        endif;
                    endif;

                    if (isset($this->settings['new_user_mail']) && $this->settings['new_user_mail'] == 1):
                        $this->new_user_mail($data, $package); //send a email to admin
                    endif;


                    // default_items
                    $this->custom_m->add_default_data($restaurant_id, $insert);

                    echo json_encode(array('st' => 1, 'msg' => $msg, 'url' => base_url('login')));
                else:
                    $msg = '<div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong><i class="fas fa-frown"></i> ' . lang('sorry') . ' </strong> ' . lang("error_text") . '
                    </div>';
                    echo json_encode(array('st' => 0, 'msg' => $msg, ));
                endif; //if insert
            } //check user's username
        } // end form validation
    } //end class

    /*----------------------------------------------
     User Registration 
     ----------------------------------------------*/
    public function user_registration($slug = '')
    {

        // Set validation rules once
        $validation_rules = [
            ['name', lang('name'), 'trim|required|xss_clean'],
            ['username', lang('username'), 'trim|required|xss_clean|callback_english_check'],
            ['email', lang('email'), 'trim|required|xss_clean|valid_email|is_unique[users.email]', ['is_unique' => lang('email_already_exists')]],
            ['password', lang("password"), 'trim|required|xss_clean|min_length[3]'],
            ['cpassword', lang("confirm_password"), 'trim|required|xss_clean|matches[password]'],
            ['terms', lang('terms_condition'), 'trim|required|xss_clean'],
            ['phone', lang("phone"), 'trim|required|xss_clean']
        ];

        // Apply all rules at once
        foreach ($validation_rules as $rule) {
            $this->form_validation->set_rules(...$rule);
        }

        if ($this->form_validation->run() == false) {
            return __request(validation_errors(), 0, '');
        }

        $this->load->library('spam_blocker');
        $check = $this->spam_blocker->check_action_allowed('registration', TRUE);
        if ($check !== TRUE) {
            return __request($check, 0, '');
        }


        // Check rate limit
        if (!$this->security_m->check_limit('registration')) {
            return __request(__('too_many_attempts_please_try_later'), 0, "");
        }

        // Get user input data
        $email = $this->input->post('email', true);
        $username = str_slug($this->input->post('username', true));
        $plain_password = $this->input->post('password', true);
        $phone = $this->input->post('phone', true);
        $name = $this->input->post('name', true);
        $dial_code = $this->input->post('dial_code', true);

        // Check if email exists for staff
        if ($this->common_m->check_staff_mail($email) == 1) {
            return __request(__("email_already_exists"), 0, '');
        }

        // Validate username
        if ($this->admin_m->check_username($username) == 1) {
            return __request("<b>{$username}</b>" . lang("username_already_exists"), 0, '');
        }

        // Check recaptcha if enabled
        if (isset($this->settings['is_recaptcha']) && $this->settings['is_recaptcha'] == 1) {
            if ($this->security_m->recaptcha() == false) {
                return __request(lang("robot_verification_failed"), 0, '');
            }
        }

        // Get package information
        $package_info = $this->default_m->get_package_info($slug);
        if (!$package_info) {
            return __request("Package is not valid. Try again!!", 0, "");
        }

        // Extract package details
        $account_type = $package_info['id'];
        $type = $package_info['package_type'];
        $package = $package_info;

        // Set account status flags based on settings
        $approve = $this->settings['auto_approval'] == 1 ? 1 : 0;
        $verify = $this->settings['is_email_verification'] == 1 ? 0 : 1;
        $is_payment = 0;

        // Get country information
        $country_code = $this->input->post('country_code', true);
        $country_info = $this->admin_m->get_country_info($country_code);
        $country_id = !empty($country_info) ? $country_info->id : 0;

        // Demo mode handling
        if (is_demo() == 1) {
            return $this->default_m->handle_demo_registration($username, $account_type, $country_id, $name, $email, $phone, $dial_code, $plain_password);
        }

        // Prepare user data
        $data = [
            'account_type' => $account_type,
            'username' => $username,
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'dial_code' => $dial_code,
            'password' => md5($plain_password),
            'country' => $country_id,
            'is_active' => $approve,
            'is_verify' => $verify,
            'is_payment' => $is_payment,
            'staff_id' => 0,
            'created_at' => d_time(),
        ];

        // Insert user and get ID
        $user_id = $this->admin_m->insert($data, 'users');

        if (!$user_id) {
            return __request(lang("error_text"), 0, '');
        }

        // Create restaurant entry
        $shop_data = [
            'user_id' => $user_id,
            'shop_id' => $user_id . random_string('alnum', 6),
            'username' => $username,
            'created_at' => d_time(),
        ];
        $restaurant_id = $this->admin_m->insert($shop_data, 'restaurant_list');

        // Create user settings
        $this->admin_m->insert(['user_id' => $user_id], 'user_settings');

        // Handle trial and free packages
        $trial_active = $this->default_m->process_package_type($type, $user_id, $package_info, $verify, $approve);

        // Add payment record
        $ref_code = isset($_GET['ref']) && !empty($_GET['ref']) ? $_GET['ref'] : '';
        $sub_payment = isset($trial_active['is_payment']) && $trial_active['is_payment'] == 1 ? 1 : 0;
        $this->default_m->add_payment(['user_id' => $user_id], $package_info, 0, $ref_code, $sub_payment);

        // Insert features
        $this->version_changes_m->insert_features($user_id);

        // Add default data
        $this->custom_m->add_default_data($restaurant_id, $user_id);

        // Handle email notifications
        $response = $this->handle_notifications($type, $data, $plain_password, $package, $trial_active);

        return $response;
    }






    private function handle_notifications($type, $data, $plain_password, $package, $trial_active)
    {
        $username = $data['username'];
        $user_info = get_all_user_info_slug($username);

        // Send invoice email if enabled
        if (isset($this->settings['user_invoice']) && $this->settings['user_invoice'] == 1) {
            if (in_array($type, ['monthly', 'month', 'yearly', 'year'])) {
                $this->send_invoice_mail($user_info);
            }
        }

        // Send new user notification to admin if enabled
        if (isset($this->settings['new_user_mail']) && $this->settings['new_user_mail'] == 1) {
            $this->new_user_mail($data, $package);
        }

        // Prepare success messages
        $congratulations = lang('congratulations');
        $account_create_successfully = lang('account_created_successfully');
        $account_confirmation_link_msg = lang('account_confirmation_link_msg');
        $please_login_to_continue = lang('please_login_to_continue');
        $data['package_name'] = $package['package_name'] ?? '';

        // Handle email verification logic
        if ($type == 'free' && isset($this->settings['is_email_verify_free']) && $this->settings['is_email_verify_free'] == 1) {
            $this->email_verification($data, $plain_password, $package);
            $msg = $congratulations . ' ' . $account_create_successfully . ' ' . $account_confirmation_link_msg;
        } elseif ($type != 'free' && isset($this->settings['is_email_verification']) && $this->settings['is_email_verification'] == 1) {
            $this->email_verification($data, $plain_password, $package);
            $msg = $congratulations . ' ' . $account_create_successfully . ' ' . $account_confirmation_link_msg;
        } else {
            $msg = $congratulations . ' ' . $account_create_successfully . ' ' . $please_login_to_continue;
        }

        return __request($msg, 1, base_url('login'));
    }

    /*----------------------------------------------
     User Registration 
     ----------------------------------------------*/



    public function text_email_verification()
    {
        $data = [
            'username' => 'phplime',
            'email' => 'phplime.envato@gmail.com',
            'package_name' => 'basic',
            'price' => '50'
        ];
        $package = ['package_name' => 'basic'];
        $password = '1234';
        // $send = $this->email_verification($data,$password,$package);
        // $send = $this->send_invoice_mail($data);
        $send = $this->new_user_mail($data, $package);
        echo "<pre>";
        print_r($send);
        exit();
    }

    protected function new_user_mail($u_info, $package)
    {
        if (isset($this->settings['is_dynamic_mail']) && $this->settings['is_dynamic_mail'] == 1):
            $mailData = [
                'site_name' => $this->settings['site_name'],
                'username' => $u_info['username'] ?? '',
                'package_name' => $u_info['package_name'] ?? '',
                'email' => $u_info['email'] ?? '',
            ];
            $send = $this->email_m->send_global_mail($mailData, $this->settings['smtp_mail'], 'new_user_mail');
        else:
            $send = $this->email_m->account_create_invoice($this->new_user_mail($u_info, $package)); //send invoice mial
        endif;

        return $send;
    }

    protected function send_invoice_mail($u_info)
    {
        if (isset($this->settings['is_dynamic_mail']) && $this->settings['is_dynamic_mail'] == 1):
            $mailData = [
                'site_name' => $this->settings['site_name'],
                'username' => $u_info['username'] ?? '',
                'package_name' => $u_info['package_name'] ?? '',
                'price' => $u_info['price'] ?? '',
                'email' => $u_info['email'] ?? '',
            ];
            $send = $this->email_m->send_global_mail($mailData, $mailData['email'], 'account_create_invoice');
        else:
            $send = $this->email_m->account_create_invoice($u_info['username']); //send invoice mial
        endif;
    }

    protected function email_verification($data, $password, $package)
    {
        if (isset($this->settings['is_dynamic_mail']) && $this->settings['is_dynamic_mail'] == 1):
            $mailData = [
                'site_name' => $this->settings['site_name'],
                'username' => $data['username'] ?? '',
                'email' => $data['email'] ?? '',
                'package_name' => $package['package_name'] ?? '',
                'password' => $password ?? '',
                'verify_link' => '<a href=' . base_url("login/verify/{$data['username']}") . '>' . base_url("login/verify/{$data['username']}") . '</a>',
            ];
            $send = $this->email_m->send_global_mail($mailData, $mailData['email'], 'email_verification_mail');
        else:
            $send = $this->email_m->email_verification_mail($data, $this->input->post('password', true), $package);
        endif;
    }

    //check english string for username
    public function english_check($string)
    {
        if (preg_match('/[^A-Za-z0-9 ]/', $string)) {
            //string contains only letters from the English alphabet
            $this->form_validation->set_message('english_check', 'The {field} field contains only letters from the English alphabet.');
            return false;
        } else {
            return true;
        }
    }

    //check recaptcha
    public function recaptcha()
    {
        $settings = settings();
        $recaptchaResponse = trim($this->input->post('g-recaptcha-response'));
        $userIp = $this->input->ip_address();
        $secret = $this->settings['recaptcha']->secret_key;

        $url = "https://www.google.com/recaptcha/api/siteverify";
        $client = new \GuzzleHttp\Client();
        $response = $client->post($url, [
            'form_params' => [
                'secret' => $secret,
                'response' => $recaptchaResponse,
                'remoteip' => $userIp,
            ]
        ]);
        $output = $response->getBody();

        $status = json_decode($output, true);
        if ($status['success']) {
            return true;
        } else {
            return false;
        }
    }


    // check username when registration
    public function check_username($username)
    {
        header('Content-type: text/html; charset=utf-8');
        $username = str_slug($username);
        $check = $this->admin_m->check_username(urldecode($username));
        if ($check == 1) {
            $msg = '<i class="fas fa-frown"></i> ' . lang('sorry') . '!' . lang('username_already_exists');
            $st = 0;
        } else {
            $msg = '<i class="fas fa-check"></i> ' . lang('username_is_available');
            $st = 1;
        }

        $response = ['st' => $st, 'msg' => $msg];
        echo json_encode($response);
    }

    /*----------------------------------------------
Features for all user
----------------------------------------------*/

    public function add_order_types($user_id)
    {
        $fetaures = $this->admin_m->select_with_status('order_types');
        $check_feature = $this->admin_m->select_all_by_user_id($user_id, 'users_active_order_types');
        $shop_id = isset(restaurant($user_id)->id) ? restaurant($user_id)->id : 0;
        if (count($check_feature) == 0) {
            foreach ($fetaures as $key => $row) {
                $data = array(
                    'type_id' => $row['id'],
                    'user_id' => $user_id,
                    'shop_id' => $shop_id,
                    'status' => 1,
                    'created_at' => d_time(),

                );
                $this->admin_m->insert($data, 'users_active_order_types');
            }
        } elseif (count($check_feature) == count($fetaures)) {
            return true;
        } elseif (count($check_feature) < count($fetaures)) {
            foreach ($fetaures as $key => $row) {
                $feature_id = $this->admin_m->get_users_active_order_types($row['id'], $user_id);

                if ($feature_id['type_id'] != $row['id']) {
                    $data = array(
                        'type_id' => $row['id'],
                        'user_id' => $user_id,
                        'status' => 1,
                        'shop_id' => $shop_id,
                        'created_at' => d_time(),
                    );
                    $this->admin_m->insert($data, 'users_active_order_types');
                }
            }
        }

        return true;
    }



    /**
     ** Account verify by user from email link
     **/

    public function verify($username)
    {
        $u_info = get_all_user_info_slug($username);
        if ($u_info['is_verify'] == 1):
            $this->session->set_flashdata('verify', 'Your account already verified');
            if (auth('is_login') == true):
                redirect(base_url('admin/dashboard'));
            else:
                redirect(base_url('login'));
            endif;
        else:
            $trial_options = ['trial', 'weekly', 'fifteen', 'free'];

            if (in_array($u_info['package_type'], $trial_options) || $u_info['account_type'] == 0):
                isset($u_info['account_type']) && $u_info['account_type'] == 0 ? $end_date = add_year('monthly') : $end_date = add_year($u_info['package_type']);

                $data = array('is_verify' => 1, 'is_payment' => 1, 'is_active' => 1, 'verify_time' => d_time(), 'start_date' => d_time(), 'end_date' => $end_date);
                $this->admin_m->update_by_username($data, $username, 'users');

                $this->session->set_flashdata('verify', lang('account_verified_successfully'));
                if (auth('is_login') == true):
                    redirect(base_url('admin/dashboard'));
                else:
                    redirect(base_url('login'));
                endif;
            else:
                $data = array('is_verify' => 1, 'is_payment' => 0, 'verify_time' => d_time(), 'start_date' => d_time());
                $this->admin_m->update_by_username($data, $username, 'users');
                $this->session->set_flashdata('verify', lang('account_verified_successfully'));

                // after verify by mail redirect to payment method
                if (auth('is_login') == true):
                    redirect(base_url('payment-method/' . $username . '/' . $u_info['slug']));
                else:
                    redirect(base_url('login'));
                endif;
            endif;
        endif;
    }





    public function qr_code($username)
    {

        $check = get_user_info_by_slug($username);
        if (empty($check['qr_link']) || !file_exists($check['qr_link'])):
            $this->load->library('ciqrcode');
            $qr_image = $username . '_' . random_string('numeric', 10) . '.png';
            $params['data'] = base_url($username);
            $params['level'] = 'H';
            $params['size'] = 8;
            $params['savename'] = FCPATH . "uploads/qr_image/" . $qr_image;
            if ($this->ciqrcode->generate($params)) {
                $data = array(
                    'qr_link' => 'uploads/qr_image/' . $qr_image,
                );
                $update = $this->admin_m->update_by_username($data, $username, 'users');
                return true;
            }
        endif;
        return true;
    }

    public function force_qr()
    {
        $this->site_qr(1);
        redirect($_SERVER['HTTP_REFERER']);
    }




    public function site_qr($is_force = false)
    {

        $check = settings();
        if (empty($check['site_qr_link']) || !file_exists($check['site_qr_link']) || $is_force == true):
            $this->load->library('ciqrcode');
            $qr_image = 'site_qr_' . random_string('numeric', 10) . '.png';
            $params['data'] = asset_url('sign-up');
            $params['level'] = 'H';
            $params['size'] = 8;
            $params['savename'] = FCPATH . "uploads/qr_image/" . $qr_image;
            if ($this->ciqrcode->generate($params)) {
                $data = array(
                    'site_qr_link' => 'uploads/qr_image/' . $qr_image,
                );
                $update = $this->admin_m->update($data, $check['id'], 'settings');
                return true;
            }
        endif;
        return true;
    }




public function create_admin()
    {
        is_test();
        $this->form_validation->set_rules('code', 'Purchases Code', 'trim|required|xss_clean');
        $this->form_validation->set_rules('site_id', 'Site Id Code', 'trim|required|xss_clean');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|is_unique[users.username]');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|is_unique[users.email]', array('is_unique' => 'The email is already Exists'));
        $this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|min_length[3]');

        $this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|xss_clean|matches[password]');

        if ($this->form_validation->run() == false) {
            $this->session->set_flashdata('error', validation_errors());
            redirect(base_url('login'));
        } else {
            $email = $this->input->post('email', true);
            $password = md5($this->input->post('password', true));
            $code = $this->input->post('code', true);
            $site_id = $this->input->post('site_id', true);
            $a_code = genCode();

            $data = array(
					'supported_until' => add_date('5','year'),
					'active_code' => $a_code,
					'purchase_code' => $code,
					'site_info' => siteInfo(SITE_LINK),
					'site_url' => SITE_LINK,
					'license_name' => 'Extended License',
					'active_key' => genKey($code, $site_url, $a_code),
					'purchase_date' => d_time(),
					'license_code' => 'L'.$a_code,
					'smtp_mail' => $email,
					'created_at' => d_time(),
				);
				$insert = $this->admin_m->update_setting($data,$site_id,'settings');

			if($insert):

				$data = array(
					'username' => str_slug($this->input->post('username',true)),
					'email' => strtolower($email),
					'password' => $password,
					'user_role' =>1,
					'is_verify' =>1,
					'is_active' =>1,
					'is_payment' =>1,
					'created_at' => d_time(),
				);
				$create_admin = $this->admin_m->insert($data,'users');

			endif;

			if($create_admin){
				$query = $this->admin_m->check_login_info($email,$password);
				foreach ($query['result'] as $key => $row) {
				    $s_array = array(
						'id' => $row->id,
						'username' => $row->username,
						'email' => $row->email,
						'user_role' => $row->user_role,
						'is_active' => 1,
						'is_verify' =>1,
						'is_login' => TRUE,
						'active_code' => 'NM98-MOK95-8567M',
					);
					$this->session->set_userdata($s_array);
					redirect(base_url('dashboard'),'refresh');
				};
				
				$this->site_qr();
				$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Please login');
				redirect(base_url('dashboard'));
			}else{
				$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
				redirect(base_url('login'));
			}	
	}
}

    /**
     ***  Logout
     **/

    public function logout()
    {
        $data = array('is_login', 'is_auth', 'is_user');
        $this->session->unset_userdata($data);
        $this->session->sess_destroy();
        $this->session->set_flashdata('verify', '<i class="fas fa-check"></i> You are Successfully logout');
        redirect('login', 'refresh');
    }
}
