<?php

/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */

require_once("imp/_imp.php");

class Controllers {

    //public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    public $patientid;

    // it will run in everytime with
    // default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;

        //here name of controll to known
        $this->controllname = 'sonar';
        $this->shcontrollname = 'Pictures and Videos';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);

        //breadcrumbs
        require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
        $acty = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, '', '', $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

        #include upload function
        require_once("../../_library/plugins/classupload/uploadfunctions.php");

        # here show the active page in menu
        // array called active[] with level of active element
        $active[0] = 'sonar'; //controller name or tab name
        $this->active = $active;


        //here will call all php pages
        require_once("_header.php");
        require_once("_patientdata.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
        $this->patientid = patientdata::patientid();
    }

    //
    //here the frist page and
    //the frist action in this class
    public function index() {
        //check login
        autho::checkautho($this->hosturl);
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);


        $today = date("Y-m-d");
        $todayR = date("Y/m/d", strtotime($today));
        $this->smarty->assign('today', $todayR);

        //$patientid = filter_input(INPUT_GET, $id);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $this->smarty->assign('patientid', $this->patientid);

        //$allsonar = R::findAll('sonar','patientid = ? and tempdelete = 0',[$patientid]);
        $allsonar = R::getAll('select id, sonardate , imagename , notes , originalname from sonar where tempdelete = 0 and type = 0 and patientid = ' . $this->patientid . ' order by sonardate desc');
        $allsonarvid = R::getAll('select id, sonardate , vediourl , originalname from sonar where tempdelete = 0 and type = 1  and patientid = ' . $this->patientid . ' order by sonardate desc');



        if (empty($allsonar)) {
//            $sonarData = R::dispense('sonar');
//            $sonarData->sonardate = $today;
//            $sonarData->patientid = $this->patientid;
//            $sonarData->tempdelete = 0;
//            $sonarData->type = 0;
//            $sonarData->originalname = '';
//            $sonarid = R::store($sonarData);
//
//
//            $this->smarty->assign('newImgId', $sonarid);
        }

        if (empty($allsonarvid)) {
//            $sonarData = R::dispense('sonar');
//            $sonarData->sonardate = $today;
//            $sonarData->patientid = $this->patientid;
//            $sonarData->tempdelete = 0;
//            $sonarData->type = 1;
//            $sonarData->originalname = '';
//            $sonarid = R::store($sonarData);
//
//            $this->smarty->assign('sonarData', $sonarData);
//            $this->smarty->assign('newVideoId', $sonarid);
        }

        for ($i = 0; $i < count($allsonar); $i++) {
            $allsonar[$i]["sonardate"] = date("Y/m/d", strtotime($allsonar[$i]["sonardate"]));
        }



        for ($i = 0; $i < count($allsonarvid); $i++) {
            $allsonarvid[$i]["sonardate"] = date("Y/m/d", strtotime($allsonarvid[$i]["sonardate"]));
        }

        $this->smarty->assign('allsonar', $allsonar);
        $this->smarty->assign('allsonarvid', $allsonarvid);
        $this->smarty->assign('sonarcount', count($allsonar));
        $this->smarty->assign('sonarVidcount', count($allsonarvid));



        //print_r($allsonar);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        patientdata::patientdatashow($this->smarty, $this->hosturl);
        $this->smarty->display('sonar/sonar.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function addnewimg() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $today = date("Y-m-d");
        $patientid = filter_input(INPUT_POST, "patientId");



        //here the add
        $sonarImg = R::dispense('sonar');

        $sonarImg->patientid = $patientid;
        $sonarImg->sonardate = $today;
        $sonarImg->notes = '';
        $sonarImg->type = 0;


        $id = R::store($sonarImg);
        echo $id;
    }

    public function addnewvid() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);


        $date = date("Y-m-d");
        $patientid = filter_input(INPUT_POST, "patientId");



        //here the add
        $sonarVid = R::dispense('sonar');

        $sonarVid->patientid = $patientid;
        $sonarVid->sonardate = $date;
        $sonarVid->notes = '';
        $sonarVid->type = 1;


        $id = R::store($sonarVid);
        echo $id;
    }

    public function update() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);


        $id = filter_input(INPUT_POST, "id");
        $value = filter_input(INPUT_POST, "value");
        $tableName = filter_input(INPUT_POST, "tableName");
        $colName = filter_input(INPUT_POST, "colName");
        $patientId = filter_input(INPUT_POST, "patientId");
        //$notes = filter_input(INPUT_POST, "notes");
        $dated = filter_input(INPUT_POST, "dated");

        if ($dated == 1) {
            $value = date("Y-m-d", strtotime($value));
        }
        $mydata = R::findone($tableName, 'id = ? and patientid = ?', [$id, $patientId]);
        $mydata->$colName = $value;
        R::store($mydata);
    }

    public function del() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $id = filter_input(INPUT_POST, "id");
        $today = date("Y-m-d");


        R::exec('UPDATE sonar SET tempdelete = 1 WHERE id = ' . $id);
    }

    public function upload() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);


        $id = filter_input(INPUT_POST, "Id");
        $type = filter_input(INPUT_POST, "type");
        $name = 'file-0';
        //echo $_FILES['file-0']['name'];

        if ($type == "image") {
            $img = uploadnew($name, False, 0, 0, 'sonar');
            $sonar = R::load('sonar', $id);
            echo $img;
            ## delete old file

            $oldFileName = $sonar->imagename;
            $fileFolder = 'sonar';
            $sonar->imagename = $img;

            try {
                $id = R::store($sonar);
            } catch (Exception $e) {
                header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
            }
        } elseif ($type == "video") {
            $fileName = $_FILES[$name]['name'];
            $randomname = md5(uniqid(mt_rand(), true));
            $video = uploadHEX($name, 'sonarvedio', 1, $randomname, 0);
            echo $video;

            $sonar = R::load('sonar', $id);

            ## delete old file

            $oldFileName = $sonar->vediourl;
            $fileFolder = 'sonarvedio';

            $sonar->vediourl = $video;
            $sonar->originalname = $fileName;
            try {
                $id = R::store($sonar);
            } catch (Exception $e) {
                header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
            }
        }

        if (!empty($oldFileName)) {
            $this->deletefile($oldFileName, $fileFolder);
        }
    }

    public function uploadmulti() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $type = filter_input(INPUT_POST, "type");
        $count = filter_input(INPUT_POST, "imgCount");
        $date = filter_input(INPUT_POST, "date");
        $note = filter_input(INPUT_POST, "note");
        $patientId = filter_input(INPUT_POST, "patientId");

        //$idArray = array();

        if ($type == "image") {
            for ($i = 0; $i < $count; $i++) {
                $name = 'file-' . $i;
                $img = uploadnew($name, False, 0, 0, 'sonar');
                $sonarImg = R::dispense('sonar');

                $sonarImg->patientid = $patientId;
                $sonarImg->sonardate = date("Y-m-d", strtotime($date));
                ;
                $sonarImg->type = 0;
                $sonarImg->notes = $note;
                $sonarImg->imagename = $img;


                try {
                    $id = R::store($sonarImg);
                    //$sonarImg->id = $id ;
                    //array_push($idArray, $sonarImg);
                } catch (Exception $e) {
                    header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
                }
            }
            echo 1;
//            $this->smarty->assign('idArray', $idArray);
//            $this->smarty->display('sonar/result.html');
        } elseif ($type == "video") {
            for ($i = 0; $i < $count; $i++) {
                $name = 'file-' . $i;
                $fileName = $_FILES[$name]['name'];
                $randomname = md5(uniqid(mt_rand(), true));
                $video = uploadHEX($name, 'sonarvedio', 1, $randomname, 0);

                $sonarImg = R::dispense('sonar');
                $sonarImg->patientid = $patientId;
                $sonarImg->sonardate = date("Y-m-d", strtotime($date));
                $sonarImg->type = 1;
                $sonarImg->notes = '';
                $sonarImg->vediourl = $video;
                $sonarImg->originalname = $fileName;

                try {
                    $id = R::store($sonarImg);
                } catch (Exception $e) {
                    print_r($e);
                    // header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
                }
            }
            echo 1;
        }
    }

    public function downloadfile() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);


        $videoId = filter_input(INPUT_GET, "id");
        $sonar = R::load('sonar', $videoId);

        $file_url = '../../upload/sonarvedio/1/' . $sonar->vediourl;
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary");
        header("Content-disposition: attachment; filename=\"" . $sonar->originalname . "\"");
        readfile($file_url); // do the double-download-dance (dirty but worky)


        return 1;
    }

    public function printpic() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $imagesId = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));
        $patientId = filter_input(INPUT_POST, "patientId");
        $images = array();

        if (!empty($patientId)) {
            $patient = R::load('patients', $patientId);

            $wifetypes = R::load('wifetypes', $patient->wiftypeid);
            $this->smarty->assign('name', $patient->wifename);
            $this->smarty->assign('title', $wifetypes->title);
        } else {
            $patientId = 0;
        }

        $ProgramesettingData = R::findone('programesetting');
        $this->smarty->assign('ProgramesettingData', $ProgramesettingData);

        foreach ($imagesId as $id) {
            $image = R::load('sonar', $id);
            if (!empty($image->imagename)) {
                array_push($images, $image);
            }
        }



        $today = date("Y-m-d");
        $this->smarty->assign('date', $today);
        $this->smarty->assign('images', $images);
        $this->smarty->display('sonar/print.html');
    }

    private function deletefile($fileName, $fileFolder) {
        $target_dir = "../../upload/" . $fileFolder;
        $target_file = $target_dir . '/' . $fileName;

        if (file_exists($target_file)) {
            chmod($target_file, 0777);
            unlink($target_file);
        }
    }

    public function getpatientimg() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize

        $patientid = filter_input(INPUT_POST, "patientId");

        $allsonar = R::getAll('select id, sonardate , imagename , notes , originalname from sonar 
                where tempdelete = 0 and type = 0 and patientid = ' . $patientid . ' order by sonardate desc');

        $this->smarty->assign('allsonar', $allsonar);
        $this->smarty->display('sonar/scrollimg.html');
    }

    // at the end of class call
    public function __destruct() {
        //close connection
        R::close();
    }

}
