<?php
    include "../db/headerApi.php";
    include "../db/connection_main.php";

    //$json = file_get_contents('php://input');
    //$data = json_decode($json);

    $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"]);

    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";
        
        $sqlarr = oci_parse($dbcon , $sql);
        oci_bind_by_name($sqlarr, ':ref_no', $refno);
        oci_bind_by_name($sqlarr, ':brand', $data->BRAND->ID);
        $r = oci_execute($sqlarr);

        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, 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, :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, ':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 and Brand 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;
        }
    }

    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);
?>