<?php
require_once('Conn.php');
header('Content-Type: application/json');

if($_SERVER['REQUEST_METHOD'] != 'POST') {
    header('HTTPS/1.1 405');
    echo json_encode(array(["message" => "method not allowed" , "status" => "false"]));
    exit;
}

if(!isset($_POST['uid'])  ||   !isset($_POST['b_list'])  || !isset($_POST['details']) || !isset($_POST['c_list']) ||  !isset($_POST['priority']) ||  !isset($_POST['subdivision'])  ) {
    echo json_encode(array(["message" => "internal body error" , "status" => "false"]));
    exit;
}

date_default_timezone_set("Asia/Kolkata"); 
$date = date("d/m/Y");
$d = date("dmy"); 
$time = date("g:i a");

$uid = $_POST['uid'];
$b_list = $_POST['b_list'];
$details = $_POST['details'];
$c_list = $_POST['c_list'];
$priority = $_POST['priority'];
$subdivision = $_POST['subdivision'];

//$query = "INSERT INTO users_complaint(date , b_list  , uid , details , c_list , time , priority , subdivision ) VALUES ('$date' , $b_list , $uid , '$details' , $c_list , '$time' , $priority , $subdivision    )";
$newQ = "INSERT INTO users_complaint(date , b_list  , uid , details , c_list , time , priority , subdivision , docketNumber ) SELECT '$date' , $b_list , $uid , '$details' , $c_list , '$time' , $priority , $subdivision , concat('$d' , if(count(u.ucid)+1 > 9 , '' , '0') , count(u.ucid)+1 ) FROM users_complaint u WHERE u.date = '$date' ";
$result = mysqli_query($connection , $newQ);

$str = "";
if($result) {
    $ucid = mysqli_insert_id($connection);

    if($_FILES['file'] == null){
        $count = 0;
    }
    else{
        $count = count($_FILES['file']['name']);
    }
   

   if($count > 0 && isset($_FILES['file']) ) {
   
    $upload_path = "Images/";
    for($i = 0 ; $i < $count ; $i++) {
        $tempPath = $_FILES['file']['tmp_name'][$i];
        $fileName = $_FILES['file']['name'][$i];

        if(move_uploaded_file($tempPath , $upload_path.$fileName)) {
            if($i == $count-1){
                $str .= "(". "'" .$fileName . "'" . "," . "$uid" . "," . "$ucid" . ")";
            }
            else{
                $str .= "(". "'" .$fileName . "'" . "," . "$uid" . "," . "$ucid" . ") , ";
            }
          
        }  
    }
    $q = "INSERT INTO users_complaint_images(img , uid , ucid) VALUES $str ";
    $r = mysqli_query($connection , $q);
    if($r){
        echo json_encode(array(["message" => "Submit" , "status" => "true"]));
    }
    else{
        echo $q;
        echo json_encode(array(["message" => mysqli_error($connection) , "status" => "false"]));
    }

}
else{
    echo json_encode(array(["message" => "Submit Complaint with no Images" , "status" => "true"]));
}


}
else{
    echo json_encode(array(["message" => mysqli_error($connection) , "status" => "false"])); 
}






?>