<?php
defined(page_security_key) or exit;

$page = 'pricelists_manage';
//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
$pricelists = [
    'rowID' => '',
    'status' => '',
    'name' => '',
    'created' => '',
    'createdby' => '',
    'updated' => '',
    'updatedby' => '',
    'accounthierarchy' => ''
];


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

    //CALL TO API FOR RELATED pricelists
    $api_url = '/v2/pricelists_items/pricelist_ID='.$_GET['rowID'];
    $pricelists_items = ioServer($api_url,'');
    //Decode Payload
    if (!empty($pricelists_items)){$pricelists_items = json_decode($pricelists_items,true);}else{$pricelists_items = null;}

    //GET PRODUCTS AND ATTRIBUTES
    $api_url = '/v2/products/list=price';
    $responses = ioServer($api_url,'');
    //Decode Payload
    if (!empty($responses)){$products = json_decode($responses,true);}else{$products = 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/pricelists', $payload);

            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=pricelists&success_msg=2');
            exit;
            }
        }

        if (isset($_POST['add'])) {
            //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //API call
            $responses = ioServer('/v2/pricelists_items', $payload);

            if ($responses === 'NOK'){

            } else {
                header('Location: index.php?page=pricelists_manage&rowID='.$_GET['rowID'].'');
                exit;
            }
        
        }
        if (isset($_POST['update']) && isset($_POST['item'])) {
            //Indicator if update has errors
            $NOK_error = 0;

            //RUN through all POST items
            foreach ($_POST['item'] as $attr){
                
                //GET ALL POST DATA
                $payload = json_encode($attr, JSON_UNESCAPED_UNICODE);

                //API call
                $responses = ioServer('/v2/pricelists_items', $payload);

                if ($responses === 'NOK'){
                    //NOT correct exit procedure
                    $NOK_error++; 
                    exit;
                } else {
                    $attr_language = $attr['language_key'];
                }
            }

            header('Location: index.php?page=pricelists_manage&rowID='.$_GET['rowID'].'');
            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/pricelists', $payload);
            // Redirect and delete product
            if ($responses === 'NOK'){

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

        } else {
            //GET ROWID OF CREATED ITEM
            $pricelists_rowID = json_decode($responses,true);
            header('Location: index.php?page=pricelists_manage&rowID='.$pricelists_rowID['rowID'].'');
            exit;
        }
    }
}
//EMPTY VIEW
$view = '';

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 0) {
        $success_msg = $error_msg_0;
    }
}

template_header('Pricelists', 'pricelists', 'manage');

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

$view .='
<form action="" method="post">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.($pricelists_h2 ?? '').'</h2>
        <a href="index.php?page=pricelists" 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 pricelist?\')">';
}
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>
    ';

//Define Service and User enabled
$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                <label for="">'.($pricelists_status ?? 'Status').'</label>
                <select name="status">
                    <option value="0" '.($pricelists['status']==0?' selected':'').'>'.$general_status_0.'</option>
                    <option value="1" '.($pricelists['status']==1?' selected':'').'>'.$general_status_1.'</option>
                </select>
            </div>
            <div class="form responsive-width-100">
                <label for="name">'.($pricelists_name ?? 'Pricelistname').'</label>
                <input id="name" type="text" name="name" placeholder="'.($pricelists_name ?? '').'" value="'.$pricelists['name'].'" required">
                <input type="hidden" name="rowID" value="'.$pricelists['rowID'].'" readonly>
            </div>
             <div class="form responsive-width-100">
                <label for="">'.($pricelists_currency ?? 'Currency').'</label>
                <select name="currency">';
                        foreach ($supportedCurrencies as $key => $value){
                        $view .='<option value="'.$key.'" '.(($pricelists['currency'] == $key)?' selected':'').'>'.(${'general_currency_'.$key} ?? $value).'</option>';
                    }   
        $view .='</select>
            </div>
            <div class="form responsive-width-100">
                <label for="name">'.($pricelists_start_date ?? 'Start date').'</label>
                <input type="date" name="start_date" placeholder="'.($pricelists_start_date ?? '').'"value="'.$pricelists['start_date'].'" required>
            </div>
            <div class="form responsive-width-100">
                <label for="name">'.($pricelists_end_date?? 'End date').'</label>
                <input type="date" name="end_date" placeholder="'.($pricelists_end_date ?? '').'"value="'.$pricelists['end_date'].'" required>
            </div>
        </div>';

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


