<?php
defined(page_security_key) or exit;

$page = 'products_attributes_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
$products_attributes = [
    'rowID' => '',
    'group_status' => '',
    'group_name' => '',
    'group_mandatory' => '',
    'group_type' => '',
    'created' => '',
    'createdby' => '',
    'updated' => '',
    'updatedby' => '',
    'accounthierarchy' => ''
];

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

    //CALL TO API FOR RELATED TRANSLATIONS
    $api_url = '/v2/products_attributes_items/media=all&group_id='.$_GET['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;}

    //CALL TO API
    $api_url = '/v2/media/list=product_image';
    $media_responses = ioServer($api_url,'');

    //Decode Payload
    if (!empty($media_responses)){$media_responses = json_decode($media_responses,true);}else{$media_responses = 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_attributes', $payload);
           
            if ($responses === 'NOK'){

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

        if (isset($_POST['add'])) {
      
            //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);

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

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

            } else {
                header('Location: index.php?page=products_attributes_manage&rowID='.$_GET['rowID'].'');
                exit;
            }
        
        }

        if (isset($_POST['update']) && isset($_POST['attributes'])) {
          
            //RUN through all POST items
            foreach ($_POST['attributes'] as $attr){
      
                //GET ALL POST DATA
                $payload = json_encode($attr, JSON_UNESCAPED_UNICODE);
                var_dump($payload);
                //API call
                $responses = ioServer('/v2/products_attributes_items', $payload);

                if ($responses === 'NOK'){
                    //NOT correct exit procedure
                    exit;
                }
            }
            header('Location: index.php?page=products_attributes_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/products_attributes', $payload);
            // Redirect and delete product
            if ($responses === 'NOK'){

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

        } else {
            //GET ROWID OF CREATED ITEM
                $group_rowID = json_decode($responses,true);
                header('Location: index.php?page=products_attributes_manage&rowID='.$group_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('Products attributes', 'products_attributes', '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">'.($products_attributes_h2 ?? '').'</h2>
        <a href="index.php?page=products_attributes" 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 variable?\')">';
}
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="">'.($products_attributes_group_status ?? 'Status').'</label>
                <select name="group_status">
                    <option value="0" '.($products_attributes['group_status']==0?' selected':'').'>'.$general_status_0.'</option>
                    <option value="1" '.($products_attributes['group_status']==1?' selected':'').'>'.$general_status_1.'</option>
                </select>
            </div>
            <div class="form responsive-width-100">
                <label for="group_name">'.($products_attributes_group_name ?? 'Groupname').'</label>
                <input id="group_name" type="text" name="group_name" placeholder="'.($products_attributes_group_name ?? '').'" value="'.$products_attributes['group_name'].'" required">
                <input type="hidden" name="rowID" value="'.$products_attributes['rowID'].'" readonly>
            </div>
              <div class="form responsive-width-100">
                <label for="group_name_internal">'.($products_attributes_group_name_internal ?? 'Internal').'</label>
                <input id="group_name_internal" type="text" name="group_name_internal" placeholder="'.($products_attributes_group_name_internal ?? '').'" value="'.$products_attributes['group_name_internal'].'" required">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($products_attributes_group_type ?? 'Type').'</label>
                <select name="group_type">
                    <option value="0" '.($products_attributes['group_type']==0?' selected':'').'>'.($general_form_0 ?? 'Radiobutton').'</option>
                    <option value="1" '.($products_attributes['group_type']==1?' selected':'').'>'.($general_form_1 ?? 'Checkbox').'</option>
                    <option value="2" '.($products_attributes['group_type']==2?' selected':'').'>'.($general_form_2 ?? 'Dropdown').'</option>
                </select>
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($products_attributes_group_mandatory ?? 'Mandatory').'</label>
                <select name="group_mandatory">
                    <option value="0" '.($products_attributes['group_mandatory']==0?' selected':'').'>'.$general_no.'</option>
                    <option value="1" '.($products_attributes['group_mandatory']==1?' selected':'').'>'.$general_yes.'</option>
                </select>
            </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($products_attributes['created']).'" readonly>
            <label for="">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$products_attributes['createdby'].'" readonly>
            <label for="productcode">'.$general_updated.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updated.'" value="'.getRelativeTime($products_attributes['updated']).'" readonly>
            <label for="productcode">'.$general_updatedby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updatedby.'" value="'.$products_attributes['updatedby'].'" readonly>
        </div>
    </div>';
$view .= '</form>';


$view .= '
<div class="content-block">
    <h2 class="responsive-width-100">'.($products_attributes_group_items ?? 'Groupitems').'  <button class="btn2" onClick="addNewRow()" > + </button>     <input form="update" class="btn2" type="submit" name="update" value="Save" class="btn"></h2>

    <form action="" id="update" method="post"></form>
    <form action="" id="new" method="post"></form>

    <div class="table">
        <table>
            <thead>
                <tr>
                    <th>'.($products_attributes_item_status ?? 'status').'</th>
                    <th>'.($products_attributes_item_name ?? 'name').'</th>
                    <th>'.($products_attributes_item_quantity ?? 'quantity').'</th>
                    <th>'.($products_attributes_item_position ?? 'position').'</th>
                    <th>'.($products_attributes_item_media ?? 'media').'</th>
                    <th>'.($products_attributes_alternative_media ?? 'alternative').'</th>
                    <th>'.$general_created.'</th>
                    <th>'.$general_actions.'</th>
                </tr>
            </thead>
            <tbody id="tableBody">
            ';

            if (empty($products_attributes_items)){
                $view .= '
             
                <tr>
                    <td colspan="8" style="text-align:center;">'.($message_no_products_attributess ?? '').'</td>
                </tr>';
            }
            else {
                foreach ($products_attributes_items as $items){
                $view .= '
                
                <tr>  
                    <td>    
                    <select form="update" name="attributes['.$items['rowID'].'][item_status]">
                        <option value="0" '.($items['item_status']==0?' selected':'').'>'.$general_status_0.'</option>
                        <option value="1" '.($items['item_status']==1?' selected':'').'>'.$general_status_1.'</option>
                    </select>
                    </td>
                    <td><input form="update" type="text" name="attributes['.$items['rowID'].'][item_name]" placeholder="'.($products_attributes_item_name ?? '').'" value="'.$items['item_name'].'"></td>
                    <td><input form="update" type="number" name="attributes['.$items['rowID'].'][item_quantity]" placeholder="'.($products_attributes_item_quantity ?? '').'" value="'.$items['item_quantity'].'"></td>
                    <td><input form="update" type="number" name="attributes['.$items['rowID'].'][item_position]" placeholder="'.($products_attributes_item_position ?? '').'" value="'.$items['item_position'].'"></td>
                    <td><input form="update" id="source_'.$items['rowID'].'" type="hidden" name="attributes['.$items['rowID'].'][item_media]" value="'.$items['item_media'].'">
                        <img id="image_'.$items['rowID'].'" src="'.$items['full_path'].'" alt="" style="display: block; max-width: 75px;">    
                    </td>
                    <td><input form="update" id="source_alt_'.$items['rowID'].'" type="hidden" name="attributes['.$items['rowID'].'][alternative_media]" value="'.$items['alternative_media'].'">
                        <img id="alt_'.$items['rowID'].'" src="'.$items['alternative_media_full_path'].'" alt="" style="display: block; max-width: 75px;">    
                    </td>
                    <td>'.getRelativeTime($items['created']).'</td>
                    <td>
                        <button type="button" class="btn" id="openSelectorBtn" onclick="setSourceID(\''.$items['rowID'].'\'), openDialog(\'image_'.$items['rowID'].'\')">'.($button_assign_image ?? 'Media').'</button>
                        <button type="button" class="btn" id="openSelectorBtn" onclick="setSourceID(\'alt_'.$items['rowID'].'\'), openDialog(\'alt_'.$items['rowID'].'\')">'.($button_assign_image ?? 'Alt').'</button>
                    </td>
                    <input form="update" type="hidden" name="attributes['.$items['rowID'].'][rowID]" value="'.$items['rowID'].'" readonly>
                    <input form="update" type="hidden" name="attributes['.$items['rowID'].'][group_id]" value="'.$products_attributes['rowID'].'" readonly>
                </tr>
                ';
                }
                
                $view .= '<!-- Image Selector Dialog -->
                <dialog id="imageSelector" style="padding: 20px; max-width: 800px;">
                    <h3>Select an Image</h3>
                    <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; margin: 20px 0;">';

                    foreach ($media_responses as $media_response){
                        $view .= '
                                <img src="'.$media_response['full_path'].'" alt="'.$media_response['title'].'" title="'.$media_response['title'].'" id="'.$media_response['rowID'].'" style="width: 100%; cursor: pointer; border: 2px solid transparent;" onmouseover="this.style.border=\'2px solid #4CAF50\'" onmouseout="this.style.border=\'2px solid transparent\'" onclick="selectImage(this.id,this.src)">
                        ';
                    }
                $view .= '</div>
                    <button onclick="closeImageSelector()">Close</button>
                </dialog>
                ';
            }
$view .= ' 
            </tbody>
        </table>
        
        <script>
            let rowCounter = 1;

            function addNewRow() {
            rowCounter++;
            const tbody = document.getElementById(\'tableBody\');
            const newRow = document.createElement(\'tr\');
            
            newRow.innerHTML = `
                    <select form="new" name="item_status">
                        <option value="0">'.$general_status_0.'</option>
                        <option value="1" selected>'.$general_status_1.'</option>
                    </select>
                    </td>
                    <td><input form="new" type="text" name="item_name" placeholder="'.($products_attributes_item_name ?? '').'" value=""></td>
                    <td><input form="new" type="number" name="item_quantity" placeholder="'.($products_attributes_item_quantity ?? '').'" min="1" value="1"></td>
                    <td><input form="new" type="number" name="item_position" placeholder="'.($products_attributes_item_position ?? '').'" value=""></td>
                    <td>
                        <input form="new" type="hidden" id="selectedImage" name="item_media" value="">
                        <img id="previewImage" src="" alt="Selected image" style="display: none; max-width: 200px;">
                    </td>
                    <td><button type="button" class="btn" id="openSelectorBtn" onclick="openDialog()">'.($button_assign_image ?? 'Assign Image').'</button></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="group_id" value="'.$products_attributes['rowID'].'" readonly>
            `;
            
            tbody.appendChild(newRow);
            }

            //POPUP FOR IMAGE SELECTION
            const dialog = document.getElementById(\'imageSelector\');
            image_source_id = 0;
            //const openButton = document.getElementById(\'openSelectorBtn\');

            function setSourceID(sourceid){
                if(sourceid.substring(0,3) == "alt"){
                    image_source_id = "source_"+sourceid;
                    image_source_src = sourceid;
                } else {
                    image_source_id = "source_"+sourceid;
                    image_source_src = "image_"+sourceid;
                }
            }

            function openDialog(){
                dialog.showModal();
            }

            function selectImage(id,src) {

                if (image_source_id != 0){
                    console.log(image_source_id);
                    const selectedImageInput = document.getElementById(image_source_id);   
                    const previewImage = document.getElementById(image_source_src);
                    
                    selectedImageInput.value = id;
                    previewImage.src = src;
          
                }
                else {
                    const selectedImageInput = document.getElementById(\'selectedImage\');
                    const previewImage = document.getElementById(\'previewImage\');

                    selectedImageInput.value = id;
                    previewImage.src = src;
                    previewImage.style.display = \'block\';
                }         
               
                dialog.close();
            }

            function closeImageSelector() {
                dialog.close();
            }

        </script>
    </div>
</div>
';



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