<?php 

require_once("../config.php");
require_once("../lib/functions.php");

$strDescription = htmlentities(trim($_POST['description']));
$strDescription = addslashes($strDescription);
$numDefect    = (isset($_POST['defect'])) ? $_POST['defect'] : 0;
$id           = (int) $_POST['loc_id'];
$filename     = "";
$allowed_extensions = array("jpg", "jpeg", "png", "gif");

$boolUploadOk=false;
if ($boolUpload && ($_FILES['uploadfile']['size']>0)) {
    $file=$_FILES['uploadfile'];
    $fileinfo = @getimagesize($file["tmp_name"]);
    if (!empty($fileinfo)) {
        //$info=read_gps_location($_FILES["uploadfile"]["tmp_name"]);
        $file_extension = pathinfo($file["name"], PATHINFO_EXTENSION);
        if (!in_array(strtolower($file_extension), $allowed_extensions)) {
            echo "Invalid file type. Please upload only jpg, jpeg, png, or gif images.";
                exit();
        }
        $strNewfilename = uniqid("", true) . "." . $file_extension;
        while (file_exists($uploaddir . $strNewfilename)) {
            $strNewfilename = uniqid("", true) . "." . $file_extension;
        }        
        if (move_uploaded_file($file['tmp_name'], $uploaddir.$strNewfilename)) {
            $filename=$strNewfilename;//$file['name'];
            $filesize=$file['size'];
            $filetype=$file['type'];   
            $boolUploadOk = true;
        } else {
            die("Upload failed with error code " . $_FILES['file']['error']);
        }
    }
}

$stmt = $db->prepare("UPDATE location SET description= :description, defect = :defect WHERE id= :id");
             
$stmt->bindValue(':description', $strDescription);
$stmt->bindValue(':defect', $numDefect);
$stmt->bindValue(':id', $id);
$r=$stmt->execute();


// Store File Upload
if ($boolUploadOk) {
    $strSQL="INSERT INTO files (loc_id,filename,filesize,filetype) VALUES (:loc_id,:filename,:filesize,:filetype)";
    $stmt = $db->prepare($strSQL);
    $stmt->bindValue(':loc_id',$id);
    $stmt->bindValue(':filename',$filename);
    $stmt->bindValue(':filesize',$filesize);
    $stmt->bindValue(':filetype',$filetype);
    $stmt->execute();
}

$result = array(
    "id" => $id,
    "description" => stripslashes(nl2br($strDescription)),
    "defect" => $arrDefect[$numDefect],
    "filename" => $filename,
);

echo json_encode($result);
             