<?php
defined(page_security_key) or exit;

$page = 'shipping';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');

$shipping = [
    'id' =>'',
    'name' => '',
    'price_from' => '',
    'price_to' => '',
    'weight_from' => '',
    'weight_to' => '',
    'price' => '',
    'type' => 'Single Product',
    'countries' => ''
];

//CALL TO API FOR shipping
$api_url = '/v2/taxes/';
$countries = ioServer($api_url,'');
//Decode Payload
if (!empty($countries)){$countries = json_decode($countries,true);}else{$countries = null;}

//CountryID mapping
$countryMap = array_column($countries, 'country', 'id');

if (isset($_GET['id'])) {
  
    //CALL TO API FOR shipping
    $api_url = '/v2/shipping/id='.$_GET['id'];
    $shipping = ioServer($api_url,'');
    //Decode Payload
    if (!empty($shipping)){$shipping = json_decode($shipping,true);}else{$shipping = null;}
    $shipping = $shipping[0];


    if (isset($_POST['submit'])) {
        //Update the shipping

        //GET ALL POST DATA
        $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
        //API call
        $responses = ioServer('/v2/shipping', $payload);
        if ($responses === 'NOK'){

        } else {
            header('Location: index.php?page=shipping&success_msg=2');
            exit;
        }
    }
    if (isset($_POST['delete'])) {
        //GET ALL POST DATA
        $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
        var_dump($payload);
        //API call
        $responses = ioServer('/v2/shipping', $payload);
        if ($responses === 'NOK'){

        } else {
            //Redirect and delete product
            header('Location: index.php?page=shipping&success_msg=3');
            exit;
        }
    }

} else {
  
    // Create a new shipping
    $page = 'Create';
    if (isset($_POST['submit'])) {
        //GET ALL POST DATA
        $payload = json_encode($_POST , JSON_UNESCAPED_UNICODE);
        //API call
        $responses = ioServer('/v2/shipping', $payload);
        if ($responses === 'NOK'){
            // DO nothing
            } 
        else {
            header('Location: index.php?page=shipping&success_msg=1');
            exit;
        }
    }
}

template_header('shipping', 'shipping', 'manage');

$view ='
<form action="" method="post" enctype="multipart/form-data">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.($shipping_h2 ?? 'shipping').'</h2>
        <a href="index.php?page=shipping" class="btn alt mar-right-2">'.$button_cancel.'</a>
';

if ($delete_allowed === 1){
    $view .= '<input type="submit" name="delete" value="Delete" class="btn red mar-right-2" onclick="return confirm(\'Are you sure you want to delete this shipping?\')">';
}
if ($update_allowed === 1){
    $view .= '<input type="submit" name="submit" value="Save" class="btn">';
}
   
$view .= '</div>';

$view .= '<div class="content-block">

        <div class="form responsive-width-100">

            <label for="name"><i class="required">*</i>'.($shipping_name ?? 'Name').'</label>
            <input type="text" name="name" placeholder="'.($shipping_name ?? 'Name').'" value="'.$shipping['name'].'" required>
            <input type="hidden" name="id" value="'.$shipping['id'].'">
            <label for="type"><i class="required">*</i>'.($shipping_type ?? 'Type').'</label>
            <select name="type" id="type" required>
                <option value="'.$shipping['type'].'" '.($shipping['type']== 0 ? ' selected':'').'>'.($shipping_type_standard ?? 'Standard').'</option>
                <option value="'.$shipping['type'].'" '.($shipping['type']== 1 ? ' selected':'').'>'.($shipping_type_express ?? 'Expres').'</option>
            </select>
            <label for="countries">'.($shipping_countries ?? 'Countries').'</label>
            <div class="multiselect" data-name="countries[]">';
                foreach (explode(',', $shipping['countries']) as $c){
                    if (empty($c)) continue; {
                        
                 $view .= ' <span class="item" data-value="'.$c.'">
                                <i class="remove">&times;</i>'.($countryMap[$c]).'
                                <input type="hidden" name="countries[]" value="'.$c.'">
                            </span>';
                    }
                }
$view .= '      <input type="text" class="search" id="countries" placeholder="'.($shipping_countries ?? 'Countries').'">
                <div class="list">';
                    foreach ($countries as $country){
                    $view .= '<span data-value="'.$country['id'].'">'.(${$country['country']} ?? $country['country']).'</span>';
                    }
$view .= '      </div>
            </div>

            <label for="price"><i class="required">*</i>'.($shipping_price_range ?? 'Product Price Range').'</label>
            <div style="display:flex;margin:0;">
                <input type="number" name="price_from" placeholder="'.($shipping_from ?? 'From').'" min="0" step=".01" value="'.$shipping['price_from'].'" required>
                <span style="padding-top:15px">&nbsp;&nbsp;&nbsp;&mdash;&nbsp;&nbsp;&nbsp;</span>
                <input type="number" name="price_to" placeholder="'.($shipping_to ?? 'To').'" min="0" step=".01" value="'.$shipping['price_to'].'" required>
            </div>

            <label for="price"><i class="required">*</i>'.($shipping_weight_range ?? 'Product Weight Range (kg)').' </label>
            <div style="display:flex;margin:0;">
                <input type="number" name="weight_from" placeholder="'.($shipping_from ?? 'From').'" min="0" step=".01" value="'.$shipping['weight_from'].'" required>
                <span style="padding-top:15px">&nbsp;&nbsp;&nbsp;&mdash;&nbsp;&nbsp;&nbsp;</span>
                <input type="number" name="weight_to" placeholder="'.($shipping_to ?? 'To').'" min="0" step=".01" value="'.$shipping['weight_to'].'" required>
            </div>

            <label for="name"><i class="required">*</i>'.($shipping_total_price ?? 'Total Shipping Price').' </label>
            <input type="number" name="price" placeholder="3.99" min="0" step=".01" value="'.$shipping['price'].'" required>

        </div>

    </div>

</form>';

//Output
echo $view;
template_footer();
?>