<?php
include("../public/impOpreation.php");
include("../library/uploadImages.php");



//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);

//USERGROUP
$UsergroupDAO = new UsergroupMySqlDAO();
$Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
$smarty->assign("Usergroupdata", $Usergroupdata);

//lang
$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/sellbill/sellbill.php");

$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");

if (empty($do)) {
  $smarty->display("header.html");

  $userData = R::getRow('SELECT * FROM user WHERE userid = ?', [$_SESSION['userid']]);
  if ($userData['viewclients'] == 1) {
    $allClients = R::getAll('select * from client where conditions = 0');
  } else {
    $allClients = R::getAll('select * from client where conditions = 0 and delegateid = ?', [$_SESSION['userid']]);
  }
  $smarty->assign('allClients', $allClients);

  $allChasis = R::getCol('SELECT chassisNo from productserial join buybill on buybillid = billid where chassisNo != "" and del = 0 and conditions = 0');
  $smarty->assign('allChasis', $allChasis);

  $smarty->display("importcontractview/add.html");
  $smarty->assign("importcontract", 1);
  $smarty->assign('customsellbillModel', 1);
  $smarty->display("footer.html");
} elseif ($do == "show") {
  include_once("../public/authentication.php");
  $show = filter_input(INPUT_GET, 'show');
  if ($show == 2) {
    $smarty->assign('show', 2);
  }

  $userData = R::getRow('SELECT * FROM user WHERE userid = ?', [$_SESSION['userid']]);
  if ($userData['viewclients'] == 1) {
    $allClients = R::getAll('select * from client where conditions = 0');
  } else {
    $allClients = R::getAll('select * from client where conditions = 0 and delegateid = ?', [$_SESSION['userid']]);
  }
  $smarty->assign('allClients', $allClients);

  $smarty->assign('date', $date);
  $smarty->display("header.html");
  $smarty->display("importcontractview/show.html");
  $smarty->assign("importcontract", 1);
  $smarty->display("footer.html");
} elseif ($do == "edit") {
  include_once("../public/authentication.php");

  $id = filter_input(INPUT_GET, 'id');
  $contractdata = R::load('importcontract', $id);
  $smarty->assign('customsellbillModel', 1);
  $smarty->assign('contractdata', $contractdata);

  $userData = R::getRow('SELECT * FROM user WHERE userid = ?', [$_SESSION['userid']]);
  if ($userData['viewclients'] == 1) {
    $allClients = R::getAll('select * from client where conditions = 0');
  } else {
    $allClients = R::getAll('select * from client where conditions = 0 and delegateid = ?', [$_SESSION['userid']]);
  }
  $smarty->assign('allClients', $allClients);
  
  $allChasis = R::getCol('SELECT chassisNo from productserial join buybill on buybillid = billid where chassisNo != "" and del = 0 and conditions = 0');
  $smarty->assign('allChasis', $allChasis);

  $clientid = $contractdata->clientid;
  $myclientdata = R::getRow('SELECT * FROM client WHERE clientid = ?', [$clientid]);
  $smarty->assign("myclientdata", $myclientdata);

  $smarty->display("header.html");
  $smarty->display("importcontractview/edit.html");
  $smarty->assign("importcontract", 1);
  $smarty->display("footer.html");
} else if ($do == 'savedata') {
  savedata();
} else if ($do == 'showajax') {
  showajax();
} else if ($do == 'removecontroller') {
  removecontroller();
} else if ($do == 'getChasisData') {
  $chasisNo = filter_input(INPUT_POST, 'chassisNo');
  if ($chasisNo) {
    $chasisData = R::getRow('SELECT carnumber,carmotor,IF(cartype = 0, "جديد", "مستعمل") as cartype FROM importcontract WHERE chasisno = ?', [$chasisNo]);
    if ($chasisData) {
      echo json_encode($chasisData);
    } else {
      echo -1;
    }
  } else {
    echo -1;
  }
}elseif($do == "checkExist"){
  $chasisNo = filter_input(INPUT_POST, 'chasis');
  $id = filter_input(INPUT_POST, 'id');
  $qs = "";
  if($id > 0)
    $qs .= " and id != $id";

  if ($chasisNo) {
    $exist = R::getCell('SELECT COUNT(*) FROM importcontract WHERE chasisno = ? '.$qs, [$chasisNo]);
    echo $exist > 0 ? 1 : 0;
  } else {
    echo -1;
  }
}


