<?php

include getenv("DOCUMENT_ROOT")."/include/session_include.php";
require_once getenv("DOCUMENT_ROOT")."/assets/conf.inc.php";
require_once getenv("DOCUMENT_ROOT")."/assets/dbCon.php";
require_once getenv("DOCUMENT_ROOT")."/assets/api/daily.php";

try {

    if ($mode == "update" && $d_uid == "") {
        echo 0;
        exit();
    }

    $d_visitdate = str_replace("-", "", trim($d_visitdate));

    $dailyApi = new DailyService();

    // payload만 구성
    $payload = [
        'd_orderdate'   => $d_visitdate,
		'd_accountno'   => $_POST['d_customerno'],
        'd_quantity'    => $d_quantity,
        'd_sludge'      => $d_sludge,
        'd_paystatus'   => $d_paystatus,
        'd_payamount'   => $d_payamount,
        'd_visit'       => 'Y',
        'd_visitdate'   => $d_visitdate . "000000",
        'd_status'      => 'F',
        'd_druid'       => $d_druid,
        'd_payeename'   => $d_payeename,
        'd_note'        => str_replace("\\", "", trim($d_note)),
        'd_inputdate'   => date("YmdHis"),
		'd_jobtype'     => $d_jobtype ?? 'UCO',
    ];

    // 기존 record 기준 update
    $opt = [
		'match_uid' => $d_uid,
    	'allow_update' => true
	];

    $dailyApi->saveDaily($payload, $opt);

    // signature만 별도 처리
    if ($signednew == 1 || ($d_payeesign == "" && $_POST['signed'] != "")) {

        $folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$d_customeruid;
        if (!is_dir($folderPath)) mkdir($folderPath, 0755, true);

        $image_parts = explode(";base64,", $_POST['signed']); 
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];

        $image_base64 = base64_decode($image_parts[1]);
        $uniquevalue = uniqid();

        $filename = substr($d_visitdate,0,8). "_". $uniquevalue . '.'.$image_type;
        $file = $folderPath ."/". $filename;

        file_put_contents($file, $image_base64);

        $dailyApi->saveDaily([
			'd_orderdate' => $d_visitdate,
			'd_accountno' => $_POST['d_customerno'],
			'd_jobtype'   => 'UCO',
			'd_payeesign' => $filename
		], [
			'match_uid' => $d_uid,
			'allow_update' => true
		]);
    }

    echo 1;

} catch (Exception $e) {

    error_log("================================");
    error_log("[order_lib_process ERROR]");
    error_log($e->getMessage());
    error_log($e->getTraceAsString());
    error_log("================================");

    echo 0;
}