<?php 
  require_once ("../var/res.php");
  ##### ADD BOQ  ####

  $boqttle = $_REQUEST['boqttle'];
  $elem = $_REQUEST['elem'];
  $ctgid = $_REQUEST['ctgid'];
  $item_id = $_REQUEST['item_id'];
  $qty = $_REQUEST['qty'];
  $boqreqst_id = $_REQUEST['boqreqst_id'];
  $con_idboq = $_REQUEST['con_idboq'];
  $boqcomp = $_REQUEST['boqcomp'];
  $boqdiv = $_REQUEST['boqdiv'];
  //$fmla_bar = $_REQUEST['fmla_bar'];

  $dt = date('Y-m-d');
  $dtrm = date('Y-m-d H:s:i');
  $sts = 4;
  
  $queCheck = $db->prepare('SELECT boqty AS lqty FROM tbl_boqs WHERE breq_id="'.$boqreqst_id.'" AND con_idboq="'.$con_idboq.'" 
  AND boqtitle="'.$boqttle.'" AND copnt_id="'.$boqcomp.'" AND div_id="'.$boqdiv.'" AND elmnt="'.$elem.'" AND bctg="'.$ctgid.'" AND itmid="'.$item_id.'" AND stsboq=4 ORDER BY boq_id DESC LIMIT 1');
  $queCheck->execute();
  if($queCheck->rowCount() >0){
  $upd = $conn->prepare('UPDATE tbl_boqs SET boqty="'.$qty.'" WHERE breq_id="'.$boqreqst_id.'" AND con_idboq="'.$con_idboq.'" 
  AND boqtitle="'.$boqttle.'" AND copnt_id="'.$boqcomp.'" AND div_id="'.$boqdiv.'" AND elmnt="'.$elem.'" AND bctg="'.$ctgid.'" AND itmid="'.$item_id.'" AND stsboq=4 ORDER BY boq_id DESC LIMIT 1');
  $upd->execute();
  $msg="Changes Saved Successfully";
  }else{
  
  ######## UNIT PRICE ########
  
  ####### ITEM PRICE #######
  $getPrix = $db->prepare("SELECT * FROM tbl_boqcon b
  INNER JOIN tbl_items i ON i.item_id=b.matid 
  WHERE itmid ='". $item_id."' AND sttscon=4 ORDER BY boqcon_id ASC");                
  $getPrix->execute(array());
  while ($rrprix = $getPrix->fetch(PDO::FETCH_ASSOC)){
      $iPrice = $rrprix['iPrice'];
      $qtyboq = $rrprix['qtyboq'];
      $totMont = $iPrice*$qtyboq;
      $unitprix= $unitprix+$totMont;
  }
  ######## END UNIT PRICE ########

  $stmt = $db->prepare("INSERT INTO tbl_boqs (breq_id,con_idboq,boqtitle, copnt_id, div_id, elmnt, bctg, itmid, boqty, unit_prix, stsboq,date_boq_created,trm_boq_created)
  VALUES (:breq_id,:con_idboq,:boqtitle, :copnt_id, :div_id, :elmnt, :bctg, :itmid, :boqty, :unit_prix, :stsboq, :date_boq_created, :trm_boq_created)");
  //if-else statement in executing our prepared statement
  $stmt->execute(array(':breq_id' => $boqreqst_id ,':con_idboq' => $con_idboq ,':boqtitle' => $boqttle ,':copnt_id' => $boqcomp, ':div_id' => $boqdiv,':elmnt' => $elem ,
   ':bctg' => $ctgid ,':itmid' => $item_id, ':boqty' => $qty, ':unit_prix' => $unitprix, ':stsboq' =>$sts, ':date_boq_created' =>$dt, ':trm_boq_created' =>$dtrm));
  $msg = 1;
 }

?>