function savedata()
{
  $today = date("Y-m-d H:i:s");
  $date = date('Y-m-d');
  $userid = $_SESSION['userid'];
  $clientid = filter_input(INPUT_POST, 'clientid');
  $brand = filter_input(INPUT_POST, 'brand');
  $carcolor = filter_input(INPUT_POST, 'carcolor');
  $carmodel = filter_input(INPUT_POST, 'carmodel');
  $chasisno = filter_input(INPUT_POST, 'chasisno');
  $cartype = filter_input(INPUT_POST, 'cartype');
  $contractvalue = filter_input(INPUT_POST, 'contractvalue');
  $carnumber = filter_input(INPUT_POST, 'carnumber');
  $carmotor = filter_input(INPUT_POST, 'carmotor');
  $notes = filter_input(INPUT_POST, 'notes');

  $contractid = filter_input(INPUT_POST, 'contractid');

  if (!$contractid) {
    $contracts = R::dispense('importcontract');
    $contracts->del = 0;
    $contracts->sysdate = $today;
    $contracts->user_id = $userid;
    $contracts->del_date = '';
    $contracts->deluserid = '';
    $handle = new upload($_FILES['contractimage']);
    $contractimage = uploadImages($handle, "../views/default/images/importcontract", 300, 300);
  } else {
    $contracts = R::load('importcontract', $contractid);

    $contracts->del = 1;
    $contracts->update_date = $today;
    $contracts->updateuserid = $userid;
    $handle = new upload($_FILES['contractimage']);
    $contractimage = updateImages($handle, "oldcontractimage", "../views/default/images/importcontract", 300, 300);
    unlink("../views/default/images/importcontract" . $contracts->contractimage);
  }
  $contracts->contractimage = $contractimage;
  $contracts->clientid = $clientid;
  $contracts->brand = $brand;
  $contracts->carcolor = $carcolor;
  $contracts->carmodel = $carmodel;
  $contracts->chasisno = $chasisno;
  $contracts->cartype = $cartype;
  $contracts->contractvalue = $contractvalue;
  $contracts->carnumber = $carnumber;
  $contracts->carmotor = $carmotor;
  $contracts->notes = $notes;

  try {
    $contractid = R::store($contracts);
    echo 1;
  } catch (Exception $e) {
    echo 0;
  }
}
function showajax()
{
  $columns = array('id', 'id', 'clientname', 'contractimg', 'sysdate', 'id', 'id', 'id');
  $start_date = $_POST['start_date'];
  $end_date   = $_POST['end_date'];
  $del        = $_POST['del'];
  $data1      = $_POST['data1'];

  $searchQuery = " ";
  if ($del == '') {
    $searchQuery .= " and importcontract.del < 2 ";
  }

  if ($data1 != '') {
    $searchQuery .= " and importcontract.clientid = " . $data1 . " ";
  }

  if ($start_date != '') {
    $searchQuery .= 'and  DATE(importcontract.sysdate)  >= "' . $start_date . '"';
  }
  if ($end_date != '') {
    $searchQuery .= 'and DATE(importcontract.sysdate) <= "' . $end_date . '" ';
  }

  if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= 'and ( importcontract.id LIKE " % ' . $_POST["search"]["value"] . ' %" 
                    OR importcontract.sysdate LIKE "%' . $_POST["search"]["value"] . ' % "
                    OR client.clientname like "%' . $_POST["search"]["value"] . '%"
                    )';
  }

  if (isset($_POST["order"])) {
    $searchQuery .= 'ORDER BY ' . $columns[$_POST['order']['0']['column']] . ' ' . $_POST['order']['0']['dir'] . '  ';
  } else {
    $searchQuery .= "ORDER BY  importcontract.id DESC ";
  }

  $totals = R::getCell('SELECT count(id) FROM `importcontract` join client on client.clientid = importcontract.clientid WHERE 1 ' . $searchQuery . ' ');

  if (isset($_POST['start']) && $_POST['length'] != '-1') {
    $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
      intval($_POST['length']);
  }

  $rResult = R::getAll('SELECT importcontract.*, client.clientname FROM `importcontract` join client on client.clientid = importcontract.clientid WHERE 1 ' . $searchQuery . ' ');
  $apps = count($rResult);

  $output = array(
    "draw" => intval($_POST["draw"]),
    "recordsTotal" => intval($apps),
    "recordsFiltered" => $totals ? $totals : 0,
    "data" => array()
  );
  foreach ($rResult as $row) {
    $date = date('Y-m-d');
    $sub_array = array();
    $sub_array[] = $row["id"];
    $sub_array[] = $row['clientname'];

    if ($row["contractimage"] != "." && $row["contractimage"] != "") {
      $sub_array[] = '<a href="../views/default/images/importcontract/' . $row["contractimage"] . '" target="_blank" class="btn btn-success">عرض</a>';
    } else {
      $sub_array[] = ' <img src="../views/default/assets/img/blank.png"  style="width: 40px;height: 40px;border: 1px solid;border-radius: 6px;" alt="" class="card-img">';
    }
    $sub_array[] = $row["sysdate"];
    if ($row["del"] < 2) {
      $sub_array[] = '<a href="importContractController.php?do=edit&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lg editicon"></a>';
      $sub_array[] = '<a href="javascript:;" data-id="' . $row["id"] . '" data-controll="importContractController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
    } else  if ($row["del"] == 5) {
      $sub_array[] = '<a href="importContractController.php?do=edit&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lg editicon"></a>';
    } else {
      $sub_array[] = '<a href="importContractController.php?do=edit&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
      $sub_array[] = 'محذوف ';
    }

    $output['data'][] = $sub_array;
  }

  echo json_encode($output, JSON_UNESCAPED_SLASHES);
}


function removecontroller()
{
  $today = date("Y-m-d H:i:s");
  $date = date('Y-m-d');
  $userid = $_SESSION['userid'];
  $id = filter_input(INPUT_POST, 'id');
  $tables = R::load('importcontract', $id);
  $tables->del = 2;
  $tables->del_date = $today;
  $tables->deluserid = $userid;
  try {
    R::store($tables);
    echo 1;
  } catch (Exception $e) {
    echo 0;
  }
}
