<?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;

   // 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 = 'operations';
      $this->shcontrollname = 'Home';
      $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);

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

      R::ext('xdispense', function ($type) {
         return R::getRedBean()->dispense($type);
      });

      //here will call all php pages
      require_once("_header.php");
      require_once("_sidebar.php");
      require_once("_leftsidebar.php");
      require_once("_footer.php");
   }

   //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']);
      //here will load the menu show
      $allPatient = R::findAll('patients');
      $this->smarty->assign('allPatient', $allPatient);

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

      $patientid = filter_input(INPUT_GET, "patientid");
      if (empty($patientid)) {
         $allData = R::findAll('operations', 'date = ?', [$today]);
         $allData2 = R::findAll('hysteroscopy', 'date = ?', [$today]);
         $allData3 = R::findAll('laparoscopy', 'date = ?', [$today]);
      } else {

         $allData = R::findAll('operations', " LEFT JOIN infertilitysheet
         ON operations.infertilitysheetid = infertilitysheet.id where 1 and  date = '$today' and patientid = $patientid ");
         $allData2 = R::findAll('hysteroscopy', " where 1 and  date = '$today' and patientid = $patientid ");
         $allData3 = R::findAll('laparoscopy', " where 1 and  date = '$today' and patientid = $patientid ");
         $lastVisitData = R::findOne('lastvisit', 'patientid = ? order by id desc ', [$patientid]);
         $lastVisit = R::dispense('lastvisit');
         $lastVisit->patientid = $patientid;
         $lastVisit->control = $this->controllname;
         if ($lastVisitData->patientid == $patientid) {
            $lastVisit->id = $lastVisitData->id;
         }
         R::store($lastVisit);
         $this->smarty->assign('patientid', $patientid);
      }


      $this->smarty->assign('allData', $allData);
      foreach ($allData as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->patientid = $infertilitysheet->patientid;
         $data->operationc = R::findAll('operation', "id in (0$data->operation)");
         $data->histopathc = R::findAll('histopath', "id in (0$data->histopath)");
         $data->placec = R::load('place', $data->place);
      }


      $this->smarty->assign('allData2', $allData2);
      foreach ($allData2 as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->patientid = $infertilitysheet->patientid;
         $data->copyplace = R::load('copyplace', $data->copyplace);
      }


      $this->smarty->assign('allData3', $allData3);
      foreach ($allData3 as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->patientid = $infertilitysheet->patientid;
         $data->laparplace = R::load('laparplace', $data->laparplace);
      }

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

   public function Add() {
      $tableName = filter_input(INPUT_POST, 'table');
      $id = filter_input(INPUT_POST, 'id');
      $colName = filter_input(INPUT_POST, 'name');
      $value = filter_input(INPUT_POST, 'value');

      try {
         $obj = R::load($tableName, $id);
         $obj->$colName = $value;
         R::store($obj);
      } catch (Exception $e) {
         
      }
   }

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

      //R::debug(TRUE);
      $fromdate = filter_input(INPUT_POST, 'fromdate');
      $todate = filter_input(INPUT_POST, 'todate');
      $patientid = filter_input(INPUT_POST, 'patientid');
      $this->smarty->assign('patientid', $patientid);
      $todate = date("Y/m/d", strtotime($todate));
      $searchQuery = '';
      if ($patientid) {
         $searchQuery = " and patientid = " . $patientid . " ";
      }
      if ($fromdate) {
         $fromdate = date("Y/m/d", strtotime($fromdate));
         $searchQuery .= " and  date >= '$fromdate' and date <=  '$todate' ";
      }
      $allData = R::findAll('operations', 'LEFT JOIN infertilitysheet
         ON operations.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
      $allData2 = R::findAll('hysteroscopyinfertility', ' LEFT JOIN infertilitysheet
         ON hysteroscopyinfertility.infertilitysheetid = infertilitysheet.id  where 1 ' . $searchQuery . '');
      $allData3 = R::findAll('laparoscopyinfertility', ' LEFT JOIN infertilitysheet
         ON laparoscopyinfertility.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
      $this->smarty->assign('allData', $allData);
      foreach ($allData as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->patientid = $infertilitysheet->patientid;
         $data->operationc = R::findAll('operation', "id in (0$data->operation)");
         $data->histopathc = R::findAll('histopath', "id in (0$data->histopath)");
         $data->placec = R::load('place', $data->place);
      }

      $this->smarty->assign('allData2', $allData2);
      foreach ($allData2 as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->patientid = $infertilitysheet->patientid;
         $data->copyplace = R::load('copyplace', $data->copyplace);
      }

      $this->smarty->assign('allData3', $allData3);
      foreach ($allData3 as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->patientid = $infertilitysheet->patientid;
         $data->laparplace = R::load('laparplace', $data->laparplace);
      }

      $this->smarty->display('reports2/operationssearch.html');
   }

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

      //R::debug(TRUE);
      $fromdate = filter_input(INPUT_POST, 'fromdate');
      $todate = filter_input(INPUT_POST, 'todate');
      $patientid = filter_input(INPUT_POST, 'patientid');
      $this->smarty->assign('patientid', $patientid);
      $todate = date("Y/m/d", strtotime($todate));
      $searchQuery = '';
      if ($patientid) {
         $searchQuery .= " and patientid = " . $patientid . " ";
      }
      if ($fromdate) {
         $fromdate = date("Y/m/d", strtotime($fromdate));
         $searchQuery .= " and  date >= '$fromdate' and date <=  '$todate' ";
      }
      $allData = R::findAll('operations', 'LEFT JOIN infertilitysheet
         ON operations.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
      $allData2 = R::findAll('hysteroscopyinfertility', ' LEFT JOIN infertilitysheet
         ON hysteroscopyinfertility.infertilitysheetid = infertilitysheet.id  where 1 ' . $searchQuery . '');
      $allData3 = R::findAll('laparoscopyinfertility', ' LEFT JOIN infertilitysheet
         ON laparoscopyinfertility.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
      $this->smarty->assign('allData', $allData);
      foreach ($allData as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->operationc = R::findAll('operation', "id in ($data->operation)");
         $data->histopathc = R::findAll('histopath', "id in ($data->histopath)");
         $data->placec = R::load('place', $data->place);
      }

      $this->smarty->assign('allData2', $allData2);
      foreach ($allData2 as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->copyplace = R::load('copyplace', $data->copyplace);
      }

      $this->smarty->assign('allData3', $allData3);
      foreach ($allData3 as $data) {
         $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
         $data->info = R::load('patients', $infertilitysheet->patientid);
         $data->laparplace = R::load('laparplace', $data->laparplace);
      }
      $this->smarty->display('reports2/operationsprint.html');
   }

   public function onesetup() {

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

      try {
         //delete all but with only default
         #1 clean roles only managment
         #2 clean menu only default
         #3 clean controls only default
         #4 users clean users
         #delete all menus
         $menus = R::findAll('awmenu', 'id > 15');
         #delete from awrolemenu
         foreach ($menus as $one) {
            //get propes
            $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
            R::trashAll($rolemenu);
         }
         R::trashAll($menus);
         #delete controles
         $controlls = R::findAll('awcontroll', 'id > 4 and id < 18');
         foreach ($controlls as $one) {
            //get propes
            $inprop = R::findAll('awcontrollprop', 'awcontroll_id = ?', [$one->id]);
            #delete from awrolecontroleprop
            foreach ($inprop as $one) {
               //get propes
               $roleprop = R::findAll('awrolecontrollprop', 'controllprop_id = ?', [$one->id]);
               R::trashAll($roleprop);
            }
            R::trashAll($inprop);
         }
         R::trashAll($controlls);
         #delete othre roles
         $roles = R::findAll('awrole', 'id > 1');
         R::trashAll($roles);
         #delete other users
         //$users = R::findAll('awusers', 'user_id > 1');
         //R::exec('Delete from awusers where user_id > 1');
         //R::trashAll($users);
         ############################
         //new one
         $menusx = R::findAll('awmenu', ' id = 4 or id = 5 or id = 7 or id = 8 or id = 10 or id = 11 or id = 13 or id = 14 or id = 15 ');
         #delete from awrolemenu
         foreach ($menusx as $one) {
            //get propes
            $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
            R::trashAll($rolemenu);
         }
         R::trashAll($menusx);

         print_r('trash all , install is good');
      } catch (Exception $ex) {
         print_r('something go wrong  , try again');
      }
   }

   ###########################  Heba   => Operation Waiting List ##############################

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

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

      $places = R::findAll('place', 'del is null ');
      $this->smarty->assign('places', $places);

      $operations = R::findAll('operation', 'del is null ');
      $this->smarty->assign('operations', $operations);

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

   public function deldataselect() {
      //check login
      autho::checkautho($this->hosturl);

      $table = filter_input(INPUT_POST, 'table');
      $id = filter_input(INPUT_POST, 'id');
      $celtables = R::load($table, $id);
      $celtables->del = 1;
      try {
         $inserted = R::store($celtables);
         echo $inserted;
      } catch (Exception $e) {
         echo 0;
      }
   }

   public function addInList() {
      //check login
      autho::checkautho($this->hosturl);
      //check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      //prepar wife data insert
      $patientId = filter_input(INPUT_POST, 'patientid');
      $opDate = date('Y/m/d', strtotime(filter_input(INPUT_POST, 'opdate')));
      $place = filter_input(INPUT_POST, 'placeW');
      $notes = filter_input(INPUT_POST, "notes");

      $operation = implode(',', $_POST['operationW']);

      //   session_start();

      $insertDataVisits = R::xdispense('op_wait_list');
      $insertDataVisits->patientid = $patientId;
      $insertDataVisits->opdate = $opDate;
      $insertDataVisits->operation = $operation;
      $insertDataVisits->place = $place;
      $insertDataVisits->notes = $notes;
      $insertDataVisits->deleted = 0;
      $insertDataVisits->createdate = date('Y-m-d h:i:s');
      $insertDataVisits->user_id = $_SESSION['user_id'];

      try {
         $insert = R::store($insertDataVisits);

         if ($insert) {
            echo 1;
         } else {
            echo -1;
         }
      } catch (Exception $ex) {
         echo -1;
      }
   }

   function reloadOpVisits() {

      $dateFrom = filter_input(INPUT_POST, "date_from");
      $dateTo = filter_input(INPUT_POST, "date_to");
      $patientId = filter_input(INPUT_POST, "patientId");
      $this->loadVisits($dateFrom, $dateTo, $patientId);
   }

   function loadVisits1($dateFrom, $dateTo, $patientId) {
      if ($patientId > 0) {
         $allvisit = $this->visitsFuture($patientId);
         $this->smarty->assign('allvisit', $allvisit);
         $this->smarty->display('operation/listdivfut.html');
      } else {
         if ($dateFrom != '00-00-0000' && !empty($dateFrom)) {
            $dateFrom = date('Y/m/d', strtotime($dateFrom));
         } else {
            $dateFrom = '0000-00-00';
         }

         if ($dateTo != '00-00-0000' && !empty($dateTo)) {
            $dateTo = date('Y/m/d', strtotime($dateTo));
         } else {
            $dateTo = date('Y/m/d');
         }

         $allvisit = $this->listVisits($dateFrom, $dateTo, 0);
         $this->smarty->assign('allvisit', $allvisit);
         $this->smarty->display('operation/listdiv.html');
      }
   }

   function loadVisits($dateFrom, $dateTo, $patientId) {
      if ($dateFrom != '00-00-0000' && !empty($dateFrom)) {
         $dateFrom = date('Y/m/d', strtotime($dateFrom));
      } else {
         $dateFrom = '0000-00-00';
      }

      if ($dateTo != '00-00-0000' && !empty($dateTo)) {
         $dateTo = date('Y/m/d', strtotime($dateTo));
      } else {
         $dateTo = date('Y/m/d');
      }

      $allvisit = $this->listVisits($dateFrom, $dateTo, $patientId);
      $this->smarty->assign('allvisit', $allvisit);
      $this->smarty->display('operation/listdiv.html');
   }

   function visitsFuture($patientId) {
      $date = date('Y/m/d');
      $sql = '  and  list.opdate  >= "' . $date . '"    and  list.patientid =  ' . $patientId . ' ORDER BY list.opdate ASC';
      $allvisit = $this->listSqlEx($sql);
      return $allvisit;
   }

   function listVisits($dateFrom, $dateTo, $patientId) {

      $result = array();
      $patSql = '';
      if ($patientId > 0) {
         $patSql = ' and list.patientid =   ' . $patientId;
      }

      $begin = new DateTime($dateFrom);
      $end = new DateTime($dateTo . ' +1 day');

      $interval = DateInterval::createFromDateString('1 day');
      $period = new DatePeriod($begin, $interval, $end);

      foreach ($period as $dt) {
         $dayDate = $dt->format("Y-m-d");
         $dayName = $this->getDayNameFnAr($dayDate);
         $dayDateAll = $dayName . ' : ' . $dayDate;

         $sql = $patSql . '  and   list.opdate  =  "' . $dayDate . '"    ORDER BY list.id ASC';
         $allvisit = $this->listSqlEx($sql);

         if (count($allvisit) > 0) {
            $result[$dayDateAll] = $allvisit;
         }
      }

      return $result;
   }

   function listSqlEx($sqlExt) {
      $sql = '       select  list.id as id   , list.operation as  operationIds  , place.title as  place
                            , list.notes   , list.opdate  , patients.wifename  as patientName   
                             , patients.statusno  as patientNo   , patients.husdandname  as husbandName 
                             , patients.address, patients.phone , "" as  operation
                            
                            from      op_wait_list       list 
                            left join   place            on place.id = list.place   
                            join patients                on patients.id = list.patientid


                    where    list.deleted = 0     ' . $sqlExt;

      $allvisit = R::getAll($sql);
      $visits = $this->listCommon($allvisit);
      return $visits;
   }

   function listCommon($allvisit) {
      $j = 0;
      foreach ($allvisit as $data) {
         $operationIds = explode(',', $data['operationIds']);
         $op = '';
         $i = 1;
         foreach ($operationIds as $id) {
            $operation = R::load('operation', $id);
            if ($i > 1) {
               $op .= ' , ';
            }
            $op .= $operation->title;
            $i++;
         }
         $allvisit[$j]['operation'] = $op;
         $j++;
      }
      return $allvisit;
   }

   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');
      $table = filter_input(INPUT_POST, 'link');
      try {
         $obj = R::load($table, $id);
         $obj->deleted = 1;
         R::store($obj);
         echo 1;
      } catch (Exception $ex) {
         echo $ex;
      }
   }

   public function editvisit() {
      $visitId = filter_input(INPUT_POST, "visitId");
      $visit = R::load('op_wait_list', $visitId);

      $visit->opdate = date("Y/m/d", strtotime($visit->opdate));
      $patient = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");

      $result = array(
          "opdate" => date("Y/m/d", strtotime($visit->opdate)),
          "patientid" => $visit->patientid,
          "statusno" => $patient['statusno'],
          "operation" => $visit->operation,
          "place" => $visit->place,
          "notes" => $visit->notes
      );

      echo json_encode($result);
   }

   public function updatevisit() {
//check login
      autho::checkautho($this->hosturl);

      $visitId = filter_input(INPUT_POST, "mVisitId");
      $patientId = filter_input(INPUT_POST, 'patientid');
      $opDate = date('Y/m/d', strtotime(filter_input(INPUT_POST, 'opdate')));
      $place = filter_input(INPUT_POST, 'placeW');
      $notes = filter_input(INPUT_POST, "notes");

      $operation = implode(',', $_POST['operationW']);

      $visit = R::load('op_wait_list', $visitId);

      $visit->patientid = $patientId;
      $visit->opdate = $opDate;
      $visit->operation = $operation;
      $visit->place = $place;
      $visit->notes = $notes;

      R::store($visit);

      echo $visitId;
   }

   private function getDayNameFnAr($date) {
      $timestamp = strtotime($date);

      $day = date('w', $timestamp);

      switch ($day) {
         case 0:
            $name = 'الأحد  ';
            break;
         case 1:
            $name = ' الإثنين';
            break;
         case 2:
            $name = ' الثلاثاء';
            break;
         case 3:
            $name = 'الأربعاء ';
            break;
         case 4:
            $name = 'الخميس  ';
            break;
         case 5:
            $name = 'الجمعة ';
            break;
         case 6:
            $name = 'السبت ';
            break;
      }

      return $name;
   }

   public function addnewrecord() {
//check login
      autho::checkautho($this->hosturl);

//vars here
      $table = filter_input(INPUT_POST, 'selectId');
      $name = filter_input(INPUT_POST, 'new_name');

      $obj_id = filter_input(INPUT_POST, 'id');
      $tableName = filter_input(INPUT_POST, 'tableName');
      $colName = filter_input(INPUT_POST, 'colName');

      try {

         $record = R::xdispense($table);
         $record->title = $name;
         $id = R::store($record);

         if ($obj_id > 0) {

            $obj = R::load($tableName, $obj_id);
            $obj->$colName = $id;
            R::store($obj);
         }


         echo $id;
      } catch (Exception $e) {
         echo $e;
      }
   }

   ###########################  Heba   => 4D Waiting List ##############################

   public function getdataselect() {
      //check login
      autho::checkautho($this->hosturl);

      $celtable = filter_input(INPUT_POST, 'celtable');
      $allceltable = R::findAll($celtable, 'del is null');
      $count = R::count($celtable, 'del is null');

      $this->smarty->assign('celtable', $celtable);
      $this->smarty->assign('allceltable', $allceltable);
      $this->smarty->display('infertilitysheet/delselect.html');
   }

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

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

      $places = R::findAll('place', 'del is null ');
      $this->smarty->assign('places', $places);

      $four_ds = R::findAll('four_d', 'del is null ');
      $this->smarty->assign('four_ds', $four_ds);

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

   function add4DListEx($ancSheetId, $patientId) {

      if ($ancSheetId > 0) {
         $op_4d_list = R::findOne('op_4d_list', 'ancsheetid = ? and deleted = 0', [$ancSheetId]);
         if (count($op_4d_list) > 0) {
            return $op_4d_list->id;
         } else {
            $insertDataVisits = R::xdispense('op_4d_list');
            $insertDataVisits->patientid = $patientId;
            $insertDataVisits->opdate = date('Y-m-d');
            $insertDataVisits->four_d = 0;
            $insertDataVisits->place = 0;
            $insertDataVisits->notes = '';
            $insertDataVisits->ancsheetid = $ancSheetId;
            $insertDataVisits->deleted = 0;
            $insertDataVisits->createdate = date('Y-m-d h:i:s');
            $insertDataVisits->user_id = $_SESSION['user_id'];

            try {
               $insert = R::store($insertDataVisits);
               return $insert;
            } catch (Exception $ex) {
               return -1;
            }
         }
      } else {
         return -1;
      }
   }

   public function add4DList() {
      //check login
      autho::checkautho($this->hosturl);
      //check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      //prepar wife data insert
      $patientId = filter_input(INPUT_POST, 'patientid');
      $opDate = date('Y/m/d', strtotime(filter_input(INPUT_POST, 'opdate')));
      $place = filter_input(INPUT_POST, 'placeW');
      $notes = filter_input(INPUT_POST, "notes");

      $four_d = implode(',', $_POST['four_d']);

      // ancsheet
      $ancsheet = R::findOne('ancsheet', 'patientid = ? and endpreg = 0', [$patientId]);

      if (count($ancsheet) > 0) {
         $insertDataVisits = R::xdispense('op_4d_list');
         $insertDataVisits->patientid = $patientId;
         $insertDataVisits->opdate = $opDate;
         $insertDataVisits->four_d = $four_d;
         $insertDataVisits->place = $place;
         $insertDataVisits->notes = $notes;
         $insertDataVisits->ancsheetid = $ancsheet->id;
         $insertDataVisits->deleted = 0;
         $insertDataVisits->createdate = date('Y-m-d h:i:s');
         $insertDataVisits->user_id = $_SESSION['user_id'];

         try {
            $insert = R::store($insertDataVisits);

            if ($insert) {
               echo 1;
            } else {
               echo -1;
            }
         } catch (Exception $ex) {
            echo -1;
         }
      } else {
         echo -2;
      }
   }

   function reload4DVisits() {

      $weekFrom = filter_input(INPUT_POST, "date_from");
      $weekTo = filter_input(INPUT_POST, "date_to");
      $patientId = filter_input(INPUT_POST, "patientId");
      $weekFrom--;
      $weekTo++;
      $this->load4DVisits($weekFrom, $weekTo, $patientId);
   }

   function load4DVisits($weekFrom, $weekTo, $patientId) {

      if ($weekTo > 0) {
         $dateFrom = date("Y/m/d", strtotime("- " . $weekTo . " weeks"));
      }

      if ($weekFrom > 0) {
         $dateTo = date("Y/m/d", strtotime("- " . $weekFrom . " weeks"));
      }

      $allvisit = $this->listVisits4D($weekFrom, $weekTo, $dateFrom, $dateTo, $patientId);
      $this->smarty->assign('allvisit', $allvisit);
      $this->smarty->display('operation/listdivfut_4d.html');
   }

   function listVisits4D($weekFrom, $weekTo, $dateFrom, $dateTo, $patientId) {

      $weekFrom++;
      $weekTo--;

      if ($patientId > 0) {
         $sql = '  and    list.patientid =  ' . $patientId;
      } else {
         $sql = '  and  ancsheet.sheetlmp  between  "' . $dateFrom . '"   and "' . $dateTo . '"    
                    ORDER BY ancsheet.sheetlmp Desc ';
      }

      $allvisit = $this->list4DSqlEx($weekFrom, $weekTo, $sql, $patientId);

      return $allvisit;
   }

   function list4DSqlEx($weekFrom, $weekTo, $sqlExt, $patientId) {

      $sql = '       select  list.id as id   , list.four_d as  fourDIds , t1user.name as t1UserName 
                            , list.notes     , patients.wifename  as patientName    , t2user.name as t2UserName 
                             , patients.statusno  as patientNo   , patients.husdandname  as husbandName 
                             , patients.address, patients.phone , "" as  four_d  , list.done  , list.confirm
                             , ancsheet.sheetedd , ancsheet.sheetlmp   , list.t1 , list.t11 , list.t12 , list.t2 , list.t21 , list.t22 
                            
                            from      op_4d_list       list 
                            left join   awusers   t1user            on t1user.user_id = list.t1_userid   
                              left join   awusers   t2user            on t2user.user_id = list.t2_userid   
                             left join   ancsheet            on ancsheet.id = list.ancsheetid   
                            join patients                on patients.id = list.patientid


                    where    list.deleted = 0 and  ancsheet.endpreg != 1          ' . $sqlExt;

      $allvisit = R::getAll($sql);
      $visits = $this->list4DCommon($weekFrom, $weekTo, $allvisit, $patientId);
      return $visits;
   }

   function list4DCommon($weekFrom, $weekTo, $allvisit, $patientId) {
      $j = 0;
      foreach ($allvisit as $data) {
         $fourDIds = explode(',', $data['fourDIds']);
         $four_d = '';
         $i = 1;
         foreach ($fourDIds as $id) {
            $d4 = R::load('four_d', $id);
            if ($i > 1) {
               $four_d .= ' , ';
            }
            $four_d .= $d4->title;
            $i++;
         }
         $allvisit[$j]['four_d'] = $four_d;
         //   $allvisit[$j]['opdate'] = date('Y/m/d', strtotime($allvisit[$j]['opdate']));

         $diff = round(abs(strtotime(date('Y/m/d')) - strtotime($allvisit[$j]['sheetlmp'])) / 86400);
         $allvisit[$j]['weeks'] = intval($diff / 7) . 'W ' . ($diff % 7) . 'D';

         if ($patientId > 0) {
            $allvisit[$j]['is_show'] = 1;
         } else {
            if ((intval($diff / 7)) >= $weekFrom && (intval($diff / 7)) <= $weekTo) {
               $allvisit[$j]['is_show'] = 1;
            } else {
               $allvisit[$j]['is_show'] = 0;
            }
         }
         $j++;
      }
      return $allvisit;
   }

   public function updateajax() {

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

      $id = filter_input(INPUT_POST, "id");
      $tablename = filter_input(INPUT_POST, "tableName");
      $colname = filter_input(INPUT_POST, "colName");
      $value = filter_input(INPUT_POST, "value");

      try {
         $gyna_obj = R::load($tablename, $id);
         $gyna_obj->$colname = $value;

         if ($tablename == 'op_4d_list' && $colname == 't1') {
            $gyna_obj->t1_userid = $_SESSION['user_id'];
         } elseif ($tablename == 'op_4d_list' && $colname == 't2') {
            $gyna_obj->t2_userid = $_SESSION['user_id'];
         }
         R::store($gyna_obj);
         //   print_r($gyna_obj);
      } catch (Exception $e) {
         echo $e;
      }
   }

   public function editvisit4d() {
      $visitId = filter_input(INPUT_POST, "visitId");
      $visit = R::load('op_4d_list', $visitId);

      $visit->opdate = date("Y/m/d", strtotime($visit->opdate));
      $patient = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");

      $result = array(
          "opdate" => date("Y/m/d", strtotime($visit->opdate)),
          "patientid" => $visit->patientid,
          "statusno" => $patient['statusno'],
          "four_d" => $visit->four_d,
          "place" => $visit->place,
          "notes" => $visit->notes
      );

      echo json_encode($result);
   }

   public function updatevisit4d() {
//check login
      autho::checkautho($this->hosturl);

      $visitId = filter_input(INPUT_POST, "mVisitId");
      $patientId = filter_input(INPUT_POST, 'patientid');
      $opDate = date('Y/m/d', strtotime(filter_input(INPUT_POST, 'opdate')));
      $place = filter_input(INPUT_POST, 'placeW');
      $notes = filter_input(INPUT_POST, "notes");

      $four_d = implode(',', $_POST['four_d']);

      $visit = R::load('op_4d_list', $visitId);

      if ($patientId != $visit->patientid) {
         $ancsheet = R::findOne('ancsheet', 'patientid = ? and endpreg = 0', [$patientId]);
         $visit->ancsheetid = $ancsheet->id;
      }

      $visit->patientid = $patientId;
      $visit->opdate = $opDate;
      $visit->four_d = $four_d;
      $visit->place = $place;
      $visit->notes = $notes;

      R::store($visit);

      echo $visitId;
   }

   function sendToVisits() {
      $id = filter_input(INPUT_POST, "visitId");
      $list = R::load('op_4d_list', $id);
      $det = R::load('detections', 36);

      $newOrder = 1;
      $data = R::getRow("SELECT MAX(enterordered) as last_order   FROM visits ");
      if ($data['last_order'] >= 1) {
         $newOrder = $data['last_order'] + 1;
      }
      date_default_timezone_set('Africa/Cairo');
      session_start();

      $insertDataVisits = R::dispense('visits');
      $insertDataVisits->patientid = $list->patientid;
      $insertDataVisits->visitdate = date('Y-m-d');
      $insertDataVisits->detectionid = 36;
      $insertDataVisits->detectionvalue_cash = 0;
      $insertDataVisits->detectionvalue_visa = 0;
      $insertDataVisits->totaldetectionvalue = $det->detectionval;
      $insertDataVisits->discount = 0;
      $insertDataVisits->restdetectionvalue = $det->detectionval;
      $insertDataVisits->visit_period = 1;
      $insertDataVisits->mobileappvisit = 0;
      $insertDataVisits->payedflag = 0;
      $insertDataVisits->urgent = 0;
      $insertDataVisits->enterordered = $newOrder;
      $insertDataVisits->visitorder = 0;
      $insertDataVisits->createdate = date('Y-m-d h:i:s');
      $insertDataVisits->user_id = $_SESSION['user_id'];
      $insertDataVisits->notes = '';

      $insertDataVisits->approx_time = date("H:i:s");

      try {
         $insert = R::store($insertDataVisits);

         if ($insert) {
            echo 1;
         } else {
            echo -1;
         }
      } catch (Exception $ex) {
         echo -1;
      }
   }

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