<?php
defined(page_security_key) or exit;

$page = 'discount';
//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');

$discount = [
    'id' =>'',
    'category_ids' => '',
    'product_ids' => '',
    'discount_code' => '',
    'discount_type' => 1,
    'discount_value' => 0,
    'start_date' => date('Y-m-d\TH:i'),
    'end_date' => date('Y-m-d\TH:i', strtotime('+1 month', strtotime(date('Y-m-d\TH:i')))), 
    'categories' => [],
    'products' => []
];

//GET ALL CATEGORIES
$api_url = '/v2/categories/';
$categories = ioServer($api_url,'');
//Decode Payload
if (!empty($categories)){$categories = json_decode($categories,true);}else{$categories = null;}

//GET PRODUCTS
$api_url = '/v2/products/list=';
$products = ioServer($api_url,'');
//Decode Payload
if (!empty($products)){$products = json_decode($products,true);}else{$products = null;}

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

    //GET CATEGORY NAMES RELATED TO DISCOUNT discount_category_id
    $api_url = '/v2/discounts/discount_category_id='.$_GET['id'];
    $discount_cat = ioServer($api_url,'');
    //Decode Payload
    if (!empty($discount_cat)){$discount['categories'] = json_decode($discount_cat,true);}else{$discount['categories']= null;}

    //GET CATEGORY NAMES RELATED TO DISCOUNT discount_products_id
    $api_url = '/v2/discounts/discount_products_id='.$_GET['id'];
    $discount_prod = ioServer($api_url,'');
    //Decode Payload
    if (!empty($discount_prod)){$discount['products'] = json_decode($discount_prod,true);}else{$discount['products']= null;}
    

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

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

        } else {
            header('Location: index.php?page=discounts&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/discounts', $payload);
        if ($responses === 'NOK'){

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

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

template_header('discount', 'discounts', '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">'.($discounts_h2 ?? 'discounts').'</h2>
        <a href="index.php?page=discounts" 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 discount?\')">';
}
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="code"><i class="required">*</i>'.($discounts_code ?? 'Code').'</label>
            <input id="code" type="text" name="discount_code" placeholder="'.($discounts_code ?? 'Code').'" value="'.$discount['discount_code'].'" required>
            <input type="hidden" name="id" value="'.$discount['id'].'">
            <label for="categories">'.($discounts_category ?? 'Categories').'</label>
            <div class="multiselect" data-name="categories[]">';
                foreach ($discount['categories'] as $cat){
                $view .= '<span class="item" data-value="'.$cat['rowID'].'">
                            <i class="remove">&times;</i>'.$cat['name'].'
                            <input type="hidden" name="categories[]" value="'.$cat['rowID'].'">
                        </span>';
                }
 $view .= '     <input type="text" class="search" id="categories" placeholder="Categories">
                <div class="list">';
                    foreach ($categories as $cat){
                    $view .= '<span data-value="'.$cat['rowID'].'">'.$cat['name'].'</span>';
                    }
$view .= '      </div>
            </div>

            <label for="products">'.($discounts_product ?? 'Products').'</label>
            <div class="multiselect" data-name="products[]">';
                foreach ($discount['products'] as $product){
       $view .= '   <span class="item" data-value="'.$product['rowID'].'">
                    <i class="remove">&times;</i>'.$product['productname'].'
                    <input type="hidden" name="products[]" value="'.$product['rowID'].'">
                </span>';
                }
        $view .= '<input type="text" class="search" id="products" placeholder="Products">
                <div class="list">';
                    foreach ($products as $product){
                   $view .= ' <span data-value="'.$product['rowID'].'">'.$product['productname'].'</span>';
                    }
        $view .= '</div>
            </div>

            <label for="type"><i class="required">*</i>'.($discounts_type ?? 'Type').'</label>
            <select id="type" name="discount_type">
                <option value="0" '.($discount['discount_type']== 0 ? ' selected':'').'>'.($discounts_type_fixed ?? 'Fixed').'</option>
                <option value="1" '.($discount['discount_type']== 1 ? ' selected':'').'>'.($discounts_type_percentage ?? 'Percentage').'</option>
            </select>
            <label for="discount_value"><i class="required">*</i>'.($discounts_value ?? 'Value').'</label>
            <input id="discount_value" type="number" name="discount_value" placeholder="'.($discounts_value ?? 'Value').'" min="0" step=".01" value="'.$discount['discount_value'].'" required>

            <label for="start_date"><i class="required">*</i>'.($discounts_start_date ?? 'Start Date').'</label>
            <input id="start_date" type="datetime-local" name="start_date" placeholder="'.($discounts_start_date ?? 'Start Date').'" value="'.(date('Y-m-d\TH:i', strtotime($discount['start_date']))).'" required>

            <label for="end_date"><i class="required">*</i> End Date</label>
            <input id="end_date" type="datetime-local" name="end_date" placeholder="'.($discounts_end_date ?? 'End Date').'" value="'.(date('Y-m-d\TH:i', strtotime($discount['end_date']))).'" required>

        </div>

    </div>

</form>';

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