<?php
require_once __DIR__ . '/../magic/auth.php';

$auth = bdr_require_privilege([5, 20], '../logout.php');
$user = $auth['user_id'];
$father = $auth['user_id'];
$branch = $auth['branch'];
$conn = $auth['conn'];
$db = $auth['conn'];

if (isset($_POST['hj1'])) {
  $start       = $_POST["hj1"];
  $endd      = $_POST["hj2"];
  $ak_id   = $_POST["ak_id"];
  $msg = 0;
  for ($count = 0; $count < count($_POST["ak_id"]); $count++) {
    if (empty($start[$count])) {
      return;
    }
    if (empty($endd[$count])) {
      return;
    }
    if (empty($ak_id[$count])) {
      return;
    }
    $sql = $db->prepare(" UPDATE aksat_in set start = ? , endd = ? where ak_id = ?");
    $sql->bindParam(1, $start[$count]);
    $sql->bindParam(2, $endd[$count]);
    $sql->bindParam(3, $ak_id[$count]);
    if ($sql->execute()) {
      $msg = $msg + 1;
    } else {
      $msg = "يوجد خطأ في تسجيل البيانات";
    }
  }
  echo $msg;
}
if (isset($_POST['payed'])) {
  $data = array();
  $ak_id      = $_POST["ak_id"];
  $payed      = $_POST["payed"];
  $printed_no = $_POST["printed_no"];
  $comm       = $_POST["comm"];
  $payMethod  = $_POST["payMethod"];
  $late = 0;
  $date_payed = date("Y-m-d");
  if (empty($father)) {
    exit();
  }
  if (empty($ak_id)) {
    exit();
  }
  $st = $db->prepare("SELECT start ,contract_id from aksat_in where ak_id = ?");
  $st->bindParam(1, $ak_id);
  $st->execute();
  if ($st->rowCount() > 0) {
    $wow = $st->fetch(PDO::FETCH_ASSOC);
    $start          = $wow["start"];
    $contract_id     = $wow["contract_id"];
  }
  if ($date_payed > $start) {
    $date1 = new DateTime($start);
    $date2 = new DateTime($date_payed);
    $late = $date2->diff($date1)->format("%a");
  }
  $sql = $db->prepare(" UPDATE aksat_in set payed = ? , date_payed = ? ,printed_no = ?,payMethod = ? ,late = ? ,comm = ? ,father = ?  where ak_id = ?");
  $sql->bindParam(1, $payed);
  $sql->bindParam(2, $date_payed);
  $sql->bindParam(3, $printed_no);
  $sql->bindParam(4, $payMethod);
  $sql->bindParam(5, $late);
  $sql->bindParam(6, $comm);
  $sql->bindParam(7, $father);
  $sql->bindParam(8, $ak_id);
  if ($sql->execute()) {
    $data["msg"] = "<div class='alert alert-success'>
                            <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                            <b>تم تسجيل سند القبض بنجاح. </b>
                            </div>";
    $last = $db->prepare("SELECT ak_id from aksat_in where date_payed IS NULL AND contract_id = ?");
    $last->bindParam(1, $contract_id);
    $last->execute();
    if ($last->rowCount() < 1) {
      $sql = $db->prepare(" UPDATE aksat_contract set status = 3 where contract_id = ?");
      $sql->bindParam(1, $contract_id);
      $sql->execute();
      $maxsql = $db->prepare("SELECT max(tash_id) as maxd FROM tash_in");
      $maxsql->execute();
      if ($maxsql->rowCount() > 0) {
        $row = $maxsql->fetch(PDO::FETCH_ASSOC);
        $maxD = $row['maxd'] + 1;
      } else {
        $maxD = 1;
      }
      $ww = $db->prepare("SELECT tash FROM aksat_contract where contract_id = ?");
      $ww->bindParam(1, $contract_id);
      $ww->execute();
      if ($ww->rowCount() > 0) {
        $w = $ww->fetch(PDO::FETCH_ASSOC);
        $wanted = $w['tash'];
      }
      $start = date('Y-m-d', strtotime($start . ' + 3 month'));
      $endd = date('Y-m-d', strtotime($start . ' - 1 days'));
      $endd  = date('Y-m-d', strtotime($endd . ' + 1 month'));
      $new_tash = $db->prepare("INSERT INTO tash_in(tash_id, contract_id, wanted, start, endd)
                                    values(?,?,?,?,?)");
      $new_tash->bindParam(1, $maxD);
      $new_tash->bindParam(2, $contract_id);
      $new_tash->bindParam(3, $wanted);
      $new_tash->bindParam(4, $start);
      $new_tash->bindParam(5, $endd);
      $new_tash->execute();
    }
  } else {
    $data["error"] = "<div class='alert alert-danger'>
                <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                <b>يوجد خطأ في تسجيل البيانات ... راجع  من فضلك</b>
                </div> ";
  }
}
// under constraction
if (isset($_POST['tarheel'])) {
  include "../actions/dbPDO.php";
  $date_payed  = date("Y-m-d");
  $contract_id = $_POST["tarheel"];
  $py = $db->prepare("SELECT sum(money_in) as cash , ak_id from aksat_payed 
                      where contract_id = ? AND tarheel = 1 GROUP BY ak_id");
  $py->bindParam(1, $contract_id);
  $py->execute();
  if ($py->rowCount() > 0) {
    $wow = $py->fetch(PDO::FETCH_ASSOC);
    $ak_id   = $wow["ak_id"];
    $cash   = $wow["cash"];
  }
  $last_kest = $db->prepare("SELECT min(ak_id) as ak_id from aksat_in where contract_id = ? AND payed IS NULL");
  $last_kest->bindParam(1, $contract_id);
  $last_kest->execute();
  if ($last_kest->rowCount() > 0) {
    $ak = $last_kest->fetch(PDO::FETCH_ASSOC);
    $minID = $ak['ak_id'];
  }
  $last_kest = $db->prepare("SELECT  ak_id , wanted , start,ak_no from aksat_in where ak_id = ? ");
  $last_kest->bindParam(1, $minID);
  $last_kest->execute();
  if ($last_kest->rowCount() > 0) {
    $ak = $last_kest->fetch(PDO::FETCH_ASSOC);
    $ak_id2 = $ak['ak_id'];
    $wanted = $ak['wanted'];
    $start = $ak['start'];
  }

  if (($ak_id == $ak_id2) && ($cash == $wanted)) {
    $sql = $db->prepare(" UPDATE aksat_payed set tarheel = 2 where ak_id = ?");
    $sql->bindParam(1, $ak_id);
    if ($sql->execute()) {
      $sql2 = $db->prepare(" UPDATE aksat_in set payed = ? , date_payed = ? ,comm = 'مرحل',payMethod = 1 ,late = ? ,father = ?  where ak_id = ?");
      $sql2->bindParam(1, $cash);
      $sql2->bindParam(2, $date_payed);
      $sql2->bindParam(3, $late);
      $sql2->bindParam(4, $father);
      $sql2->bindParam(5, $ak_id);
      if ($sql2->execute()) {
        $last = $db->prepare("SELECT ak_id from aksat_in where date_payed IS NULL AND contract_id = ?");
        $last->bindParam(1, $contract_id);
        $last->execute();
        if ($last->rowCount() < 1) {
          $sql = $db->prepare(" UPDATE aksat_contract set status = 3 where contract_id = ?");
          $sql->bindParam(1, $contract_id);
          $sql->execute();
          $maxsql = $db->prepare("SELECT max(tash_id) as maxd FROM tash_in");
          $maxsql->execute();
          if ($maxsql->rowCount() > 0) {
            $row = $maxsql->fetch(PDO::FETCH_ASSOC);
            $maxD = $row['maxd'] + 1;
          } else {
            $maxD = 1;
          }
          $ww = $db->prepare("SELECT tash FROM aksat_contract where contract_id = ?");
          $ww->bindParam(1, $contract_id);
          $ww->execute();
          if ($ww->rowCount() > 0) {
            $w = $ww->fetch(PDO::FETCH_ASSOC);
            $wanted = $w['tash'];
          }
          $start = date('Y-m-d', strtotime($start . ' + 3 month'));
          $endd = date('Y-m-d', strtotime($start . ' - 1 days'));
          $endd  = date('Y-m-d', strtotime($endd . ' + 1 month'));
          $new_tash = $db->prepare("INSERT INTO tash_in(tash_id, contract_id, wanted, start, endd)
                               values(?,?,?,?,?)");
          $new_tash->bindParam(1, $maxD);
          $new_tash->bindParam(2, $contract_id);
          $new_tash->bindParam(3, $wanted);
          $new_tash->bindParam(4, $start);
          $new_tash->bindParam(5, $endd);
          $new_tash->execute();
        }
        echo  " تم ترحيل سندات القبض الي الاقساط بنجاح. ";
      } else {
        echo "يوجد خطأ في تسجيل البيانات ... راجع  من فضلك ";
      }
    }
  }
}
// tamm update
if (isset($_POST['tamm'])) {
  include "../actions/dbPDO.php";
  $contract_id  = $_POST["contract_id"];
  $tamm         = $_POST["tamm"] - 1;
  if ($tamm > 1) {
    $tamm_expire = date('Y-m-d', strtotime(' + ' . $tamm . ' days'));
  } else {
    exit();
  }
  $sql = $db->prepare(" UPDATE aksat_contract set tamm_expire = ?  where contract_id = ?");
  $sql->bindParam(1, $tamm_expire);
  $sql->bindParam(2, $contract_id);
  $sql->execute();
}

if (isset($_POST["used_area"])) {
  $contract_id    = $_POST['contract_id'];
  $used_area      = $_POST['used_area'];
  $rent_days      = $_POST['rent_days'];
  $Number = '/^[0-9]+(\.[0-9]{1,2})?$/';
  $data = array();
  $error = array();
  if (empty($used_area) || empty($rent_days)) {
    $error["used_area"] = "من فضلك سجل منطقة الإستخدام و مدة العقد ليتم الحفظ  ";
  }
  if (!empty($rent_days)) {
    $rent_days = htmlspecialchars(strip_tags($rent_days));
  }else{$rent_days = 'شهر';}
  if (!empty($used_area)) {
    $used_area = htmlspecialchars(strip_tags($used_area));
  }else{$used_area = null;}
  if (!empty($error)) {
    $data["error"] = $error;
  } else {
    $contt = $db->prepare(" UPDATE aksat_contract SET used_area = ? , rent_days = ?  WHERE contract_id = ? ");
    $contt->bindParam(1, $used_area);
    $contt->bindParam(2, $rent_days);
    $contt->bindParam(3, $contract_id);
    if ($contt->execute()) {
      $data["msg"] = "<div class='alert alert-success'>
                              <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                              <b>تم تحديث منطقة الإستخدام و مدة العقد...</b>
                              </div>";
    } else {
      $data["msg"] = "<div class='alert alert-danger'>
                              <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                              <b>يوجد خطأ في تسجيل البيانات ... راجع  من فضلك</b>
                              </div> ";
    }
  }
  echo json_encode($data);
}
if (isset($_POST["cust_id2"])) {
  $contract_id   = $_POST['contract_id'];
  $cust_id2      = $_POST['cust_id2'];

  $contt = $db->prepare(" UPDATE aksat_contract SET cust_id2 =?  WHERE contract_id = ? ");
  $contt->bindParam(1, $cust_id2);
  $contt->bindParam(2, $contract_id);
  if ($contt->execute()) {
    $data["msg"] = "<div class='alert alert-success'>
                              <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                              <b>تمت إضافة المستأجر الثاني بنجاح</b>
                              </div>";
    $data["contract_id"] = $contract_id;
  } else {
    $data["msg"] = "<div class='alert alert-danger'>
                              <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                              <b>يوجد خطأ في تسجيل البيانات ... راجع  من فضلك</b>
                              </div> ";
  }
  echo json_encode($data);
}
// close aksat contract and set car in new woner
if (isset($_POST['carid'])) {
  include_once("../actions/dbPDO.php");
  $contract_id = $_POST["contt"];
  $carid       = $_POST["carid"];
  $date_sale = date("Y-m-d");
  $msg       = "<div class='alert alert-success'>
                            <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>";
  $sql = $db->prepare(" UPDATE aksat_contract set status = 2 ,end =? where contract_id = ?");
  $sql->bindParam(1, $date_sale);
  $sql->bindParam(2, $contract_id);
  if ($sql->execute()) {
    $msg .= "<b>تم غلق العقد بنجاح ..</b>";
  }
  $sql = $db->prepare(" UPDATE cars set carstatus = 1 , car_job_id = 6 , branch = 1 , date_sale = ? where carid = ?");
  $sql->bindParam(1, $date_sale);
  $sql->bindParam(2, $carid);
  if ($sql->execute()) {
    $msg .= "<b> تم نقل ملكية السيارة..</b>";
  }
  $msg .= "</div>";
  echo $msg;
}
if (isset($_POST['retrun_id'])) {
  include_once("../actions/dbPDO.php");
  $contract_id  = $_POST["contt"];
  $carid       = $_POST["retrun_id"];
  $date_sale = date("Y-m-d");
  $msg       = "<div class='alert alert-success'>
                      <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>";
  $sql = $db->prepare(" UPDATE aksat_contract set status = 2 ,end =? where contract_id = ?");
  $sql->bindParam(1, $date_sale);
  $sql->bindParam(2, $contract_id);
  if ($sql->execute()) {
    $msg .= "<b>تم غلق العقد بنجاح ..</b>";
  }
  $sql = $db->prepare(" UPDATE cars set carstatus = 1 , car_job_id = 2 , branch = 0  where carid = ?");
  $sql->bindParam(1, $carid);
  if ($sql->execute()) {
    $msg .= "<b> تم إعادة السيارة إستعداد للتمليك..</b>";
  }
  $msg .= "</div>";
  echo $msg;
}
if (isset($_POST['newStart'])) {
  include_once("../actions/dbPDO.php");
  $contract_id  = $_POST["contract_id"];
  $newStart     = $_POST['newStart'] ;

  $kest = $db->prepare("SELECT * FROM `aksat_in` WHERE `contract_id` = ? 
                    AND `payed` IS NULL ORDER BY ak_id");
  $kest->bindParam(1,$contract_id);
  $kest->execute();
  if($kest->rowCount()>0){
    while($row = $kest->fetch())
       {   
       
        $endd   = date('Y-m-d', strtotime($newStart. ' + 1  month'));
        $endd   = date('Y-m-d', strtotime($endd. ' -1 days'));

         $ak_id = $row['ak_id'];
        $contt = $db->prepare(" UPDATE aksat_in SET start =? ,endd = ? WHERE ak_id = ? ");
        $contt->bindParam(1, $newStart);
        $contt->bindParam(2, $endd);
        $contt->bindParam(3, $ak_id);
        $contt->execute();

       $newStart = date('Y-m-d', strtotime($newStart. ' + 1  month'));
 
}
echo("تمت التحديث بنجاح");
}}
