<?php
defined(page_security_key) or exit;

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

// Default input product values
$products_configurations = [
    'rowID' => '',
    'productrowid' => '',
    'status' => '',
    'version' => '',
    'assignment' => '',
    'created' => '',
    'createdby' => $_SESSION['username'],
    'updated' => '',
    'updatedby' => ''
];

//productrowid is required by api
$productrowid = $_GET['productrowid'] ?? '';

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

//GET RELATED PRODUCT VERSIONS
$api_url = '/v2/products_versions/productrowid='.$productrowid;
$products_versions = ioServer($api_url,'');

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


if (isset($_GET['rowID'])) {
    // ID param exists, edit an existing product
    //CALL TO API
    $api_url = '/v2/products_configurations/rowID='.$_GET['rowID'].'&productrowid='.$productrowid;
    $responses = ioServer($api_url,'');

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

    $products_configurations = json_decode(json_encode($responses[0]), true);

    //------------------------------------------
    //CALL TO API FOR RELATED ATTTRIBUTES_ITEMS
    //GET rowID of group from assignment
    //------------------------------------------
    $api_url = '/v2/products_attributes/group_id='.$products_configurations['assignment'];
    $group_id = ioServer($api_url,'');

    if (!empty($group_id) && strlen($group_id) > 3){
        $group_id = json_decode($group_id,true);
        //get the related attributes
        $api_url = '/v2/products_attributes_items/media=all&group_id='.$group_id[0]['rowID'];
        $products_attributes_items = ioServer($api_url,'');
        //Decode Payload
        if (!empty($products_attributes_items)){$products_attributes_items = json_decode($products_attributes_items,true);}else{$products_attributes_items = null;}

    } 

    if ($update_allowed === 1){
        if (isset($_POST['submit'])) {

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

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

            } else {
            // Redirect and delete product
            header('Location: index.php?page=product&rowID='.$productrowid.'&success_msg=3');
            exit;
            }
        }
    }
   
} else {
    // Create a new product
    if (isset($_POST['submit']) && $create_allowed === 1) {
        
        //GET ALL POST DATA
        $payload = json_encode($_POST , JSON_UNESCAPED_UNICODE);
        //API call
        $responses = ioServer('/v2/products_configurations', $payload);
        if ($responses === 'NOK'){

            } 
        else {
        header('Location: index.php?page=product&rowID='.$productrowid.'&success_msg=1');
        exit;
        }
    }
}

template_header('Products configurations', 'products configurations', '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">'.($product_configuration ?? 'Product configuration').'</h2>
        <a href="index.php?page=product&rowID='.$productrowid.'" 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 product?\')">';
}
if ($update_allowed === 1){
    $view .= '<input type="submit" name="submit" value="Save" class="btn">';
}
   
$view .= '</div>';

$view .= '<div class="tabs">
            <a href="#" class="active">'.$tab1.'</a>
            <a href="#">'.$tab3.'</a>
         </div>
    ';

$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                <label for="status">'.$product_status.'</label>
                <select id="status" name="status">
                    <option value="1" '.($products_configurations['status']==1?' selected':'').'>'.$prod_status_1 .'</option>
                    <option value="0" '.($products_configurations['status']==0?' selected':'').'>'.$prod_status_0 .'</option>
                </select>
                <label for=""><i class="required">*</i>'.($product_configuration_version ?? 'Version').'</label>
                <select name="version">';
                foreach ($products_versions as $product_version){
                    $view .= '<option value="'.$product_version['rowID'].'" '.($product_version['rowID']==$products_configurations['version'] ?' selected':'').'>'.($product_version['version'] ?? '').'</option>
                    ';}  
    $view .= '  </select>   
                <label for=""><i class="required">*</i>'.($product_configuration_assignment ?? 'Product assignment').'</label>
                <select name="assignment">';
                foreach ($products as $product){
                    $view .= '<option value="'.$product['product_id'].'" '.($product['product_id']==$products_configurations['assignment'] ?' selected':'').'>'.$product['product_id'].' - '.(${$product['product_name']} ?? $product['product_name']).'</option>
                   ';}  
    $view .= '  </select>';

$view .= '                
                <input type="hidden" name="rowID" value="'.$products_configurations['rowID'].'"> 
                <input type="hidden" name="productrowid" value="'.$productrowid.'">   
            </div>
        </div>';

$view .= '<div class="content-block tab-content">
        <div class="form responsive-width-100">
            <label for="productcode">'.$general_created.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_created.'" value="'.$products_configurations['created'].'" readonly>
            <label for="productcode">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$products_configurations['createdby'].'" readonly>
        </div>
    </div>';
$view .= '</form>';

if (!empty($products_attributes_items)){
    $view .= '
            <div class="content-block">
                <h2 class="responsive-width-100">'.($products_attributes_group_items ?? 'Groupitems').'</h2>
                <div class="table">
                    <table>
                        <thead>
                            <tr>
                                <th>'.($products_attributes_item_name ?? 'name').'</th>
                                <th>'.($products_attributes_item_quantity ?? 'quantity').'</th>
                                <th>'.($products_attributes_item_media ?? 'media').'</th>
                                <th>'.$general_created.'</th>
                                <th>'.$general_actions.'</th>
                            </tr>
                        </thead>
                        <tbody id="tableBody">
                        ';
                foreach ($products_attributes_items as $item){
                    $view .= '   
                        <tr>  
                            <td>'.(${$item['item_name']} ?? $item['item_name']).'</td>
                            <td>'.$item['item_quantity'].'</td>
                            <td><img id="image_'.$item['rowID'].'" src="'.$item['full_path'].'" alt="" style="display: block; max-width: 75px;">    
                            </td>
                            <td>'.getRelativeTime($item['created']).'</td>
                        </tr>
                    ';
                }
                $view .= ' 
                    </tbody>
                </table>
            </div>
        </div>';

}

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