<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class CoreController extends Controller
{

    /**
     * Instance of the main Request object.
     *
     * @var CLIRequest|IncomingRequest
     */
    protected $request;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var list<string>
     */
    protected $helpers = [];

    /**
     * Be sure to declare properties for any property fetch you initialized.
     * The creation of dynamic property is deprecated in PHP 8.2.
     */
    // protected $session;

    /**
     * @return void
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        // you dont have bussines here if you are not in session
        if (!isset($_SESSION['session_id']) or ! isset($_SESSION['practice_id']) or !isset( $_SESSION['user_id'] )) {
            redirect('logout');
        }
        // Preload any models, libraries, etc, here.

        // E.g.: $this->session = \Config\Services::session();
    }
    var $template = array(
        'table_open' => "<table class='table table-sm table-striped table-hover table-bordered table-condensed'>",
        'thead_open' => '<thead class=\'bg-indigo\'>',
        'thead_close' => '</thead>',
        'heading_row_start' => '<tr>',
        'heading_row_end' => '</tr>',
        'heading_cell_start' => '<th>',
        'heading_cell_end' => '</th>',
        'tbody_open' => '<tbody>',
        'tbody_close' => '</tbody>',
        'row_start' => '<tr>',
        'row_end' => '</tr>',
        'cell_start' => '<td>',
        'cell_end' => '</td>',
        'row_alt_start' => '<tr>',
        'row_alt_end' => '</tr>',
        'cell_alt_start' => '<td>',
        'cell_alt_end' => '</td>',
        'table_close' => '</table>'
    );
    var $template_nohead = array(
        'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
        'thead_open' => '<thead>',
        'thead_close' => '</thead>',
        'heading_row_start' => '<tr>',
        'heading_row_end' => '</tr>',
        'heading_cell_start' => '<th>',
        'heading_cell_end' => '</th>',
        'tbody_open' => '<tbody>',
        'tbody_close' => '</tbody>',
        'row_start' => '<tr>',
        'row_end' => '</tr>',
        'cell_start' => '<td>',
        'cell_end' => '</td>',
        'row_alt_start' => '<tr>',
        'row_alt_end' => '</tr>',
        'cell_alt_start' => '<td>',
        'cell_alt_end' => '</td>',
        'table_close' => '</table>'
    );
    public $data = array();


    public function mermsemr_api($in, $out) {
        $this->load->model('backend_model');
        // $out = array();
        return $this->backend_model->mermsemr_api($in, $out);
    }

    protected function smart_htmlspecialchars($str) {
        if (substr($str, 0, 1) == '<')
            return $str;
        return htmlspecialchars($str);
    }

    protected function loginUser($data, $out) {

        $data['action'] = MERMS_PROVIDERS_LOGIN;
        //  $data['mlog'] = $mlog;
        // $data['member_id'] = $_SESSION['member_id'];
        $this->load->model('backend_model');
        $out = array();
        $res = $this->backend_model->mermsemr_api($data, $out);

        $loginReturn = false;

        if ($res == PHP_LOGIN_OK && isset($out["practice_id"]) && $out["practice_id"] > 0) {
            $_SESSION['session_id'] = $out['sessionid']; // "";
            $_SESSION['username'] = $out['username']; // "";
            $_SESSION['practice_name'] = $out['practice_name'];
            $_SESSION['practice_code'] = "IFE0001A";
            $_SESSION['user_firstname'] = $out['firstname'];
            $_SESSION['user_lastname'] = $out['lastname'];
            $_SESSION['user_email'] = $out['email'];
            $_SESSION['user_id'] = $out['user_id'];
            $_SESSION['practice_id'] = $out['practice_id'];
            $_SESSION['user_provider'] = "1";
            $_SESSION['user_admin'] = "1";
            $loginReturn = true;
        } else {
            $data['error_message'] = "Invalid Username or Password";
        }


        return $loginReturn;
    }

    protected function getSessionArray() {
        $data['username'] = $_SESSION['username']; // = $this->input->post('username');
        $data['name'] = $_SESSION['name']; // = $this->input->post('username');
        $data['firstname'] = $_SESSION['firstname']; // = $ret->firstname;
        $data['lastname'] = $_SESSION['lastname']; // = $ret->lastname;
        $data['email'] = $_SESSION['email']; // = $ret->email;
        $data['member_id'] = $_SESSION['member_id'];

        $this->load->model('dash_model');
        $out = $this->dash_model->getDashData($data);
        $data['active_task'] = $out['active_task'];
        $data['active_pass_due'] = $out['active_pass_due'];
        $data['current_balance'] = $out['current_balance'];
        $data['new_message'] = $out['new_message'];
        $_SESSION["active_offers_count"] = $out['active_offers_count'];

        $data = $_SESSION['secure_data'];
        $data['member_id'] = $_SESSION['member_id']; // = $ret->email;

        $this->refreshAccountDetail($_SESSION['member_id']);
        return $data;
    }

    private function refreshAccountDetail($member_id) {

    }
    protected function logUser($mlog) {
        //
        $data['action'] = WRENCHBOARD_LOG_MEMBER;
        $data['mlog'] = $mlog;
        $data['member_id'] = $_SESSION['member_id'];
        $this->load->model('backend_model');
        $out = array();
        $res = $this->backend_model->mermsemr_api($data, $out);

        $this->load->model('userlog_model');
        $xy["member_id"] = $_SESSION['member_id'];
        $_SESSION['member_log'] = $this->userlog_model->loadUserLog($xy);
        //  print_r($out);
    }

    protected function myMessagesSnapshot() {

        $str = "<li class='media'>
                    <div class='media-left'>
                        <img src='/assets/images/placeholder.jpg' class='img-circle img-sm' alt=''>                        
                    </div>

                    <div class='media-body'>
                        <a href='#' class='media-heading'>
                            <span class='text-semibold'>System</span>
                            <span class='media-annotation pull-right'>00:00</span>
                        </a>

                        <span class='text-muted'>You have no pending messages</span>
                    </div>
                </li>";


        return $str;
    }

    protected function sql_escape_func($inp) {
        if (is_array($inp)) {
            return array_map(__METHOD__, $inp);
        }


        if (!empty($inp) && is_string($inp)) {
            return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
        }

        return $inp;
    }

    protected function findOffers($email) {
        $this->load->model('offers_model');
        $this->offers_model->attachOffers($email);
    }

    protected function home1($pagename = '') {
        $data['sitename'] = 'home';
        $res = $this->getExtJobList();

        $data['market_data'] = $res;

        $data['why_list'] = $this->getExtWhyList();


        //$this->load->view('templates/header_boxed', $data);
        //
        $this->load->view('home/view_index1', $data);


        //$this->load->view('users/view_external_footer');
    }

    protected function readFixedText($text_key) {

        $page_key = trim($text_key);
        $finaltxt = "";
        if ($page_key != '') {
            $mysql = "SELECT * FROM general_text WHERE page_key='$page_key'";
            $query = $this->db->query($mysql);
            if ($query->num_rows() == 0) {
                $finaltxt = "";
            } else {
                $row = $query->row();
                $finaltxt = $row->txt_detail;
            }
        }

        return $finaltxt;
    }

    protected function libraryContent($content_id) {
        $out = array();

        $query = $this->db->query("SELECT * FROM library WHERE id = " . $content_id);
        if ($query->num_rows() > 0) {
            $row = $query->row();

            $out['title'] = $row->title;
            $out['description'] = $row->description;
            $out['detail'] = $row->detail;
        }
        return $out;
    }

    protected function getExtJobList() {

        $mysql = "SELECT j.title,j.description,m.job_id,m.expire "
            . "FROM members_jobs_offer m "
            . "LEFT JOIN members_jobs j ON j.id=m.job_id "
            . "WHERE m.status = 1 AND m.client_id=0 "
            . "AND m.expire IS NOT NULL "
            . "AND  m.public_view = 1 "
            . "ORDER BY m.expire DESC LIMIT 6";
        $query = $this->db->query($mysql);
        return $query->result();
    }

    protected function getExtWhyList() {

        $mysql = "SELECT * FROM why ORDER BY flags DESC";
        $query = $this->db->query($mysql);
        return $query->result();
    }

    protected function renderProviderSecurePage($page_name, $data) {

        // you dont have bussines here if you are not in session
        if (!isset($_SESSION['session_id']) or ! isset($_SESSION['username']) or $_SESSION['username'] == '') {
            redirect('logout');
        }

        return view('template/provider_header', $data).
               view('provider/' . $page_name, $data).
               view('template/provider_footer', $data);
    }
}