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

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

//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
$output_excel_display ='';
$total_summary = '';

if ($update_allowed === 1){
    if (isset($_POST['excel_data'])) {
        //GET ALL POST DATA
        $excel_data = explode("\n",$_POST['excel_data']) ?? '';
        $trimmedArray = array_map('trim', $excel_data);
        $excel_data_1 = array_filter($trimmedArray, 'strlen');
    
        //Create clean array
        $output_excel = [];
        
        //Totals variables
        $total_rowID = 0;
        $total_not_found = 0;

        $output_excel_display .= '<table>
                                <thead style="text-align: left;">
                                <tr>
                                    <th>'.$equipment_label2.'</th>
                                    <th>'.$product_code.'</th>
                                    <th>'.$product_name.'</th>
                                    <th>'.$product_status.'</th>
                                </tr>
                                </thead>
                                <tbody>';
        

        foreach ($excel_data_1 as $key => $val){
            //GET ROW ID
            $api_url = '/v1/application/serialnumber='.$val.'/get_rowID';
            $responses = ioServer($api_url,'');
            
            //Decode Payload
            if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;}

                //IF rowID is found add to array
                if (isset ($responses->rowID)){
                $output_excel[$val]['rowID'] = $responses->rowID;
                $output_excel[$val]['serialnumber'] = $val;
                $output_excel[$val]['productcode'] = $responses->productcode;
                $output_excel[$val]['productname'] = ${$responses->productname} ?? $responses->productname;
                $output_excel[$val]['order_ref'] = $_POST['order_ref'];
                $output_excel[$val]['status'] = $_POST['status'];
                $output_excel[$val]['salesid'] = $_POST['salesid'];
                $output_excel[$val]['soldto'] = $_POST['soldto'];
                if (!empty($_POST['shipto']) || $_POST['shipto'] !=''){
                    $output_excel[$val]['shipto'] = $_POST['shipto'];
                }
                if (!empty($_POST['location']) || $_POST['location'] !=''){
                    $output_excel[$val]['location'] = $_POST['location'];
                }
                //Count total_rowID
                $total_rowID++;
                }
                else
                {
                    $output_excel_display .= '<tr><td>'.$val.'</td><td></td><td></td><td>'.$mass_update_not_found.'</td></tr>';
                    //Count total_not_found
                    $total_not_found++;
                }

                
        }
        // Update all items of array
        
        foreach ($output_excel as $data_to_update){
            $data = json_encode($data_to_update, JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/equipments', $payload);
            if ($responses === 'NOK'){

            } 
            else {
                $output_excel_display .= '<tr><td>'.$data_to_update['serialnumber'].'</td><td>'.$data_to_update['productcode'].'</td><td>'.(${$data_to_update['productname']} ?? $data_to_update['productname']).'</td><td>'.$mass_update_correct.'</td></tr>';
            }
        }
        $output_excel_display .= '</tbody></table>';

        //Totals
        $total_input =  $total_rowID + $total_not_found;
        $total_summary = '('.$total_rowID.$general_page_of.$total_input.')';

        //CHECK if shipto exists if not empty. Use shipto when soldto not available
        $shipto = (isset($_POST['shipto']) ? $_POST['shipto'] : '');
        $customer = (isset($_POST['soldto']) ? $_POST['soldto'] : $shipto);
        
        $order_header = '<table style="margin-bottom: 15px;width:50%;">
                            <thead>
                                <tr><th style="text-align: left;">'.$tab1.'</th></td>
                                <tr><th></th></td>
                            </thead>
                            <tbody>
                                <tr><td>'.$mass_update_order_ref.'</td><td>'.($_POST['order_ref'] ?? '').'</td></tr>
                                <tr><td>'.$mass_update_order_total.'</td><td>'.$total_rowID.'</td></tr>
                                <tr><td>'.$mass_update_customer.'</td><td>'.$customer.'</td></tr>
                            </tbody>
                        </table>';
    }
}

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 1) {
        $success_msg = $message_eq_1;
    }
    if ($_GET['success_msg'] == 2) {
        $success_msg = $message_eq_2;
    }
    if ($_GET['success_msg'] == 3) {
        $success_msg = $message_eq_3;
    }
}

