<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/config.php');

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "taken") 
    $timeTaken = $paramValue;  
  else if ($paramName == "selectid") 
    $os_id = $paramValue;  
}

$dal = new DAL();

$ph_id = hexdec(uniqid());

$sql = "INSERT INTO photo (id, time_taken) VALUES ($ph_id, '$timeTaken') ";
$result = $dal->query($sql);       

$sql = "SELECT refno " .
       "FROM operationspatialunit OS, projectworkdayoperation PWO, " .
       "projectworkday PW, parcel PA, project PR " .
       "WHERE OS.id = $os_id AND PWO.operation_id = OS.operation_id " . 
       "AND PW.id = PWO.projectworkday_id AND PA.id = PW.parcel_id " .
       "AND PR.id = PA.project_id LIMIT 1 ";
$refno = $dal->query($sql)->refno;       

$path = PHOTO_PATH . $refno ;
$fileName = $refno . "_" . str_pad($ph_id, 8, '0', STR_PAD_LEFT);
$filePath = $path . "/" . $fileName;

$sql = "UPDATE photo SET filename='$filePath' WHERE id = $ph_id ";
$result = $dal->query($sql);       

$osp_id = hexdec(uniqid());

$sql = "INSERT INTO operationspatialunitphoto (id, photo_id, operationspatialunit_id) " .
         "VALUES ($osp_id, $ph_id, $os_id) "; 
$result = $dal->query($sql);
    
echo json_encode(array($ph_id, $fileName, $refno, $path, $timeTaken));

?>

