<?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 SliderController
{

    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 " . SLIDER . " 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 " . SLIDER . " 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('start_counter',  $startAt);
        $this->_view->setVal('slider_data',  $live_data);
        $this->_view->setVal('slider_data_count',  $live_data_count);
        $this->_view->setVal('slider_data_list',  $live_data_list);
        $this->_view->setVal('slider_data_pagination',  $live_data_pagination);
        $this->_view->setVal('meta_title', 'Slider Page');
        $this->_view->setVal('meta_description', 'Slider Page');
        $this->_view->setVal('meta_keyword', 'Slider Page');
        $this->_view->renderAdmin('slider/slider-list');
    }

    public function delete($id)
    {
        $id = decryptData($id);
        $retVal = false;
        $sql = "SELECT * FROM " . SLIDER . " WHERE 1  AND id  = " . $id;

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

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

        if ($id > 0) {
            $sql = "DELETE FROM " . SLIDER . " WHERE 1  AND id = " . $id;
            $this->_db->query($sql);
            $retVal = $this->_db->execute();
            if (!empty($res['image'])) {
                unlink(UPLOAD_ROOT . 'slider/' . $res['image']);
            }
            if ($retVal) {
                $type = 'success';
                $msg = 'Slider Data Successfully Deleted';
            } else {
                $type = 'error';
                $msg = 'Error In deleting Slider Data';
            }
        } else {
            $type = 'error';
            $msg = 'Error In deleting Slider data';
        }


        set_session_alert($type, $msg);

        redirect(ADMIN_URL . 'slider');
    }

    public function manage($id = '')
    {
        $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);
        }

        $id = decryptData($id);
        if (!empty($id)) {

            $edit_id = $id;

            if ($edit_id > 0) {
                $sql = "SELECT * FROM " . SLIDER . " WHERE 1  AND id = " . $id;
                $this->_db->query($sql);
                $res = $this->_db->single();
                $this->_view->setVal('sliderData', $res);
                $label = 'Edit Slider';
            } else {
                set_session_alert('error', 'Invalid Data');
                redirect(ADMIN_URL . 'slider');
            }
        } else {
            $label = 'Add Slider';
        }

        $this->_view->setVal('title', $label);
        $this->_view->setVal('meta_title',   $label);
        $this->_view->setVal('meta_description',   $label);
        $this->_view->setVal('meta_keyword',  $label);
        $this->_view->renderAdmin('slider/slider-data');
    }

    public function save()
    {

        $title = $_POST['title'];
        $status = $_POST['status'];
        $id = $_POST['id'] ?? '';
        $folder_data = UPLOAD_ROOT . 'slider/';

        $filename = $_FILES["media"]["name"];
        $temp_name = $_FILES["media"]["tmp_name"];
        $old_file = $_POST['media_old'] ?? null;
        $new_file_name = rand(100, 99999999) . $filename;
        $folder = $folder_data . $new_file_name;
        if (!empty($old_file)) {
            if (!empty($temp_name)) {
                if (move_uploaded_file($temp_name, $folder)) {
                    unlink($folder_data . $old_file);
                    $file_name = $new_file_name;
                } else {
                    $file_name = $old_file;
                }
            } else {
                $file_name = $old_file;
            }
        } else {
            if (move_uploaded_file($temp_name, $folder)) {
                $file_name = $new_file_name;
            } else {
                $file_name = null;
            }
        }


        $data = [
            'title' => htmlspecialchars($title),
            'image' => $file_name,
            'status' => $status,
        ];
        if (!empty($id)) {
            $data['updated_at'] =  date('Y-m-d h:i:s');
            $update_colum = '';
            $updated_colum_keys = array_keys($data);
            foreach ($data as $uk => $uv) {
                if ($uk != end($updated_colum_keys)) {
                    $separator = ',';
                } else {
                    $separator = '';
                }
                $update_colum .= $uk . " = '" . $uv . "'" . $separator;
            }

            $sql = "UPDATE " . SLIDER . " SET " . $update_colum . " WHERE id = " . $id;
            $mode = 'Updated';
            $url = 'manage/' . encryptData($id);
        } else {
            $data['created_at'] =  date('Y-m-d h:i:s');
            $url = 'manage';
            $insert_bind_colum = '';
            $insert_colum_keys = array_keys($data);
            $insert_colum =  implode(',', $insert_colum_keys);
            foreach ($data as $uk => $uv) {
                if ($uk != end($insert_colum_keys)) {
                    $separator = ',';
                } else {
                    $separator = '';
                }
                $insert_bind_colum .= "'" . $uv . "'" . $separator;
            }
            $sql = " INSERT INTO " . SLIDER . " ( " .  $insert_colum . ") VALUES (" . $insert_bind_colum . ")";
            $mode = 'Saved';
        }

        $type = "error";
        try {
            $db =  new Database();
            $db->query($sql);
            $results = $db->execute();
        } catch (Exception $e) {
            $msg  = $e->getMessage();
            $results = 0;
        }
        if ($results) {
            $type = 'success';
            $msg = 'Slider Data Successfully ' . $mode;
        } else {
            $type   = "error";
            $msg = "Unable to " . $mode . " Slider Data!!";
        }

        set_session_alert($type, $msg);

        redirect(ADMIN_URL . 'slider/' . $url);
    }
}
