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

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

  $allCharities = R::getAll('select * from charities where del < 2' . $searchQuery);
  $smarty->assign('allCharities', $allCharities);

  $smarty->display("subventionview/add.html");
  $smarty->assign("charity", 1);
  $smarty->display("footer.html");
} else if ($do == "show") {
  header('location:subventionController.php');
} else if ($do == 'savedata') {
  savedata();
} else if ($do == 'showajax') {
  showajax();
} else if ($do == 'removecontroller') {
  removecontroller();
} elseif ($do == "getBeneficiaries") {
  $charity_id = filter_input(INPUT_POST, 'id');
  $allBen = R::getAll('SELECT beneficiaries.* from beneficiaries left join subvention ON subvention.beneficier_id = beneficiaries.id where subvention.beneficier_id is Null and beneficiaries.charity_id = ' . $charity_id . ' and beneficiaries.del <2');
  if (count($allBen) > 0) {
    $smarty->assign('allBen', $allBen);
    $smarty->display('subventionview/benef_tbl.html');
  } else {
    echo -1;
  }
} else if ($do == 'saveguarantee_type') {
  saveGurantee();
} else if ($do == 'gettabledata') {
  gettabledata();
}


function savedata()
{
  $today = date("Y-m-d H:i:s");
  $date = date('Y-m-d');
  $userid = $_SESSION['userid'];

  $charity_id = filter_input(INPUT_POST, 'charity_id');
  $itr = filter_input(INPUT_POST, 'itr');
  var_dump($_POST);
  try {
    for ($i = 1; $i <= $itr; $i++) {
      $beneficier_id = filter_input(INPUT_POST, 'id' . $i);
      $financial_aid = filter_input(INPUT_POST, 'financial_aid' . $i);
      $inkind_aid = filter_input(INPUT_POST, 'inkind_aid' . $i);
      $guarantee_type_id = filter_input(INPUT_POST, 'guarantee_type_id' . $i);
      $notes = filter_input(INPUT_POST, 'notes' . $i);
      if ($beneficier_id && $charity_id) {
        $subvention = R::dispense('subvention');
        $subvention->del = 0;
        $subvention->sysdate = $today;
        $subvention->user_id = $userid;
        $subvention->charity_id = $charity_id;
        $subvention->beneficier_id = $beneficier_id;
        $subvention->financial_aid = $financial_aid;
        $subvention->inkind_aid = $inkind_aid;
        $subvention->guarantee_type_id = $guarantee_type_id;
        $subvention->notes = $notes;
      }
      $subventionid = R::store($subvention);
    }
    echo 1;
  } catch (Exception $e) {
    echo 0;
  }
}
function showajax()
{
  $columns = array('id', 'id', 'subventionname', 'subventionnumber', 'subventionphone', 'sysdate', '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 subvention.id = " . $data1 . " ";
  }
  if ($del == '') {
    $searchQuery .= " and subvention.del < 2 ";
  }

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

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

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


  if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= 'and ( subvention.id LIKE " % ' . $_POST["search"]["value"] . ' %" 
                    OR subvention.subventionnumber LIKE "%' . $_POST["search"]["value"] . '%"
                    OR subvention.subventionphone LIKE "%' . $_POST["search"]["value"] . '%"
                    OR subvention.sysdate LIKE "%' . $_POST["search"]["value"] . ' % "
                    OR subvention.subventionname LIKE "%' . $_POST["search"]["value"] . '%"
                    )';
  }

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

  $totals = R::count('subvention', 'LEFT JOIN user
         ON subvention.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 subvention.* FROM `subvention` LEFT JOIN user
         ON subvention.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["subventionimage"] != "." && $row["subventionimage"] != "") {
      $sub_array[] = '<img src="../views/default/images/subvention/' . $row["subventionimage"] . '"  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["subventionname"];
    $sub_array[] = $row["subventionnumber"];
    $sub_array[] = $row["subventionphone"];
    $sub_array[] = $row["sysdate"];
    if ($row["del"] < 2) {
      $sub_array[] = '<a href="subventionController.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="subventionController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
    } else  if ($row["del"] == 5) {
      $sub_array[] = '<a href="subventionController.php?do=edit&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lg editicon"></a>';
    } else {
      $sub_array[] = '<a href="subventionController.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('subvention', $id);
  $tables->del = 2;
  $tables->del_date = $today;
  $tables->deluserid = $userid;
  try {
    R::store($tables);
    echo 1;
  } catch (Exception $e) {
    echo 0;
  }
}

function saveGurantee()
{
  $today = date("Y-m-d H:i:s");
  $date = date('Y-m-d');
  $userid = $_SESSION['userid'];
  $name = filter_input(INPUT_POST, 'name');
  $guarantee_type_id = filter_input(INPUT_POST, 'guarantee_type_id');
  $selectitr  = filter_input(INPUT_POST, 'selectitr');
  try {
    if (!$guarantee_type_id) {
      $guarantee_type = R::dispense('guaranteetype');
      $guarantee_type->user_id = $userid;
      $guarantee_type->sysdate = $date;
    } else {
      $guarantee_type = R::load('guaranteetype', $guarantee_type_id);
      $text = $name;
    }
    $guarantee_type->name = $name;
    $guarantee_type_id = R::store($guarantee_type);

    $last = R::getROW("SELECT id, name FROM `guaranteetype` order by id desc");
    $guarantee_type_id = $guarantee_type_id;
    $text = $name;
    echo json_encode(array('id' => $guarantee_type_id, 'selectname' => 'guarantee_type_id', 'selectid' => 'guarantee_type_id', 'text' => $text, 'selectid' => 'guarantee_type_id', 'selectitr' => 'guarantee_type_id'));
  } catch (Exception $e) {
    echo 0;
  }
}

function gettabledata()
{
  $table = $_POST['table'];
  $tableid = $_POST['tableid'];
  $tableval = $_POST['tableval'];
  $join = $_POST['join'];
  $tableid = $table . "." . $tableid;
  $getdata = R::getRow("SELECT * FROM $table $join WHERE $tableid = ?", [$tableval]);
  echo json_encode($getdata);
}
