<?php

require_once APP_DIR . 'libs/View.php';

require_once APP_DIR . 'libs/Input.php';

require_once APP_DIR . 'libs/Session.php';

require_once APP_DIR . 'models/AuthModel.php';
require_once APP_DIR . 'libs/Database.php';

require_once APP_DIR . 'libs/Pagination.php';

class EnquiriesController

{

    private $_view;
    private $_db;

    public function __construct()

    {

        check_login('index');

        $this->_view  = new View();
        $this->_db = new Database();
    }



    public function index()

    {

        $user_id = SESSION::get('uId');

        if (!empty($user_id)) {

            $authObj = new AuthModel();

            $login_user_data = $authObj->getUserDetails($user_id);

            $this->_view->setVal('login_user_data', $login_user_data);
        }

        $limit = isset($_GET['page_limit']) ?  $_GET['page_limit'] :  50;

        $page_num = isset($_GET['page_num']) ? $_GET['page_num'] : 1;

        $startAt = ($limit * ($page_num - 1));

        $live_data_list =  $live_data_pagination = [];

        $sql = "SELECT  count(*) as count  FROM " . CONTACT_FORM . " WHERE 1 ";


        $this->_db->query($sql);

        $live_data = $this->_db->single();

        $live_data_count = $live_data['count'];

        if ($live_data_count > 0) {

            $page_num = isset($_GET['page_num']) ? $_GET['page_num'] : 1;


            $startAt = ($limit * ($page_num - 1));


            $sql = "SELECT * FROM " . CONTACT_FORM . " WHERE 1  LIMIT " .  $startAt . ',' . $limit;

            $this->_db->query($sql);

            $live_data_list = $this->_db->getAll();

            $live_data_pagination  = new Pagination($live_data_count, $page_num, $limit, $startAt);
        }

        $this->_view->setVal('enquiries_count',  $live_data_count);
        $this->_view->setVal('enquiries_list',  $live_data_list);

        $this->_view->setVal('enquiries_pagination',  $live_data_pagination);

        $this->_view->setVal('meta_title', 'Enquiries Page');

        $this->_view->setVal('meta_description', 'Enquiries Page');

        $this->_view->setVal('meta_keyword', 'Enquiries Page');

        $this->_view->renderAdmin('enquiries-list');
    }

    //Delete Enquiry
    public function deleteEnquiry($id)
    {

        $retVal = false;

        $id = decryptData($id);

        if ($id > 0) {


            $sql = "DELETE FROM " . CONTACT_FORM . " WHERE 1  AND id = " . $id;




            $this->_db->query($sql);


            $retVal = $this->_db->execute();


            if ($retVal) {



                $type = 'success';



                $msg = 'Enquiry Successfully Deleted';
            } else {



                $type = 'error';



                $msg = 'Error In deleting Enquiry data';
            }
        } else {



            $type = 'error';



            $msg = 'Error In deleting Enquiry data';
        }


        set_session_alert($type, $msg);

        redirect(ADMIN_URL . 'enquiries');
    }

}
