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

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

// ob_start();
require_once "../op/close_up.php";
require_once('../op/contractHistory.php');



$sanad_date = date("Y-m-d");

if (isset($_POST["carid"])) {
  if ($_POST['contract_id'] != "") {
    $contract_id   = $_POST['contract_id'];
    $day_cost      = $_POST['day_cost'];
    $km_in         = $_POST['km_in'];
    $kilo_cost     = $_POST['kilo_cost'];
    $open_kilo     = $_POST['open_kilo'];
    $addtion_cost  = $_POST['addtion_cost'];
    $addtion_desc  = $_POST['addtion_desc'];
    $violations    = $_POST['violations'];
    $deduction     = $_POST['deduction'];
    $free_dd       = $_POST['free_dd'];
    $comm          = $_POST["comm"];
    $carid         = $_POST["carid"];
    $cont_status   = $_POST["cont_status"];

    $contHistory = new  ContHistory($conn, $contract_id, $father);
    $last = $conn->prepare("SELECT  cars.km3 ,contracts.date_in from cars , contracts
                        where contracts.carid = cars.carid
                        AND contracts.contract_id = ? ");
    $last->bindParam(1, $contract_id);
    $last->execute();
    if ($last->rowCount() > 0) {
      $free = $last->fetch(PDO::FETCH_ASSOC);
      $km3       = $free["km3"];
      $freekm   = $free["freekilo"];
      $date_in  = $free["date_in"];
    }
    if ($date_in > 1) {
      $error["msg"] = "تم غلق العقد غير مسموح لك بالتعديل";
    }
    $dc     = '/^[0-9]+(\.[0-9]{1,2})?$/';
    $Number = "/^[0-9]+$/";

    $data  = array();
    $error = array();


    if ($open_kilo > 0) {
      $kilo_cost = 0;
    } else {
      if (empty($kilo_cost)) {
        $error["kilo_cost"] = "من فضلك سجل سعر الكيلو بالهللة";
      }
      if (!preg_match($Number, $kilo_cost)) {
        $error["kilo_cost"] = "أرقام فقط";
      }
      if ($km3 > $kilo_cost) {
        $kilo_cost = $km3;
      }
    }

    if (!empty($km_in)) {
      if (!preg_match($Number, $km_in)) {
        $error["km_in"] = "أرقام صحيحة فقط";
      }
    } else {
      $km_in = null;
    }
    if (!empty($addtion_cost)) {
      if (!preg_match($dc, $addtion_cost)) {
        $error["addtion_cost"] = "تأكد من الرقم";
      }
    } else {
      $addtion_cost = null;
    }
    if (!empty($violations)) {
      if (!preg_match($Number, $violations)) {
        $error["violations"] = "أرقام صحيحة فقط";
      }
    } else {
      $violations = null;
    }
    if (!empty($deduction)) {
      if (!preg_match($dc, $deduction)) {
        $error["deduction"] = "أرقام فقط";
      }
      if ($deduction > $free_dd) {
        $error["deduction"] = "لقد تخطيت الخصم المسموح بيه";
      }
    } else {
      $deduction = null;
    }
    if (!empty($addtion_desc)) {
      $addtion_desc = htmlspecialchars(strip_tags($addtion_desc));
    } else {
      $addtion_desc = null;
    }
    if (!empty($comm)) {
      $comm = htmlspecialchars(strip_tags($comm));
    } else {
      $comm = null;
    }
    if (!empty($error)) {
      $data["error"] = $error;
    } else {

      $contt = $conn->prepare(" UPDATE contracts SET km_in = ? , kilo_cost = ?  , addtion_cost = ? , addtion_desc = ?,
      violations = ? ,comm = ? ,deduction = ? WHERE contract_id = ? ");
      $contt->bindParam(1, $km_in);
      $contt->bindParam(2, $kilo_cost);
      $contt->bindParam(3, $addtion_cost);
      $contt->bindParam(4, $addtion_desc);
      $contt->bindParam(5, $violations);
      $contt->bindParam(6, $comm);
      $contt->bindParam(7, $deduction);
      $contt->bindParam(8, $contract_id);
      if ($contt->execute()) {
        if ($cont_status == 3) {
          auto_close($conn, $contract_id);
        }
        $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>";
        $check_new = $contHistory->checkHistory($day_cost, $kilo_cost, $addtion_cost, $violations, 0, $deduction);
        if ($check_new) {
          $contHistory->create($day_cost, $kilo_cost, $addtion_cost, $violations, 0, $deduction, $father);
        }
      } 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);
  }
}
//add second custmoers to the current contract
if (isset($_POST["cust_id2"])) {
  $contract_id   = $_POST['contract_id'];
  $cust_id2      = $_POST['cust_id2'];

  $contt = $conn->prepare(" UPDATE contracts 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);
}

if (isset($_POST["tamm_expire"])) {
  $contract_id      = $_POST['contract_id'];
  $tamm_expire      = $_POST['tamm_expire'];

  $contt = $conn->prepare(" UPDATE contracts SET tamm_expire =?  WHERE contract_id = ? ");
  $contt->bindParam(1, $tamm_expire);
  $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>";
  } 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["used_area"])) {
  $contract_id    = $_POST['contract_id'];
  $used_area      = $_POST['used_area'];
  $rent_days      = $_POST['rent_days'];
  $tamm           = $_POST['tamm'];

  $Number = "/^[0-9]+$/";

  $data = array();
  $error = array();

  if (empty($used_area) || empty($rent_days)) {
    $error["used_area"] = "من فضلك سجل منطقة الإستخدام و مدة العقد ليتم الحفظ  ";
  }
  if (!empty($used_area)) {
    $used_area = htmlspecialchars(strip_tags($used_area));
  }
  if (!empty($rent_days)) {
    $rent_days = htmlspecialchars(strip_tags($rent_days));
  }
  if (!empty($tamm)) {
    $tamm = htmlspecialchars(strip_tags($tamm));
  }
  if (!empty($error)) {
    $data["error"] = $error;
  } else {
    $contt = $conn->prepare(" UPDATE contracts SET used_area = ? , rent_days = ? ,tamm = ? WHERE contract_id = ? ");
    $contt->bindParam(1, $used_area);
    $contt->bindParam(2, $rent_days);
    $contt->bindParam(3, $tamm);
    $contt->bindParam(4, $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);
}
