<?php
if(!isset($_SESSION)) {  session_start(); }
 ob_start();
if(!isset($_SESSION["user_id"])){header("location:../logout.php");}
 $father = $_SESSION["user_id"];
include "../actions/dbPDO.php";

$mat_in_id      = $_POST['invoice_id'];
$item_search    = $_POST['item_search'];
$tot_price      = $_POST['tot_price'];
$qty            = $_POST['qty'];
$unit           = $_POST['unit'];
$location       = $_POST['location'];
$comm           = $_POST['comm'];

  $Number = '/^[0-9]+(\.[0-9]{1,2})?$/' ;
  $error = array();
  $data = '';
$del =$db->prepare("DELETE from items_line where mat_in_id = ?");
$del->bindParam(1,$mat_in_id);
$del->execute();

    $maxsql2= $db->prepare("SELECT max(line_id) as maxd , max(audate) as time1 FROM items_line");
    $maxsql2->execute();
if($maxsql2->rowCount()>0){$row = $maxsql2->fetch(PDO::FETCH_ASSOC);
    $maxDD = $row['maxd']+1;
    $start = $row['time1'] ;
     } else {$maxDD = 1 ; }
  if(!empty($maxDD)){
      $start = strtotime($start);
      $date_today = date("Y-m-d H:i:s");
      $end = strtotime($date_today);
  // $end = $end + 3600 ;
  $mano =   $end -$start  ;
      if($mano < 5){
              exit();
        }}
if(!empty($tot_price)){
      $sum_price = array_sum($tot_price);
    }else{$sum_price = 0;}

  $vat= $db->prepare("SELECT net_cost FROM material_in where mat_in_id = ?");
  $vat->bindParam(1,$mat_in_id);
  $vat->execute();
if($vat->rowCount()>0){$medo = $vat->fetch(PDO::FETCH_ASSOC);
  $net_cost = $medo['net_cost'];}
  $cashPP = $net_cost / $sum_price ;

for($count = 0; $count < count($_POST["item_search"]); $count++)
    {
      if(empty($tot_price[$count])){     return ;      }
     if(empty($item_search[$count])){
       return ;
     }else{
      $searchWords = htmlspecialchars(strip_tags($item_search[$count])) ;
     }
  
  if(!empty($unit[$count])){ $unit[$count] = htmlspecialchars(strip_tags($unit[$count])) ;}else{ $unit[$count] = 'حبة';}
  if(!empty($location[$count])){ $location[$count] = htmlspecialchars(strip_tags($location[$count])) ;}else{$location[$count] = null;}
  if(!empty($comm[$count])){ $comm[$count] = htmlspecialchars(strip_tags($comm[$count])) ;}else{$comm[$count] = null;}

  if(empty($error)){
    $item_id = "";
    // $searchWords = $item_search[$count];

    // if(!empty($String)){ $String = htmlspecialchars(strip_tags($String)) ;   }
        $itemSql =$db->prepare("SELECT item_id FROM items WHERE item_name = ? LIMIT 1");
        $itemSql->bindParam(1,$searchWords);
    $itemSql->execute();
      if($itemSql->rowCount()>0){
          $row = $itemSql->fetch(PDO::FETCH_ASSOC);
          $item_id = $row["item_id"];

        }
        else
         { 
            $maxsql= $db->prepare("SELECT max(item_id) as maxd FROM items");
            $maxsql->execute();
          if($maxsql->rowCount()>0){
            $row = $maxsql->fetch(PDO::FETCH_ASSOC);
            $maxD = $row['maxd']+1;} 
          else {$maxD = 1 ;   }

        $kind = 'جميع السيارات' ;
        $sql = $db->prepare(" INSERT INTO items
        (item_id , item_name , kind,father)
         VALUES (?, ? , ? , ?)");
         $sql->bindParam(1,$maxD);
         $sql->bindParam(2,$searchWords);
         $sql->bindParam(3,$kind);
         $sql->bindParam(4,$father);
         if($sql->execute())
            { $item_id = $maxD;}
      }
    // existing mat_name in your database
$sql =$db->prepare("SELECT line_id , item_id , tot_price FROM items_line
     WHERE   item_id = ? AND mat_in_id = ?  LIMIT 1");
$sql->bindParam(1,$item_id);
$sql->bindParam(2,$mat_in_id);
$sql->execute();
  if($sql->rowCount()>0){$row = $sql->fetch(PDO::FETCH_ASSOC);
      $line_id          = $row["line_id"];
      $tot_price        = $row["tot_price"];
  echo "
      <div class='alert alert-danger'>
      <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
      <b>تم تسجيل بيانات $item_search[$count]  من قبل كود رقم $line_id بسعر  $tot_price[$count] في نفس الفاتورة</b>
      </div>
      ";
  exit();
}else {
      $new_price  = round(($tot_price[$count] * $cashPP),2);
      $unit_price = round(($new_price / $qty[$count]),2);
  $sql = $db->prepare(" INSERT INTO items_line
  (line_id , mat_in_id, item_id , tot_price, qty, unit , unit_price ,location , comm)
   VALUES (?, ?, ?, ?, ?, ? , ?, ?,?)");
   $sql->bindParam(1,$maxDD);
   $sql->bindParam(2,$mat_in_id);
   $sql->bindParam(3,$item_id);
   $sql->bindParam(4,$new_price);
   $sql->bindParam(5,$qty[$count]);
   $sql->bindParam(6,$unit[$count]);
   $sql->bindParam(7,$unit_price);
   $sql->bindParam(8,$location[$count]);
   $sql->bindParam(9,$comm[$count]);
 if($sql->execute()){
   $data = "<div class='alert alert-success'>
   <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
     <b>تم تسجيل الفاتورة بنجاح</b>
   </div>
   ";}
  else{ echo "<div class='alert alert-danger'>
  <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
    <b>يوجد خطأ في تسجيل البيانات ... راجع  من فضلك</b>
  </div>
  ";}
}}
$maxDD = $maxDD + 1 ;
echo $data;
}
?>
