<?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';

session_start();
$database = new Database();
$db = $database->getConnection();
 
$installation = new Installation($db);

$data = json_decode(file_get_contents("php://input"));


$installation->city = $data->city;
$installation->df = $data->df;
$installation->dt = $data->dt;
$installation->id_no = $data->id_no;
$installation->install_type = $data->install_type;
$installation->dnsn = $data->dnsn;

$installation->updateInDe();

$arr = array();
$arr["records"] = array();

$stmt1 = $installation->getItemML();
$num1 = $stmt1->rowCount();

$iDetail = array();
while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)){
    extract($row1);
    $iDetail[$item_name] = 0;
}


$stmt = $installation->searchML();
$num = $stmt->rowCount();

$arr=array();
$arr["records"]=array();
if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        $detail = array();
        foreach ($row as $key => $value) {
                $detail[$key] = $value;
        }
        array_push($arr["records"], array_merge($detail, $iDetail));
    }
}

$stmt2 = $installation->getItemML();
$num2 = $stmt2->rowCount();

while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)){
    extract($row2);
        $chk_val = array_search($installation_id, array_column($arr["records"], 'id'));
        if(gettype($chk_val)=="integer"){
            $arr["records"][$chk_val][$item_name] = number_format($quantity); 
        }
}

echo json_encode($arr);
?>