template_header('Mass update', 'equipment_mass_update', 'view');
$view = '
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.$mass_update_h2.'</h2>
        <a href="index.php?page=equipments" class="btn alt mar-right-2">'.$button_cancel.'</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 .= '<form action="" method="post">
            <div class="content-block-wrapper">
            ';


//BUID UP DROPDOWNS
$partner = json_decode($_SESSION['partnerhierarchy'],true);

$salesid_dropdown = listPartner('salesid',$_SESSION['permission'],$partner['salesid'],'yes');
$soldto_dropdown = listPartner('soldto',$_SESSION['permission'],'','yes');
$shipto_dropdown = listPartner('shipto',$_SESSION['permission'],'','');
$location_dropdown = listPartner('location',$_SESSION['permission'],'','');

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

// SHOW SALESID and SOLDTO ONLY TO ADMIN
if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){
    $view .='<div class="order-detail">
                    <h3>'.$general_salesid.'</h3>
                    <p>'.$salesid_dropdown.'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_soldto.'</h3>
                    <p>'.$soldto_dropdown.'</p>
            </div>';
}
$view .='    <div class="order-detail">
                    <h3>'.$general_shipto.'</h3>
                    <p>'.$shipto_dropdown.'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_location.'</h3>
                    <p>'.$location_dropdown.'</p>
            </div>
                <input type="hidden" name="section" value="">   
        </div>';

$view .= '  <div class="content-block order-details">
                <div class="block-header">
                <i class="fa-solid fa-circle-info"></i></i>'.$mass_update_input.'
                </div>
                <div class="order-detail">
                    <h3><label for="status">'.$equipment_label11.'</label></h3>
                </div>
                <div class="order-detail">    
                    <input id="name" type="text" name="order_ref" required>
                </div>
                <div class="order-detail">
                    <h3><label for="status">'.$equipment_label3.'</label></h3>
                </div>
                <div class="order-detail">    
                    <select id="status" name="status" required>';
if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){
                        $view .= '<option value="0">'.$status0_text .'</option>
                                  <option value="1">'.$status1_text .'</option>
                                  <option value="2">'.$status2_text .'</option>';
}
                        $view .= ' 
                        <option value="3" selected>'.$status3_text .'</option>
                        <option value="4">'.$status4_text .'</option>
                        <option value="5">'.$status5_text .'</option>
                    </select>
                </div>
                <div class="order-detail">
                <h3>'.$paste_excel_h3.'</h3><h3 id="count"><h3>
                </div>
                <div class="order-detail">
                <textarea id="excel_data" name="excel_data" onkeydown="countLines()" style="width:100%;height:150px;" placeholder="'.$paste_excel_1.'&#10;'.$paste_excel_2.'"></textarea>
                </div>
                <input type="submit" id="mass_update_submit" value="'.$button_apply.'" onclick="return confirm(\''.$mass_update_confirm_message.'\')" class="btn">
            ';
$view .='              
            </div>
';

$view .= '</form>';

$view .= '</div></div>';
if ($update_allowed === 1){
    $view .= '<div class="content-block">
                <div class="block-header" style="margin-bottom: 40px;border-bottom: 0px;">
                    <i class="fa-solid fa-bars fa-sm"></i>'.$tab3.' '.$total_summary.'
                    <button class="btn" style="float:inline-end;" onclick="printDiv(\'excel_table\')">Print</button>
                </div>
                   <div class="table order-table" id="excel_table">
                   '.($order_header ?? '' ).'
                   '.$output_excel_display.'
                   </div>
            </div>
    ';
}



//OUTPUT
echo $view;    

echo '
<script>

function countLines(){ 
    let button = document.getElementById("mass_update_submit");
    var text = document.getElementById("excel_data").value.trim(); 
    var lines = text.split(/\r|\r\n|\n/);
    var count = lines.length;
    document.getElementById("count").innerHTML = lines.length;

    function checkIfDuplicateExists(arr) {
        return new Set(arr).size !== arr.length
    }

    if (checkIfDuplicateExists(lines) == true){
        var lines = [...new Set(lines)];
        var count = lines.length;
        document.getElementById("count").innerHTML = lines.length;
        button.disabled = true;
        button.style.background="#e3e4e6";
    } else {
        button.disabled = false;
        button.style.background="#4a79b4";
    }
}
</script>
';

template_footer();

?>