<?php

require_once __DIR__ . '/db_config.php';
require_once __DIR__ . '/notify.php';

$r = array();

if (isset($_POST["cname"]) ) {

$cname=$_POST["cname"];
$facility_id=$_POST["facility_id"];
$eamount=$_POST["eamount"];
$empemail=$_POST["empemail"];
$status = "open";
$defect = addslashes($_POST["defect"]);
$defective_equipment = $_POST["de"];
$kitchen_number=$_POST["kitchen"];
date_default_timezone_set("Asia/Calcutta");   //India time (GMT+5:30)
$datetime=date('Y-m-d H:i:s');
$report_id="";

$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysql_error());

$idQuery="SELECT generateDefectId('$cname') AS id";
$idResult=mysqli_query($con,$idQuery);
if(!empty($idResult) && mysqli_num_rows($idResult) > 0){
    $row = mysqli_fetch_array($idResult,MYSQLI_ASSOC);
    $report_id=$row["id"];
}



$query = "INSERT INTO defect_report(report_id,datetime,companyname,facility_id,estimated_amount,approved_amount,emp_emailid,status,defect,open_status_DT,open_user_id,defective_equipment,kitchen_number) 
VALUES('$report_id','$datetime','$cname','$facility_id','$eamount','$eamount','$empemail','$status','$defect','$datetime','$empemail','$defective_equipment','$kitchen_number')";

$result=mysqli_query($con,$query);

if($result){ 
    $r["s"]=1;
    $r["id"]=$report_id;
    
    $noity=new notify();
    $query= "SELECT mep_id FROM mep_facility where companyname='$cname' AND facility_id='$facility_id' AND delete_status=0";
    $result=mysqli_query($con,$query);
    if(!empty($result) && mysqli_num_rows($result) > 0){
        $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
        $message="New Defect Raised";
        $noity->send($con,$row["mep_id"],$report_id,$message);
    }
}
else{ $r["s"]=2; 
    
}

mysqli_close($con);


}

echo json_encode($r,JSON_UNESCAPED_SLASHES);


?>