<?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 = 'order';

//create backbutton to prev_origin
$back_btn_orgin =  ($prev_page != '')? '<a href="'.$prev_page.'" class="btn alt mar-right-2">'.$button_back.'</a>':'';

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

//GET PARAMETERS && STORE in SESSION for FURTHER USE/NAVIGATION
$pagination_page = $_SESSION['p'] = isset($_GET['p']) ? $_GET['p'] : 1;

//PAGE Security
$page_manage = 'order_manage';
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$update_allowed_edit = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'C');

//GET Details from URL
$_GET['list'] = 'order';
$GET_VALUES = urlGETdetails($_GET) ?? '';

//CALL TO API
$api_url = '/v2/transactions/'.$GET_VALUES;
$order = ioServer($api_url,'');
//Decode Payload
if (!empty($order)){$order = json_decode($order,true);}else{$order = null;}

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

template_header('order', 'order', 'view');
$view = '
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.$order['header']['id'].' - '.$order['header']['txn_id'].'</h2>
        <a href="index.php?page='.$_SESSION['origin'].'&p='.$_SESSION['p'].'" class="btn alt mar-right-2">'.$button_cancel.'</a>
';


//------------------------------------
//
//------------------------------------
if ($update_allowed_edit === 1){
    $view .= '<a href="index.php?page=order_manage&id='.$_GET['id'].'" class="btn">Edit</a>';
}

$view .= '</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-block-wrapper">';

$view .='
    <div class="content-block order-details">
        <div class="block-header">
            <i class="fa-solid fa-cart-shopping fa-sm"></i>Order Details
        </div>
        <div class="order-detail">
            <h3>Order ID</h3>
            <p>' . $order['header']['id'] . '</p>
        </div>
        <div class="order-detail">
            <h3>Transaction ID</h3>
            <p>' . $order['header']['txn_id'] . '</p>
        </div>';

if ($order['header']['shipping_method']) {
    $view .='
        <div class="order-detail">
            <h3>Shipping Method</h3>
            <p>' . htmlspecialchars($order['header']['shipping_method'], ENT_QUOTES) . '</p>
        </div>';
}

//Translate status INT to STR
$payment_status = 'payment_status_'.$order['header']['payment_status'];
$payment_method = 'payment_method_'.$order['header']['payment_method'];

$view .='
        <div class="order-detail">
            <h3>Payment Method</h3>
            <p>' . (${$payment_method} ?? $order['header']['payment_method'] ). '</p>
        </div>
        <div class="order-detail">
            <h3>Payment Status</h3>
            <p>' . (${$payment_status} ?? $order['header']['payment_status'] ). '</p>
        </div>
        <div class="order-detail">
            <h3>Date</h3>
            <p>'.getRelativeTime($order['header']['created']). '</p>
        </div>';

if ($order['header']['discount_code']) {
    $view .='
        <div class="order-detail">
            <h3>Discount Code</h3>
            <p>' . htmlspecialchars($order['header']['discount_code'], ENT_QUOTES) . '</p>
        </div>';
}

$view .='    </div>';

// Account Details Block
$view .='
    <div class="content-block order-details">
        <div class="block-header">
            <i class="fa-solid fa-user fa-sm"></i>Account Details
        </div>';

if ($order['customer']['email']) {
    $view .='
        <div class="order-detail">
            <h3>Email</h3>
            <p><a href="index.php?page=account&id=' . $order['header']['id'] . '" target="_blank" class="link1" style="margin:0">' . htmlspecialchars($order['customer']['email'], ENT_QUOTES) . '</a></p>
        </div>
        <div class="order-detail">
            <h3>Name</h3>
            <p>' . htmlspecialchars($order['customer']['name'], ENT_QUOTES) . '</p>
        </div>
        <div class="order-detail">
            <h3>Address</h3>
            <p style="text-align:right;">' . htmlspecialchars($order['customer']['street'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['city'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['state'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['zip'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['country'], ENT_QUOTES) . '</p>
        </div>
        <div class="order-detail">
            <h3>Contact</h3>
            <p style="text-align:right;">' . htmlspecialchars($order['customer']['phone'], ENT_QUOTES) . '</p>
        </div>';
} else {
    $view .='        <p>The order is not associated with an account.</p>';
}

$view .='    </div>';

// Customer Details Block
$view .='
    <div class="content-block order-details">
        <div class="block-header">
            <i class="fa-solid fa-user fa-sm"></i>Customer Details
        </div>
        <div class="order-detail">
            <h3>Email</h3>
            <p>' . htmlspecialchars($order['customer']['email'], ENT_QUOTES) . '</p>
        </div>
        <div class="order-detail">
            <h3>Name</h3>
            <p>' . htmlspecialchars($order['customer']['name'], ENT_QUOTES) . ' </p>
        </div>
        <div class="order-detail">
            <h3>Address</h3>
            <p style="text-align:right;">' . htmlspecialchars($order['customer']['street'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['city'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['state'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['zip'], ENT_QUOTES) . '<br>
                ' . htmlspecialchars($order['customer']['country'], ENT_QUOTES) . '</p>
        </div>
        <div class="order-detail">
            <h3>Contact</h3>
            <p style="text-align:right;">' . htmlspecialchars($order['customer']['phone'], ENT_QUOTES) . '</p>
        </div>
    </div>
