<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../objects/installation.php';
include_once '../objects/installation_detail.php';

date_default_timezone_set('Asia/Rangoon'); 
session_start();

$database = new Database();
$db = $database->getConnection();
 
$installation = new Installation($db);
$installation_detail = new InstallationDetail($db);
$data = json_decode(file_get_contents("php://input"));
	
$installation->id = $data->id;
$installation->install_date = $data->install_date;
$installation->install_address = $data->install_address;
$installation->geolocation = $data->geolocation;
$installation->DN = $data->DN;
$installation->SN = $data->SN;
$installation->technician1 = $data->technician1;
$installation->technician2 = $data->technician2;
$installation->technician3 = $data->technician3;
$installation->remark = $data->remark;
$installation->entry_by = $_SESSION['user'];
$installation->entry_date_time = date("Y-m-d H:i:s");	
$installation_detail->installation_id = $data->id;
$installation_detail->delete();

	if($installation->update()){

		foreach($data->item_details as $p_detail){
	
			$installation_detail->item_code = $p_detail->item_code;
			$installation_detail->item_name = $p_detail->item_name;
			$installation_detail->quantity = $p_detail->quantity;
			$installation_detail->unit = $p_detail->unit;
			$installation_detail->entry_by = $_SESSION['user'];
			$installation_detail->entry_date_time = date("Y-m-d H:i:s");	
		
			if(!$installation_detail->create()){
				$msg_arr = array(
					"message" => "error",
					"table" => "installation_detail"
				);
				echo json_encode($msg_arr);
				die();
			}
		}

		$arr = array(
			"message" => "created",
			"last_id" => $installation->id
		);
	}else{
		$arr = array(
			"message" => "error"
		);
	}

echo json_encode($arr);
?>
