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

class Updatesoft extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        error_reporting(0);
        $this->fx->validateCORS();
        $this->load->model(array('Updatesoft_Model', 'Master_Model'));
        $this->load->helper(array('file', 'download'));
        $this->load->library('Dynamicformcontent');
        ini_set('max_execution_time', 300); // 300 seconds = 5 minutes
        $this->convertHeaderToPost($this->input->request_headers());
    }

    private function convertHeaderToPost($headerData)
    {
        foreach ($headerData as $key => $value) {
            if (strtolower($key) == 'token') {
                $_POST[strtolower($key)] = $value;
                break;
            }
        }
    }
    function setData($token)
    {
        $array = explode("-", $this->decode($token));
        if (empty($array[0])) {
            return;
        }

        $this->user_id = $this->db->escape_str($array[0]);
        $this->user_email = $this->db->escape_str($array[1]);
        $this->user_mobile = $this->db->escape_str($array[2]);
        $this->user_type = $this->db->escape_str($array[3]);
        $this->full_control = $this->db->escape_str($array[4]);
        $this->queue_perm_id = $this->db->escape_str($array[5]);
        $this->maskEmail = $this->db->escape_str($array[6]);
        $this->maskPhone = $this->db->escape_str($array[7]);
        return true;
    }

    function api_response($response, $status_code = 200)
    {

        $CI = &get_instance();
        $CI->output
            ->set_status_header(200)
            ->set_content_type('application/json', 'utf-8')
            ->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
            ->_display();
        exit;
    }

    private function decode($string)
    {
        return $this->fx->encrypt_decrypt('decrypt', $string);
    }

    public function index()
    {

        $token = $this->input->post('token');

        if ($token == "") {
            $this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
            return;
        }
        if ($this->setData($token) == false)
            return;

        $post = json_decode(file_get_contents("php://input"));


        $count = $this->Updatesoft_Model->checkPass((array)$post);

        if ($count == 1) {
            $resp =  $this->updateDb();

            if ($resp['status'] == true) {
                $updatelog = array(
                    'modified_by' => $this->user_id,
                    'status' => 1
                );
                $this->Updatesoft_Model->insertUpdateLog($updatelog, $this->logId);

                // Empty Uploaded file ----------------- START
                $file = fopen(FCPATH . "updateSoftFile/update_all_db.txt", 'w');
                ftruncate($file, 0);
                fclose($file);
                // Empty Uploaded file ----------------- END

                $this->api_response(['success' => true, 'status_code' => 200, 'message' => "Database Updated Successfully", 'result' => '']);
                return;
            } else {
                $this->api_response(['success' => false, 'status_code' => 400, 'message' => $resp['msg'], 'result' => '']);
                return;
            }
        } else {
            $this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Password', 'result' => '']);
            return;
        }
    }

    private function updateDb()
    {



        $sql = file_get_contents(FCPATH . "updateSoftFile/update_all_db.txt");
        $sqls = explode('**', $sql);

        if (empty(trim($sqls[0]))) {
            return array("status" => false, "msg" => "Uploaded file is empty");
        }


        $inslogData = array(
            'created_by' => $this->user_id,
            'ip_addr' => getenv('HTTP_CLIENT_IP') ?: getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?: getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?: getenv('REMOTE_ADDR')
        );
        $this->logId =   $this->Updatesoft_Model->insertUpdateLog($inslogData);


        $filename = "update_all_db_" . $this->logId . ".txt";
        $uploadFileLoc = FCPATH . "/updateSoftFile/updateSoftLog/";


        $resp = copy(FCPATH . "updateSoftFile/update_all_db.txt", $uploadFileLoc . $filename);
        chmod($uploadFileLoc . $filename, 0777);


        $updatelog = array(
            'modified_by' => $this->user_id,
            'uploaded_file' => $filename
        );
        $this->Updatesoft_Model->insertUpdateLog($updatelog, $this->logId);


        $queueData = $this->Updatesoft_Model->getAllQueueData();
        $queueIdArr = array_column($queueData, 'queue_id');


        $st = array();

        if (!empty($sqls) && count($sqls) > 0) {
            foreach ($sqls as $key => $stmt) {
                if (!empty(trim($stmt))) {
                    $qrystmt = array();
                    $queueStatus = strpos($stmt, "##QU##");

                    if ($queueStatus === false) {
                        $qrystmt = $this->QueryStmt($stmt);
                    } else {
                        foreach ($queueIdArr as $QuId) {
                            $this->Updatesoft_Model->QueueId = $QuId;
                            $qrystmt = $this->QueryStmt($stmt);
                            if ($qrystmt['status'] == false) {
                                break;
                            }
                        }
                    }
                    $st = $qrystmt;
                    if ($qrystmt['status'] == false) {
                        break;
                    }
                }
            }
        }

        return $st;
    }


    public function QueryStmt($stmt)
    {
        $stmtArr = explode("|", trim($stmt));
        $stmtType = trim($stmtArr[0]);
        $st = array();

        if ($stmtType == "CRT_TBL") {
            $st = $this->Updatesoft_Model->createTable(trim($stmtArr[1]), trim($stmtArr[2]));
        } elseif ($stmtType == 'DRP_TBL') {
            $st = $this->Updatesoft_Model->dropTable(trim($stmtArr[1]));
        } elseif ($stmtType == 'RNM_TBL') {
            $st = $this->Updatesoft_Model->renameTable(trim($stmtArr[1]), trim($stmtArr[2]));
        } elseif ($stmtType == 'ADD_CLM') {
            $st = $this->Updatesoft_Model->addColumn(trim($stmtArr[1]), trim($stmtArr[2]), trim($stmtArr[3]), trim($stmtArr[4]), trim($stmtArr[5]), trim($stmtArr[6]), trim($stmtArr[7]));
        } elseif ($stmtType == 'DRP_CLM') {
            $st = $this->Updatesoft_Model->dropColumn(trim($stmtArr[1]), trim($stmtArr[2]));
        } elseif ($stmtType == 'ALT_TBL') {
            $st = $this->Updatesoft_Model->alterTable(trim($stmtArr[1]), trim($stmtArr[2]), trim($stmtArr[3]), trim($stmtArr[4]), trim($stmtArr[5]), trim($stmtArr[6]), trim($stmtArr[7]), trim($stmtArr[8]));
        } elseif ($stmtType == 'QRY') {
            $st = $this->Updatesoft_Model->query(trim($stmtArr[1]));
        } elseif ($stmtType == 'CRT_PRO') {
            $st = $this->Updatesoft_Model->createProcedure(trim($stmtArr[1]), trim($stmtArr[2]));
        } elseif ($stmtType == 'CRT_FUN') {
            $st = $this->Updatesoft_Model->createFunction(trim($stmtArr[1]), trim($stmtArr[2]));
        }


        $logResp = $this->Master_Model->getScalerCol("response", "tms_updatesoft_log t1", "1=1 and t1.id = $this->logId")->response;
        $updatelog = array(
            'modified_by' => $this->user_id,
            'response' => !empty($logResp) ? $logResp . ", " . $st['msg'] : $st['msg']
        );
        $re = $this->Updatesoft_Model->insertUpdateLog($updatelog, $this->logId);

        return $st;
    }


    public function downloadFile()
    {
        $token = $this->input->post('token');
        if ($token == "") {
            $this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
            return;
        }
        if ($this->setData($token) == false)
            return;
        $post = (array) json_decode(file_get_contents('php://input'));


        $folderPath = FCPATH . "updateSoftFile/updateSoftLog/";
        $fileName = $post['file_name'];
        $uploadedSoftId =  $post['updatesoft_id'];

        $file_path = $folderPath . $fileName;


        if (file_exists($file_path)) {
            header('Content-Type: application/octet-stream');
            header('Content-Type: ' . mime_content_type($file_path));
            // header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
            header('Content-Disposition: attachment; filename="' . $fileName . '"');

            //To prevent from corrupt file download added ob_get_level() and ob_end_clean()
            while (ob_get_level()) {
                ob_end_clean();
            }

            readfile($file_path);
            exit;
        } else {
            $this->api_response(['success' => false, 'status_code' => 400, 'message' => 'File Not Found'], 400);
        }
    }
}
