<?php

$inputRules = [
    "from_firstname" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_lastname" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_email" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_phone" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_address" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_zipcode" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_city" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_state" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "from_country" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],

    "to_firstname" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_lastname" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_email" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_phone" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_address" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_zipcode" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_city" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_state" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "to_country" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],

    "subject" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "date" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "note" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
];

$failed = false;

$oldFiles = explode("|",$_POST['from_oldfiles']);
$removeOldFiles = explode("|",$_POST['from_delete_files']);
$updateOldFiles = [];

foreach($oldFiles as $key => $val) {
    if(!empty($val)){
        $checkFile = explode("-", $val);
        if (in_array($checkFile[0], $removeOldFiles)){
            $filename = $checkFile[1];
            unlink(__DIR__ . '/../user/storage/upload/'.$filename);
        } else {
            $updateOldFiles[] = $val;
        }
    }
}


if (__RB_validateInput($inputRules, 'shipping_upload_edit')) {
    $failed = false;

    $oldPost = $_POST;

    $objCreate = [
        'files' => []
    ];

    foreach ($inputRules as $key => $val) {
        $objCreate[$key] = $_POST[$key];
    }
    // echo "<pre>";
    // print_r($_POST);
    // print_r($_FILES);
    // exit;
    if(!empty($_FILES["upload"]['name'][0])) {
        foreach ($_FILES["upload"]["error"] as $key => $error) {
            if ($error != UPLOAD_ERR_OK) {
                $failed = true;
            }

            $finfo = new finfo(FILEINFO_MIME_TYPE);

            if ('application/pdf' != $finfo->file($_FILES['upload']['tmp_name'][$key])) {
                __RB_errorHandler('shipping_upload_edit', 'upload', 'Upload File : '. $__RB_LNG['error']['validation']);

                $failed = 2;
            }
        }
    }

    $date = explode('-', $_POST['date']);
    $date2 = explode('/', $_POST['date']);

    if (empty($data[1]) && !empty($date2[1])) {
        $date = $date2;
    }

    $year = $date[2];
    $month = $date[0];
    $day = $date[1];

    if (!checkdate($month, $day, $year)) {
        __RB_errorHandler('shipping_upload_edit', 'date', 'Date : ' . $__RB_LNG['error']['validation']);

        $failed = 2;
    }

    if (!$failed) {
        if(!empty($_FILES["upload"]['name'][0])) {
            foreach ($_FILES["upload"]["tmp_name"] as $key => $error) {
                move_uploaded_file($_FILES["upload"]["tmp_name"][$key], __DIR__ . '/../user/storage/upload/' . $_SESSION['id'] . '_' . $key .'_'. time() . '.pdf');
                $objCreate['files'][$_FILES["upload"]["name"][$key]]  = $_SESSION['id'] . '_' . $key .'_'. time() . '.pdf';
            }
        }

        foreach($updateOldFiles as $newKey => $value) {
            $str = explode('-', $value);
            $objCreate['files'][$str[0]] = $str[1];
        }

        $json = "";
        
        $data = [
            'id' => $_POST['id'],
            'id_customer' => $_SESSION['id'],
            'data' => $objCreate
        ];

        __RB_api_cloud(__RB_API_ACTION_CLOUD_SET_SHIPPING, $data, $json);

        $__RB_success['shipping_upload_edit'] = true;

        $_POST = [];

    } else {
        if ($failed !== 2) {
            __RB_errorHandler('shipping_upload_edit', 'upload', $__RB_LNG['error']['missing'] . ' Upload file');
        }
    }
}
