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

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

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

  $allCenters = R::getAll('select * from charitiescenter where del < 2');
  $smarty->assign('allCenters', $allCenters);

  $smarty->display("charityview/add.html");
  $smarty->assign("charity", 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);
  }

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

  $id = filter_input(INPUT_GET, 'id');
  $charitydata = R::load('charities', $id);
  $smarty->assign('charitydata', $charitydata);

  $allCenters = R::getAll('select * from charitiescenter where del < 2');
  $smarty->assign('allCenters', $allCenters);

  $smarty->display("header.html");
  $smarty->display("charityview/edit.html");
  $smarty->assign("charity", 1);
  $smarty->display("footer.html");
} else if ($do == 'savedata') {
  savedata();
} else if ($do == 'showajax') {
  showajax();
} else if ($do == 'removecontroller') {
  removecontroller();
} else if ($do == 'removeAllBen') {
  removeAllBen();
}


function savedata()
{
  $today = date("Y-m-d H:i:s");
  $date = date('Y-m-d');
  $userid = $_SESSION['userid'];
  $charityname = filter_input(INPUT_POST, 'charityname');
  $createdate = filter_input(INPUT_POST, 'createdate');
  $charityphone = filter_input(INPUT_POST, 'charityphone');
  $charitynumber = filter_input(INPUT_POST, 'charitynumber');
  $charityaddress = filter_input(INPUT_POST, 'charityaddress');
  $charitynote = filter_input(INPUT_POST, 'charitynote');
  $center_id = filter_input(INPUT_POST, 'center_id');
  $charityid = filter_input(INPUT_POST, 'charityid');

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

    $charities->del = 1;
    $charities->update_date = $today;
    $charities->updateuserid = $userid;
    $handle = new upload($_FILES['charityimage']);
    $charityimage = updateImages($handle, "oldcharityimage", "../views/default/images/charities", 300, 300);
    unlink("../views/default/images/charities" . $charities->charityimage);
  }
  $charities->charityname  = $charityname;
  $charities->charitynumber = $charitynumber;
  $charities->charityphone = $charityphone;
  $charities->charityaddress = $charityaddress;
  $charities->charityimage = $charityimage;
  $charities->charitynote = $charitynote;
  $charities->createdate = $createdate;
  $charities->center_id = $center_id;
  try {
    $charityid = R::store($charities);
    echo 1;
  } catch (Exception $e) {
    echo 0;
  }
}
function showajax()
{
  $columns = array('id', 'id', 'charityname', 'charitynumber', 'charityphone', 'sysdate', 'added_benef', 'payed_benef', 'id', 'id','id');
  $start_date = $_POST['start_date'];
  $end_date   = $_POST['end_date'];
  $del        = $_POST['del'];
  $data1      = $_POST['data1'];
  $data2      = $_POST['data2'];
  $data3      = $_POST['data3'];

  $searchQuery = " ";
  if ($data1 != '') {
    $searchQuery .=  " and charities.id = " . $data1 . " ";
  }
  if ($del == '') {
    $searchQuery .= " and charities.del < 2 ";
  }

  if ($data3 != '') {
    $searchQuery .= " and charities.branchid = " . $data3 . " ";
  }

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

  if ($_SESSION['charityids'] && !$data1)
    $searchQuery .= ' and charities.id in(' . $_SESSION['charityids'] . ')';


  if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= 'and ( charities.id LIKE " % ' . $_POST["search"]["value"] . ' %" 
                    OR charities.charitynumber LIKE "%' . $_POST["search"]["value"] . '%"
                    OR charities.charityphone LIKE "%' . $_POST["search"]["value"] . '%"
                    OR charities.sysdate LIKE "%' . $_POST["search"]["value"] . ' % "
                    OR charities.charityname LIKE "%' . $_POST["search"]["value"] . '%"
                    )';
  }

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

  $totals = R::count('charities', 'LEFT JOIN user
         ON charities.user_id = user.userid WHERE 1 ' . $searchQuery . ' ');

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

  $rResult = R::getAll('SELECT charities.* FROM `charities` LEFT JOIN user
         ON charities.user_id = user.userid  WHERE 1 ' . $searchQuery . ' ');
  $apps = count($rResult);

  $output = array(
    "draw" => intval($_POST["draw"]),
    "recordsTotal" => intval($apps),
    "recordsFiltered" => $totals,
    "data" => array()
  );

  foreach ($rResult as $row) {
    $date = date('Y-m-d');
    $sub_array = array();
    $sub_array[] = $row["id"];
    if ($row["charityimage"] != "." && $row["charityimage"] != "") {
      $sub_array[] = '<img src="../views/default/images/charities/' . $row["charityimage"] . '"  style="width: 40px;height: 40px;border: 1px solid;border-radius: 6px;">';
    } 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["charityname"];
    $sub_array[] = $row["charitynumber"];
    $sub_array[] = $row["charityphone"];
    $sub_array[] = $row["sysdate"];
    $sub_array[] = R::getCell('select COUNT(id) from beneficiaries where del < 2 and charity_id = ' . $row['id']);
    $sub_array[] = R::getCell('select COUNT(DISTINCT benefeciary_id) from subventionpay where del < 2 and charity_id = ' . $row['id']);
    if ($row["del"] < 2) {
      $sub_array[] = '<a href="charityController.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="charityController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
      // if($_SESSION['userid'] <= 1)
      //   $sub_array[] = '<a href="javascript:;" data-id="' . $row["id"] . '" data-controll="charityController" type="button" class="btn btn-default btn-lg removeicon removeAllBen"  ></a>';
    } else  if ($row["del"] == 5) {
      $sub_array[] = '<a href="charityController.php?do=edit&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lg editicon"></a>';
    } else {
      $sub_array[] = '<a href="charityController.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('charities', $id);
  $tables->del = 2;
  $tables->del_date = $today;
  $tables->deluserid = $userid;
  try {
    R::store($tables);
    echo 1;
  } catch (Exception $e) {
    echo 0;
  }
}

function removeAllBen()
{
  $id = filter_input(INPUT_POST, 'id');
  try {
    R::exec('DELETE FROM beneficiaries where charity_id = '.$id);
    R::exec('DELETE FROM subvention where charity_id = '.$id);
    R::exec('DELETE FROM subventionpay where charity_id = '.$id);
    echo 1;
  } catch (Exception $e) {
    echo 0;
  }
}
