<?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['payed'])) {
  $data = array();
  $tash_id   = $_POST["tash_id"];
  $payed     = $_POST["payed"];
  $printed_no = $_POST["printed_no"];
  $payMethod      = $_POST["payMethod"];
  $late = 0;
  $date_payed = date("Y-m-d");
  if (empty($father)) {
    exit();
  }
  if (empty($tash_id)) {
    exit();
  }
  $st = $db->prepare("SELECT start ,contract_id from tash_in where tash_id = ?");
  $st->bindParam(1, $tash_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 tash_in set payed = ? , date_payed = ? ,printed_no = ?,payMethod = ? ,late = ? ,father = ?  where tash_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, $father);
  $sql->bindParam(7, $tash_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>";
  } 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> ";
  }
}