$view .= '
<div class="content-block">
    <button class="btn2" onClick="addNewRow()" > + </button>
    <form action="" id="update" method="post"></form>
    <form action="" id="new" method="post"></form>

    <div class="table">
        <table>
            <thead>
                <tr>
                    <th>'.($pricelists_item_status ?? 'Status').'</th>
                    <th>'.($pricelists_item_product_id ?? 'Product ID').'</th>
                    <th>'.($pricelists_item_price ?? 'Price').'</th>
                    <th>'.($pricelists_item_rpp ?? 'RPP').'</th>
                    <th>'.($pricelists_item_price_modifier ?? 'Modifier').'</th>
                    <th>'.$general_created.'</th>
                    <th>'.$general_actions.'</th>
                </tr>
            </thead>
            <tbody id="tableBody">
            ';

            if (empty($pricelists_items)){
                $view .= '
             
                <tr>
                    <td colspan="8" style="text-align:center;">'.($message_no_pricelists ?? 'There are no pricelist items').'</td>
                </tr>';
            }
            else {
                foreach ($pricelists_items as $pricelist_item){

                $view .= '
                <tr><td>
                        <select form="update" name="item['.$pricelist_item['rowID'].'][status]">
                            <option value="0" '.($pricelist_item['status']==0?' selected':'').'>'.$general_status_0.'</option>
                            <option value="1" '.($pricelist_item['status']==1?' selected':'').'>'.$general_status_1.'</option>
                        </select>
                    </td>
                    <td>
                        <select form="update" class="exclusive-select" name="item['.$pricelist_item['rowID'].'][product_id]">';
                        foreach ($products as $product){
                            $view .= '<option value="'.$product['product_id'].'" '.($product['product_id']==$pricelist_item['product_id'] ?' selected':'').'>'.$product['product_id'] .' - '.(${$product['product_name']} ?? $product['product_name']).'</option>
                           ';}  
            $view .= '  </select>
                    </td>
                    <td><input form="update" type="number" min="0" step="0.01" name="item['.$pricelist_item['rowID'].'][price]" placeholder="'.($pricelists_item_price ?? 'Price').'" value="'.$pricelist_item['price'].'"></td>
                    <td><input form="update" type="number" min="0" step="0.01" name="item['.$pricelist_item['rowID'].'][rrp]" placeholder="'.($pricelists_item_rrp ?? 'Recommended Price').'" value="'.$pricelist_item['rrp'].'"></td>
                    <td>
                        <select form="update" name="item['.$pricelist_item['rowID'].'][price_modifier]">';
                        foreach ($supportedModifiers as $key => $value){
                        $view .='<option value="'.$key.'" '.(($pricelist_item['price_modifier'] == $key)?' selected':'').'>'.(${'general_modifier_'.$key} ?? $value).'</option>';
                    }   
           $view .='    </select>
                    </td>
                    <td>'.getRelativeTime($pricelist_item['created']).'</td>
                    <td><input form="update" type="submit" name="update" value="&" class="btn"></td>
                    <input form="update" type="hidden" name="item['.$pricelist_item['rowID'].'][rowID]" value="'.$pricelist_item['rowID'].'" readonly>
                    <input form="update" type="hidden" name="item['.$pricelist_item['rowID'].'][pricelist_ID]" value="'.$pricelist_item['pricelist_ID'].'" readonly>
                </tr>
                </form>';
                }
            }
            
$view .= ' 
            </tbody>
        </table>
        
        <script>
            let rowCounter = 1;
            
            
            function getAllSelectedValues() {
                const selects = document.querySelectorAll(\'.exclusive-select\');
                const selectedValues = [];
                
                selects.forEach(select => {
                    if (select.value) {
                        selectedValues.push(select.value);
                    }
                });
                
                return selectedValues;
            }
          
            // Update all selects to hide options selected elsewhere
            function updateOptions() {
                const selects = document.querySelectorAll(\'.exclusive-select\');
                const selectedValues = getAllSelectedValues();
                
                selects.forEach(select => {
                    const currentValue = select.value;
                    
                    Array.from(select.options).forEach(option => {
                        // Skip the default empty option
                        if (option.value === \'\') return;
                        
                        // Skip the currently selected option for this select
                        if (option.value === currentValue) {
                            option.classList.remove(\'hidden\');
                            return;
                        }
                        
                        // Hide if the option is selected in another dropdown
                        if (selectedValues.includes(option.value)) {
                            option.classList.add(\'hidden\');
                        } else {
                            option.classList.remove(\'hidden\');
                        }
                    });
                });
            }

            // Run on page load to set up initial state
            document.addEventListener(\'DOMContentLoaded\', function() {
                // Initialize all selects
                const selects = document.querySelectorAll(\'.exclusive-select\');
                selects.forEach(select => {
                    select.addEventListener(\'change\', updateOptions);
                });
                
                // Apply initial state
                updateOptions();
            });

         
            const productOptions = [
                    ';foreach ($products as $product){
                        
                $view .= '{
                            value: "'.$product['product_id'].'",
                            text: "'.$product['product_id'].' - '.$product['product_name'].'"
                        },';
                    }
    $view .='  ];
        

            // Function to generate option HTML with appropriate hidden class
            function generateOptionsWithHidden(selectedValues) {
            let optionsHTML = \'\';

            // Manually loop through productOptions instead of using template literals
            for (let i = 0; i < productOptions.length; i++) {
                const option = productOptions[i];
                const isHidden = selectedValues.includes(option.value) ? \'class="hidden"\' : \'\';
                optionsHTML += \'<option value="\' + option.value + \'" \' + isHidden + \'>\' + option.text + \'</option>\';
            }

            return optionsHTML;
            }

            function addNewRow() {

            rowCounter++;
            const tbody = document.getElementById(\'tableBody\');
            const newRow = document.createElement(\'tr\');
            
            // Get all currently selected values before creating the new row
            const selectedValues = getAllSelectedValues();
            
            newRow.innerHTML = `
            <tr><td>
                    <select form="new" name="status">
                        <option value="0">'.$general_status_0.'</option>
                        <option value="1" selected>'.$general_status_1.'</option>
                    </select>
                    </td>
                    <td>
                        <select form="new" class="exclusive-select" name="product_id">
                            ${generateOptionsWithHidden(selectedValues)} 
                        </select>
                    </td>
                    <td><input form="new" type="number" min="0" step="0.01" name="price" placeholder="'.($pricelists_item_price ?? 'Price').'" value=""></td>
                    <td><input form="new" type="number" min="0" step="0.01" name="rrp" placeholder="'.($pricelists_item_rrp ?? 'Recommended Price').'" value=""></td>
                    <td>
                       <select form="new" name="price_modifier">';
                        foreach ($supportedModifiers as $key => $value){
                        $view .='<option value="'.$key.'" '.(($key == 1)?' selected':'').'>'.(${'general_modifier_'.$key} ?? $value).'</option>';
                    }   
           $view .='    </select>
                    </td>
                    <td></td>
                    <td><input form="new" type="submit" name="add" value="+" class="btn"></td>
                    <input form="new" type="hidden" name="rowID" value="" readonly>
                    <input form="new" type="hidden" name="pricelist_ID" value="'.$pricelists['rowID'].'" readonly>
                </tr>  
            `;
            
            tbody.appendChild(newRow);
            }

          
        </script>
        ';
    
$view .= '
    </div>
</div>
';



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