<?php
defined(page_security_key) or exit;

if (debug && debug_id == $_SESSION['id']){
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);  
}

include_once './assets/functions.php';
include_once './settings/settings_redirector.php';

//SET ORIGIN FOR NAVIGATION
$prev_page = $_SESSION['prev_origin'] ?? '';
$page = $_SESSION['origin'] = 'shipping';

//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}

//GET PARAMETERS
$pagination_page = isset($_GET['p']) ? $_GET['p'] : 1;
$search = isset($_GET['search']) ? '&search='.$_GET['search'] : '';

// Determine the URL
$url = 'index.php?page=shipping'.$search;
//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
//CALL TO API
$api_url = '/v2/shipping/'.$GET_VALUES;
$shipping = ioServer($api_url,'');
//Decode Payload
if (!empty($shipping)){$shipping = json_decode($shipping,true);}else{$shipping = null;}

//Return QueryTotal from API
$api_url = '/v2/shipping/totals=';
$query_total = ioServer($api_url,'');

//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;}

//Decode Payload
if (!empty($query_total)){$query_total = json_decode($query_total,true);}else{$query_total = null;}

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 1) {
        $success_msg = $message_shipping_1 ?? 'Created';
    }
    if ($_GET['success_msg'] == 2) {
        $success_msg = $message_shipping_2 ?? 'Updated';
    }
    if ($_GET['success_msg'] == 3) {
        $success_msg = $message_shipping_3 ?? 'Deleted' ;
    }
}

template_header('shipping', 'shipping','view');
$view = '
<div class="content-title">
    <div class="title">
        <i class="fa-solid fa-truck-fast"></i>
        <div class="txt">
            <h2>'.($shipping_h2 ?? 'shipping').' ('.$query_total.')</h2>
            <p>'.($shipping_p ?? '').'</p>
        </div>
    </div>
</div>';

if (isset($success_msg)){
$view .= ' <div class="msg success">
                <i class="fas fa-check-circle"></i>
                <p>'.$success_msg.'</p>
                <i class="fas fa-times"></i>
            </div>';
}

$view .= '
<div class="content-header responsive-flex-column pad-top-5">
    <a href="index.php?page=shipping_manage" class="btn">'.($button_create_shipping ?? 'Create shipping').'</a>
</div>
<div class="content-block">
    <div class="table">
        <table>
            <thead>
                <tr>
                    <td>'.($shipping_id ?? '#').'</td>
                    <td>'.($shipping_name ?? 'name').'</td>
                    <td>'.($shipping_type ?? 'Type').'</td>
                    <td class="responsive-hidden">'.($shipping_category ?? 'Countries').'</td>
                    <td class="responsive-hidden">'.($shipping_price ?? 'Price Range').'</td>
                    <td class="responsive-hidden">'.($shipping_weight ?? 'Weight Range').'</td>
                    <td>'.($shipping_price_total ?? 'Total price').'</td>
                    <td>'.$general_actions.'</td>
                </tr>
            </thead>
            <tbody>';
                if (empty($shipping)){
                $view .= '<tr>
                            <td colspan="8" style="text-align:center;">'.($message_no_shipping ?? 'There are no shipping').'</td>
                         </tr>';
                }
                else {
                    foreach ($shipping as $shipment){
                        $current_date = strtotime((new DateTime())->format('Y-m-d H:i:s'));

                        $shipping_countries = ($shipment['countries'] ? str_replace(',', ', ', $shipment['countries']) : $general_all ?? 'all');
                        
                        if ($shipping_countries != ($general_all ?? 'all')){
                            $countryNames = getCountryNamesByIds($countries, $shipping_countries);
                            $shipping_countries = implode(', ', $countryNames);
                        }

                        $view .= '
                        <tr>
                            <td>'.$shipment['id'].'</td>
                            <td>'.$shipment['name'].'</td>
                            <td>'.($shipment['type'] == 0 ? ($shipping_type_standard ?? 'Standard' ) : ($shipping_type_express ?? 'Express')).'</td>
                            <td class="responsive-hidden" style="max-width:300px">'.$shipping_countries.'</td>
                            <td class="responsive-hidden">'.number_format($shipment['price_from'], 2).' - '.number_format($shipment['price_to'], 2).'</td>
                            <td class="responsive-hidden">'.number_format($shipment['weight_from'], 2).' kg - '.number_format($shipment['weight_to'], 2).' kg</td>
                            <td><?=currency_code?>'.number_format($shipment['price'], 2).'</td>
                            <td><a href="index.php?page=shipping_manage&id='.$shipment['id'].'" class="btn_link">'.$general_view.'</a></td>
                        </tr>';
                    }
                }
             
$view .= '                
            </tbody>
        </table>
    </div>
</div>
';

$view.='<div class="pagination">';
if ($pagination_page > 1) {
    $page = $pagination_page-1;
    $view .= '<a href="'.$url.'&p=1">'.$general_first.'</a>';
    $view .= '<a href="'.$url.'&p='.$page.'">'.$general_prev.'</a>';
}
$totals = ceil($query_total / $page_rows_shipping) == 0 ? 1 : ceil($query_total / $page_rows_shipping);
$view .= '<span> '.$general_page.$pagination_page.$general_page_of.$totals.'</span>';
if ($pagination_page * $page_rows_shipping < $query_total){
    $page = $pagination_page+1;
    $view .= '<a href="'.$url.'&p='.$page.'">'.$general_next.'</a>';
    $view .= '<a href="'.$url.'&p='.$totals.'">'.$general_last.'</a>';

}
$view .= '</div>';
//OUTPUT
echo $view;

template_footer();
?>