<?php

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_config.php';
require_once __DIR__ . '/image_upload.php';


if (isset($_POST['JSON'])) {
    
    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysql_error());
    $img=new ImageUpload();

    $json=json_decode($_POST['JSON'],true);
    $email=$json['email'];
    $ticket=$json['ticket'];
    $companyname=$json["company"];
    $lat=$json['lat'];
    $lon=$json['lon'];
    $location=$json['location'];
    $facility=$json['facility'];
    $spares=$json['spares'];
    $workstatus=$json['workstatus'];
    $workreportdetails=$json['things'];
    $working_hours=$json['hours'];
    $servicecharge=$json['servicecharge'];
    $sparesamount=$json['sparescharge'];
    $amountreceived=$servicecharge+$sparesamount;
    $nameofsignature=$json['signaturer'];
    $datetime=date('Y-m-d H:i:s');
    date_default_timezone_set('Asia/Calcutta');
    $dt=date('YmdHis');
    $fileNmae=$companyname."_".$ticket."_".date('Ymd');
    
    if(!empty($json["bill"])){
        $billimage=$img->uploadImage("Bill_$fileNmae",$json["bill"]);
    }else{
        $billimage="";
    }
    if(!empty($json["sign"])){
    $customersignature=$img->uploadImage("Sign_$fileNmae",$json["sign"]);
    }
    if(!empty($json["status"])){
        $image=$img->uploadImage("Img_$fileNmae",$json["status"]);
    }
    
    $query="SELECT combinationname,combinationtype,customername FROM tickets WHERE ticketnumber='$ticket' AND companyname='$companyname'";
    $result = mysqli_query($con,$query);
    if(!empty($result) && mysqli_num_rows($result) > 0){
        while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
            $combinationname=$row["combinationname"];
            $combinationtype=$row["combinationtype"];
            $customername=$json['customername'];
        }
    }

  
    $sparesArray=array();
    if(count($spares)!=0){
        foreach($spares as $obj){
            $name=$obj['name'];
            $amount=$obj['amount'];
            $unit=$obj['unit'];
            $total=$obj['total'];
            $insertvalues="('$companyname','$combinationname','$combinationtype','$ticket','$name','$amount','$unit','$total','$datetime')";
            array_push($sparesArray,$insertvalues);
        }
         
         $spareInsertQuery="INSERT INTO spareparts(companyname,combinationname,combinationtype,ticketnumber,item_name,amount,quantity,totalamount,dateandtime)
        VALUES".implode(",",$sparesArray);
        mysqli_query($con,$spareInsertQuery);
    }
    
     $reportInsertQuery="INSERT INTO workreport(companyname,ticketnumber,latitude,longitude,workdonelocation,customer_name,workstatus,workreportdetails,working_hours,servicecharge,sparesamount,amountreceived,workdoneby,imagepath,billimagepath,signaturepath,nameofsignature,dateandtime) VALUES ('$companyname','$ticket','$lat','$lon','$location','$customername','$workstatus','$workreportdetails','$working_hours','$servicecharge','$sparesamount','$amountreceived','$email','$image','$billimage','$customersignature','$nameofsignature','$datetime')";
    
   
        
    if (mysqli_query($con,$reportInsertQuery)) {
        
        if($workstatus=="complete"){
            $dt="completed_datetime";
            $by="completed_by";
            $type="completed_type";
        }else{
            $dt="incompleted_datetime";
            $by="incompleted_by";
            $type="incompleted_type";
        }
        
         $query="UPDATE tickets SET ticketstatus='$workstatus',$type='employee',$dt='$datetime',$by='$email' WHERE ticketnumber='$ticket' AND companyname='$companyname' AND Assignedto='$email'";
         if(mysqli_query($con,$query)){
                $response["s"] = 1;
         }else{
                $response["s"] = 0;
         }
    } else {
        $response["s"] = 2;
    }
    
    
    mysqli_close($con);
    
 
}
     // echoing JSON response
    echo json_encode($response);

?>