</div>';

// Order Items Table
$view .='
<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>Order
    </div>
    <div class="table order-table">
        <table>
            <thead>
                <tr>
                    <td>Product</td>
                    <td>Options</td>
                    <td>Qty</td>
                    <td class="responsive-hidden">Price</td>
                    <td style="text-align:right;">Total</td>
                </tr>
            </thead>
            <tbody>';

if (empty($order)) {
    $view .='
                <tr>
                    <td colspan="5" style="text-align:center;">There are no order items</td>
                </tr>';
} else {
    foreach ($order['products'] as $item) {

        $view .='
                <tr>
                    <td>' . ($item['product_name'] ? htmlspecialchars(${$item['product_name']} ?? $item['product_name'] , ENT_QUOTES) : '(Product ' . $item['item_id'] . ')') . '</td>
                    <td>' . ($item['options'] ? htmlspecialchars(implode(", ", $item['options']), ENT_QUOTES) : '--') . '</td>
                    <td>' . $item['quantity'] . '</td>
                    <td class="responsive-hidden">' .  number_format($item['price'], 2) . '</td>
                    <td style="text-align:right;">' .  number_format($item['line_total'], 2) . '</td>
                </tr>';
    }
}

$view .='
                <tr>
                    <td colspan="5" class="item-list-end"></td>
                </tr>
                <tr>
                    <td colspan="4" class="subtotal">Subtotal</td>
                    <td class="num">' .  number_format($order['pricing']['subtotal'], 2) . '</td>
                </tr>
                <tr>
                    <td colspan="4" class="shipping">Shipping</td>
                    <td class="num">' .  number_format($order['pricing']['shipping_total'], 2) . '</td>
                </tr>
                <tr>
                    <td colspan="4" class="shipping">Discount</td>
                    <td class="num">' .  number_format($order['pricing']['discount_total'], 2) . '</td>
                </tr>
                <tr>
                    <td colspan="4" class="shipping">VAT</td>
                    <td class="num" style="border-bottom: 1px solid #f0f1f2;">' .  number_format($order['pricing']['tax_total'], 2) . '</td>
                </tr>
                <tr>
                    <td colspan="4" class="total">Total</td>
                    <td class="num"><b>' .  number_format($order['pricing']['payment_amount'], 2) . '</b></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>';

// Giftcards Block
$view .='
<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>Giftcards
    </div>
    <div class="table order-table">
        <a href="index.php?page=order&id=' . $_GET['id'] . '&add_giftcard" class="btn">Relate giftcards</a>
        <table>
            <thead>
                <tr>
                    <td>Giftcard</td>
                    <td>Valid</td>
                    <td>Value</td>
                </tr>
            </thead>
            <tbody>';

if (empty($giftcards)) {
    $view .='
                <tr>
                    <td colspan="5" style="text-align:center;">There are no order items</td>
                </tr>';
} else {
    foreach ($giftcards as $giftcard) {
        $view .='
                <tr>
                    <td>' . $giftcard['discount_code'] . '</td>
                    <td>' . ($current_date >= strtotime($giftcard['start_date']) && $current_date <= strtotime($giftcard['end_date']) ? 'Yes' : 'No') . '</td>
                    <td>' .  number_format($giftcard['discount_value'], 2) . '</td>
                </tr>';
    }
}

$view .='
                <tr>
                    <td colspan="5" class="item-list-end"></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>';

// Invoice Block
$view .='
<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>Invoice
    </div>
    <div class="table order-table">
        <table>
            <tr>
                <td style="width:70px";>
                    <form action="index.php?page=factuur" method="post">
                        <input type="hidden" name="txn_id" value="' . $order['header']['txn_id'] . '">
                        <input type="submit" class="btn" name="show_invoice" value="Show">
                    </form>
                </td>
                <td style="width: 157px;">
                    <form action="index.php?page=factuur" method="post">
                        <input type="hidden" name="txn_id" value="' . $order['header']['txn_id'] . '">
                        <input type="submit" class="btn" name="email_invoice" value="Email to Customer" onclick="return confirm(\'Send invoice to customer?\');">
                    </form>
                </td>
                <td>
                    <form action="index.php?page=factuur" method="post">
                        <input type="hidden" name="txn_id" value="' . $order['header']['txn_id'] . '">
                        <input type="submit" class="btn" name="email_invoice_to_admin" value="Email to Admin" onclick="return confirm(\'Send invoice to admin?\');">
                    </form>
                </td>
            </tr>
        </table>
    </div>';

$view .='</div>';

//OUTPUT
echo $view;    

template_footer()

?>