<?php
    include "../db/headerApi.php";
    include "../db/connection_main.php";

    $data = json_decode($_POST["MAIN"]);
    $details = json_decode($_POST["DETAILS"]);
    $userid = json_decode($_POST["USERID"]);
    $existing = json_decode($_POST["EXISTING"]);
    $newref = json_decode($_POST["NEWREF"]);
    $mstimport = json_decode($_POST["MSTIMPORT"], true);

    if (!$existing) {
        
        //Ref No
        if($newref) {
            $refno = $data->REF_NO_NEW;
        } else {
            $refno = $data->REF_NO;
        }

        //Check if REF and Brand already exist
        $sql = "SELECT COUNT(id) vexist
                  FROM ytycustom.xx_yty_incoming_outgoing_inspection_tbl
                 WHERE ref_no = :ref_no
                   AND brand = :brand
                   AND cust_order_no = :cust_ord
                   AND NVL(cancel_flag,'N') = 'N'";
        
        $sqlarr = oci_parse($dbcon , $sql);
        oci_bind_by_name($sqlarr, ':ref_no', $refno);
        oci_bind_by_name($sqlarr, ':brand', $data->BRAND->ID);
        oci_bind_by_name($sqlarr, ':cust_ord', $data->CUST_ORDER_NO);
        $r = oci_execute($sqlarr, OCI_NO_AUTO_COMMIT);

        if (!$r) {
            $e = oci_error($sqlarr);
            $errorMsg = json_encode($e['message']);
        }
        oci_fetch_all($sqlarr, $rows_check, null, null, OCI_FETCHSTATEMENT_BY_ROW);

        if ($rows_check[0]["VEXIST"] == "0") {
            
            //New Data
            $sql = "INSERT INTO YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_TBL 
                                (CUSTOMER, REF_NO, CUST_ORDER_NO, BRAND, DATE_RECEIVED, RECEIVED_BY, TOTAL_CTN, SAMPLE_DATA, APPLICATION_STATUS, REMARKS, SAMPLE_FLAG, CREATED_BY, CREATED_AT)
                        VALUES (:CUSTOMER, :REF_NO, :CUST_ORDER_NO, :BRAND, TO_DATE(:DATE_RECEIVED,'YYYY-MM-DD'), :RECEIVED_BY, :TOTAL_CTN, :SAMPLE_DATA, '1', :REMARKS, :SAMPLE_FLAG, :CREATED_BY, SYSDATE)
                        RETURNING ID INTO :NEWID";
            
            $sqlarr = oci_parse($dbcon , $sql);
            oci_bind_by_name($sqlarr, ':CUSTOMER', $data->CUSTOMER->ID);
            oci_bind_by_name($sqlarr, ':REF_NO', $refno);
            oci_bind_by_name($sqlarr, ':CUST_ORDER_NO', $data->CUST_ORDER_NO);
            oci_bind_by_name($sqlarr, ':BRAND', $data->BRAND->ID);
            oci_bind_by_name($sqlarr, ':DATE_RECEIVED', $data->DATE_RECEIVED);
            oci_bind_by_name($sqlarr, ':RECEIVED_BY', $data->RECEIVED_BY->ID);
            oci_bind_by_name($sqlarr, ':TOTAL_CTN', $data->TOTAL_CTN);
            oci_bind_by_name($sqlarr, ':SAMPLE_DATA', $data->SAMPLE_DATA);
            oci_bind_by_name($sqlarr, ':REMARKS', $data->REMARKS);
            oci_bind_by_name($sqlarr, ':SAMPLE_FLAG', $data->SAMPLE_FLAG);
            oci_bind_by_name($sqlarr, ':CREATED_BY', $userid);
            oci_bind_by_name($sqlarr, ':NEWID', $newid, 20);
            $r = oci_execute($sqlarr, OCI_NO_AUTO_COMMIT);

            if (!$r) {
                $e = oci_error($sqlarr);
                $errorMsg = json_encode($e['message']);
                goto finalStep;
            }

            if (!empty($newid) && empty($errorMsg) && !empty($details)) {
                foreach ($details->details as $det) {
                    $sql_det = "INSERT INTO YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_DETAIL_TBL 
                                            (INSPECTION_ID, PALLET_NO, QUANTITY_OF_CARTONS, QUANTITY_PCS, SIZE_CODE, LOT_NO, REMARKS_RECV)
                                    VALUES (:INSPECTION_ID, :PALLET_NO, :QUANTITY_OF_CARTONS, :QUANTITY_PCS, :SIZE_CODE, :LOT_NO, :REMARKS_RECV)";
                    $sqlarr_det = oci_parse($dbcon , $sql_det);
                    oci_bind_by_name($sqlarr_det, ':INSPECTION_ID', $newid);
                    oci_bind_by_name($sqlarr_det, ':PALLET_NO', $det->PALLET_NO);
                    oci_bind_by_name($sqlarr_det, ':QUANTITY_OF_CARTONS', $det->QUANTITY_OF_CARTONS);
                    oci_bind_by_name($sqlarr_det, ':QUANTITY_PCS', $det->QUANTITY_PCS);
                    oci_bind_by_name($sqlarr_det, ':SIZE_CODE', $det->SIZE_CODE->ID);
                    oci_bind_by_name($sqlarr_det, ':LOT_NO', $det->LOT_NO);
                    oci_bind_by_name($sqlarr_det, ':REMARKS_RECV', $det->REMARKS_RECV);
                    $r = oci_execute($sqlarr_det, OCI_NO_AUTO_COMMIT);

                    if (!$r) {
                        $e = oci_error($sqlarr_det);
                        $errorMsg = json_encode($e['message']);
                        goto finalStep;
                    }
                }
            }
        } else {
            $errorMsg = "This PWO / DO Number, Brand and Customer Order Ref. already exist in the system";
        }

    } else {

        //Ref No
        if($newref) {
            $refno = $data->REF_NO_NEW;
        } else {
            $refno = $data->REF_NO;
        }

        //Existing Data
        $newid = $data->ID;

        $sql = "UPDATE YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_TBL
                   SET DATE_RECEIVED = TO_DATE(:DATE_RECEIVED,'YYYY-MM-DD'),
                       REF_NO = :REF_NO,
                       CUST_ORDER_NO = :CUST_ORDER_NO,
                       TOTAL_CTN = :TOTAL_CTN,
                       SAMPLE_DATA = :SAMPLE_DATA,
                       REMARKS = :REMARKS,
                       MODIFIED_BY = :MODIFIED_BY,
                       MODIFIED_AT = SYSDATE
                 WHERE ID = :INSP_ID";
        
        $sqlarr = oci_parse($dbcon , $sql);
        oci_bind_by_name($sqlarr, ':DATE_RECEIVED', $data->DATE_RECEIVED);
        oci_bind_by_name($sqlarr, ':REF_NO', $refno);
        oci_bind_by_name($sqlarr, ':CUST_ORDER_NO', $data->CUST_ORDER_NO);
        oci_bind_by_name($sqlarr, ':TOTAL_CTN', $data->TOTAL_CTN);
        oci_bind_by_name($sqlarr, ':SAMPLE_DATA', $data->SAMPLE_DATA);
        oci_bind_by_name($sqlarr, ':REMARKS', $data->REMARKS);
        oci_bind_by_name($sqlarr, ':MODIFIED_BY', $userid);
        oci_bind_by_name($sqlarr, ':INSP_ID', $newid);
        $r = oci_execute($sqlarr, OCI_NO_AUTO_COMMIT);

        if (!$r) {
            $e = oci_error($sqlarr);
            $errorMsg = json_encode($e['message']);
            goto finalStep;
        }

        if (!empty($newid) && empty($errorMsg) && !empty($details)) {
            $sql = "DELETE FROM YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_DETAIL_TBL 
                     WHERE INSPECTION_ID = :INSP_ID
                       AND NVL(LOCK_REL,'0') = '0'";
                
            $sqlarr = oci_parse($dbcon , $sql);
            oci_bind_by_name($sqlarr, ':INSP_ID', $newid);
            $r = oci_execute($sqlarr, OCI_NO_AUTO_COMMIT);

            foreach ($details->details as $det) {
                if ($det->LOCK_REL != "1") {
                    $sql_det = "INSERT INTO YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_DETAIL_TBL 
                                            (INSPECTION_ID, PALLET_NO, QUANTITY_OF_CARTONS, QUANTITY_PCS, SIZE_CODE, LOT_NO, REMARKS_RECV)
                                    VALUES (:INSPECTION_ID, :PALLET_NO, :QUANTITY_OF_CARTONS, :QUANTITY_PCS, :SIZE_CODE, :LOT_NO, :REMARKS_RECV)";
                    $sqlarr_det = oci_parse($dbcon , $sql_det);
                    oci_bind_by_name($sqlarr_det, ':INSPECTION_ID', $newid);
                    oci_bind_by_name($sqlarr_det, ':PALLET_NO', $det->PALLET_NO);
                    oci_bind_by_name($sqlarr_det, ':QUANTITY_OF_CARTONS', $det->QUANTITY_OF_CARTONS);
                    oci_bind_by_name($sqlarr_det, ':QUANTITY_PCS', $det->QUANTITY_PCS);
                    oci_bind_by_name($sqlarr_det, ':SIZE_CODE', $det->SIZE_CODE->ID);
                    oci_bind_by_name($sqlarr_det, ':LOT_NO', $det->LOT_NO);
                    oci_bind_by_name($sqlarr_det, ':REMARKS_RECV', $det->REMARKS_RECV);
                    $r = oci_execute($sqlarr_det, OCI_NO_AUTO_COMMIT);

                    if (!$r) {
                        $e = oci_error($sqlarr_det);
                        $errorMsg = json_encode($e['message']);
                        goto finalStep;
                    }
                }
            }
        }    
    }

    //Attachment
    $file_i = 1;
    $file1 = null;
    $file2 = null;
    foreach ($_FILES['ATTACH']['tmp_name'] as $k => $v) {
        $path = $_FILES['ATTACH']['name'][$k];
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        $filename = $newid."_".$file_i.".".$ext;

        switch($file_i) {
            case 1: $targetPath1 = "../../webfiles/shopfloor/receiving/".$filename;

                    $uploadSuccess = false;
                    if (in_array($ext, ['jpg', 'jpeg', 'png'])) {
                        $uploadSuccess = compressAndSaveImage($_FILES['ATTACH']["tmp_name"][$k], $targetPath1, $ext);
                    } else {
                        $uploadSuccess = move_uploaded_file($_FILES['ATTACH']["tmp_name"][$k], $targetPath1);
                    }

                    if ($uploadSuccess) {
                        $file1 = $filename;
                    }
                    break;  

            case 2: $targetPath2 = "../../webfiles/shopfloor/receiving/".$filename;
                
                    $uploadSuccess = false;
                    if (in_array($ext, ['jpg', 'jpeg', 'png'])) {
                        $uploadSuccess = compressAndSaveImage($_FILES['ATTACH']["tmp_name"][$k], $targetPath2, $ext);
                    } else {
                        $uploadSuccess = move_uploaded_file($_FILES['ATTACH']["tmp_name"][$k], $targetPath2);
                    }

                    if ($uploadSuccess) {
                        $file2 = $filename;
                    }
                    break;  
        }
        $file_i++;
    }

    //Attachment Update
    if (!empty($file1) || !empty($file2)) {
        $sql = "UPDATE YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_TBL
                    SET ATTACHMENT1 = :ATTACHMENT1,
                        ATTACHMENT2 = :ATTACHMENT2
                    WHERE ID = :INSP_ID";
        
        $sqlarr = oci_parse($dbcon , $sql);
        oci_bind_by_name($sqlarr, ':ATTACHMENT1', $file1);
        oci_bind_by_name($sqlarr, ':ATTACHMENT2', $file2);
        oci_bind_by_name($sqlarr, ':INSP_ID', $newid);
        $r = oci_execute($sqlarr, OCI_NO_AUTO_COMMIT);

        if (!$r) {
            $e = oci_error($sqlarr);
            $errorMsg = json_encode($e['message']);
            goto finalStep;
        }
    }

    //Medisafe Import
    if (!empty($newid) && empty($errorMsg) && !empty($mstimport)) {
        foreach ($mstimport as $mst) {
            $api_url = 'https://medisafeportal.com/mst-api-prod/api/subinv-mst.php';
            
            $bearer_token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJZVFkiLCJuYW1lIjoiWVRZIEF0dGVuZGFuY2UiLCJhZG1pbiI6dHJ1ZX0.tWOG3I9GXNjNxbUeVO14baRgUEi7z7bWXswA7QBLaxuC-Nt23Asp6MgnopOHrYSfdDQMuG9ONmQPnTBWAO2QCvHjsiJ5WGDAW6s-uQ53t5hdkABYD9iIuUHmDTLENE9sEhF7HQHP5ebdgQXxny20q6C4KXnKdYOrr2khlzCf2kAJugAjj9UkuKIFZO8rxuZpMrYHimqnpd-5u6cqLj5_yExAR8bhaBmHHxwV7IWi2bxqLy655QAGV8PvH62dPsY4pYoMKFQKR8ff6sH1WUJacrqR2rylwWD_K1Uq8svZkr5ptwjB2mK5SC9SJ9-sU15Kp4YQnhs5J6ADcgRx1CEtZg';

            $dataReq = [
                "p_header_id" => $mst["INVOICE_HEADER_ID"],
                "P_LINE_ID" => $mst["INVOICE_LINE_ID"],
                "TR_TYPE" => "WIP",
                "FROM_SUBINV" => "GTH",
                "FROM_LOCATOR" => "GTH.INTR",
                "TO_SIBINV" => "GTH",
                "TO_LOCATOR" => "GTH.STWIP"
            ];
            $json_data = json_encode($dataReq);

            $response_data = null;
            try {
                $ch = curl_init($api_url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);

                $headers = [
                    'Authorization: Bearer ' . $bearer_token,
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($json_data)
                ];
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                $response = curl_exec($ch);

                if (curl_errno($ch)) {
                    $response_data = null;
                    $error_msg = curl_error($ch);
                    $e_message = $error_msg;
                
                } else {
                    $response_data = json_decode($response, true);

                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $response_data = null;
                    }
                }

                $e_flag = "";
                $e_message = "";
                if (!empty($response_data)) {
                    $e_flag = $response_data['E_code'];
                    $e_message = $response_data['E_Message'];
                }
            } catch (Exception $e) {
                error_log("Medisafe API Exception: " . $e->getMessage());
            }

            //$ids_array = array_column($mstimport, 'ID'); $sql_det = IN (".implode(',', $ids_array).")
            if ($e_flag === 'S' || $e_flag === 'AP') {    
                $sql_det = " UPDATE gth_medisafe_invoice_details
                                SET status = 2,
                                    gth_id = :gth_id,
                                    gth_date = SYSDATE,
                                    ebs_flag = :ebs_flag,
                                    ebs_message = :ebs_message,
                                    ebs_request = :ebs_request,
                                    ebs_response = :ebs_response,
                                    ebs_date = sysdate
                            WHERE id = :mstid";

                $resp_json = json_encode($response_data);

                $sqlarr_det = oci_parse($dbcon , $sql_det);
                oci_bind_by_name($sqlarr_det, ':gth_id', $newid);
                oci_bind_by_name($sqlarr_det, ':ebs_flag', $e_flag);
                oci_bind_by_name($sqlarr_det, ':ebs_message', $e_message);
                oci_bind_by_name($sqlarr_det, ':ebs_request', $json_data);
                oci_bind_by_name($sqlarr_det, ':ebs_response', $resp_json);
                oci_bind_by_name($sqlarr_det, ':mstid', $mst["ID"]);
                $r = oci_execute($sqlarr_det, OCI_NO_AUTO_COMMIT);

                if (!$r) {
                    $e = oci_error($sqlarr_det);
                    $errorMsg = json_encode($e['message']);
                    goto finalStep;
                }
            }
        }
    }

    function compressAndSaveImage($source, $destination, $extension) {
        // 1. Get original image sizes
        list($width, $height) = getimagesize($source);
        if (!$width || !$height) return false;

        // 2. Set an optional maximum boundary dimension (e.g., 2000px) 
        // This stops massive mobile photos from consuming too much database storage or RAM
        $maxDimension = 2000;
        if ($width > $maxDimension || $height > $maxDimension) {
            $ratio = min($maxDimension / $width, $maxDimension / $height);
            $newWidth = round($width * $ratio);
            $newHeight = round($height * $ratio);
        } else {
            $newWidth = $width;
            $newHeight = $height;
        }

        // 3. Prepare canvas
        $virtualImage = imagecreatetruecolor($newWidth, $newHeight);

        // 4. Load original image by type
        if ($extension === 'png') {
            $sourceImage = imagecreatefrompng($source);
            imagealphablending($virtualImage, false);
            imagesavealpha($virtualImage, true);
        } else {
            $sourceImage = imagecreatefromjpeg($source);
        }

        if (!$sourceImage) return false;

        // 5. Resize original into canvas
        imagecopyresampled($virtualImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

        // 6. Save back to disk with compression parameters
        if ($extension === 'png') {
            $success = imagepng($virtualImage, $destination, 6); // Scale 0-9 (6 is standard compression)
        } else {
            $success = imagejpeg($virtualImage, $destination, 75); // Quality 0-100 (75 drastically drops file size beautifully)
        }

        // 7. Clean up RAM allocation
        imagedestroy($virtualImage);
        imagedestroy($sourceImage);

        return $success;
    }

finalStep:
    $result = [];
    if ($errorMsg == "") {
        oci_commit($dbcon);
        $result[] = [
            "message" => "Success",
            "id" => $newid
        ];
    } else {
        oci_rollback($dbcon);
        $result[] = [
            "message" => $errorMsg,
            "id" => ""
        ];
    }
    print json_encode($result);
?>