<?php
defined(page_security_key) or exit;

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

//
if ($_GET['id'] !=''){
    $url = 'index.php?page=product&rowID='.$_GET['id'];
} else {
    $url = 'index.php?page=products';
}

// Default input product values
$product = [
    'rowID' => '',
    'productcode' => '',
    'productname' => '',
    'productdescription' => '',
    'softwareversion' => 'v1.0',
    'product_media' =>'',
    'url_slug' => '',
    'full_path' =>'',
    'created' => '',
    'createdby' => $_SESSION['username'],
    'parttype' => 1,
    'price' => '0',
    'salesflag' => 0,
    'quantity' => 1,
    'updated' => '',
    'updatedby' => $_SESSION['username'],
    'product_category' => '',
    'status' => 1,
    'build' => 1,
    'partnerhierarchy' => '',
    'sn' =>'',
    'healthindex' =>'',
    'configurable' =>'',
    'categories' => []
];

//GET ALL CATEGORIES
$api_url = '/v2/categories/';
$categories = ioServer($api_url,'');

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


if (isset($_GET['id'])) {
    // ID param exists, edit an existing product
    //CALL TO API
    $api_url = '/v2/products/rowID='.$_GET['id'];
    $responses = ioServer($api_url,'');
    //Decode Payload
    if (!empty($responses)){$responses = json_decode($responses);}else{$responses = null;}
    
    $product = json_decode(json_encode($responses[0]), true);
    
    //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;}

    //GET PATH OF ASSIGNED MEDIA
    foreach ($media_responses as $media){
        if($media['rowID'] == $product['product_media']){
            $product['full_path'] = $media['full_path'];
        }
    }

    //GET RELATED CATEGORIES    
    $api_url = '/v2/products_categories/product_id='.$_GET['id'];
    $product['categories'] = ioServer($api_url,'');

    //Decode Payload
    if (!empty($product['categories'] )){$product['categories']  = json_decode($product['categories'] ,true);}else{$product['categories']  = null;}

    if ($update_allowed === 1){
        if (isset($_POST['file_upload'])){
            uploadProduct($_POST['productcode']);
        }
        if (isset($_POST['submit'])) {
            
            //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //API call
            $responses = ioServer('/v2/products', $payload);
            if ($responses === 'NOK'){

            } else {
                header('Location: index.php?page=product&rowID='.$_GET['id'].'&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', $payload);
            if ($responses === 'NOK'){

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

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

template_header('Product', 'product', 'manage');

$view ='
<form action="" method="post">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.$product_h2.'</h2>
        <a href="'.$url.'" 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="#">'.$tab4.'</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" '.($product['status']==1?' selected':'').'>'.$prod_status_1 .'</option>
                    <option value="0" '.($product['status']==0?' selected':'').'>'.$prod_status_0 .'</option>
                </select>
                <label for="parttype">'.$product_parttype.'</label>
                <select id="status" name="parttype">
                    <option value="1" '.($product['parttype']==1?' selected':'').'>'.$part_type1.'</option>
                    <option value="2" '.($product['parttype']==2?' selected':'').'>'.$part_type2.'</option>
                    <option value="3" '.($product['parttype']==3?' selected':'').'>'.$part_type3.'</option>
                </select>
                <label for="parttype">'.$product_category.'</label>
                <select id="status" name="product_category">
                    <option value="0" '.($product['product_category']==0?' selected':'').'>'.$product_category0.'</option>
                    <option value="1" '.($product['product_category']==1?' selected':'').'>'.$product_category1.'</option>
                    <option value="2" '.($product['product_category']==2?' selected':'').'>'.$product_category2.'</option>
                    <option value="3" '.($product['product_category']==3?' selected':'').'>'.$product_category3.'</option>
                </select>
                <label for="productcode"><i class="required">*</i>'.$product_code.'</label>
                <input id="name" type="text" name="productcode" placeholder="'.$product_code.'" value="'.$product['productcode'].'" required>
                <label for="productname"><i class="required">*</i>'.$product_name.'</label>
                <input id="name" type="text" name="productname" placeholder="'.$product_name.'" value="'.$product['productname'].'" required>
                <label for="productname"><i class="required">*</i>'.($product_slug ?? 'Product_slug').'</label>
                <input id="name" type="text" name="url_slug" placeholder="'.($product_slug ?? 'Product_slug').'" value="'.$product['url_slug'].'">
                <label for="productdescription">'.$product_description.'</label>
                <textarea id="description" name="productdescription" placeholder="'.$product_description.'">'.$product['productdescription'].'</textarea>
                <label for="softwareversion">'.$product_software.'</label>
                <input id="name" type="text" name="softwareversion" placeholder="'.$product_software.'" value="'.$product['softwareversion'].'">
                <label for="price"><i class="required">*</i> '.($product_quantity ?? 'Quantity').' </label>
                <input id="price" type="number" name="quantity" placeholder="'.($product_quantity ?? 'Quantity').'" min="0" step="1" value="'.$product['quantity'].'"> 
                <input type="hidden" name="rowID" value="'.$product['rowID'].'">
                <label for="category">Categories</label>
                <div class="multiselect" data-name="categories[]">';
                    foreach ($product['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="category" placeholder="Categories">
                    <div class="list">';
                    foreach ($categories as $cat) {
                       $view .= ' <span data-value="'.$cat['rowID'].'">'.$cat['name'].'</span>';
                    }
$view .= '          </div>
                </div>
                <input id="source_'.$product['rowID'].'" type="hidden" name="product_media" value="'.$product['product_media'].'">
                <img id="image_'.$product['rowID'].'" src="'.$product['full_path'].'" alt="" style="display: block; max-width: 75px;">
                <button type="button" class="btn" id="openSelectorBtn" onclick="setSourceID(\''.$product['rowID'].'\'), openDialog(\'image_'.$product['rowID'].'\')">'.($button_assign_image ?? 'Assign Image').'</button>   
            </div>
        </div>';

$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">
                <label for="serialized">'.($product_configurable ?? 'Configurable').'</label>
                <select id="status" name="configurable">
                    <option value="1" '.($product['configurable']==1?' selected':'').'>'.$enabled.'</option>
                    <option value="0" '.($product['configurable']==0?' selected':'').'>'.$disabled.'</option>
                </select>
                <label for="serialized">'.$product_serialized.'</label>
                <select id="status" name="sn">
                    <option value="1" '.($product['sn']==1?' selected':'').'>'.$enabled.'</option>
                    <option value="0" '.($product['sn']==0?' selected':'').'>'.$disabled.'</option>
                </select>
                <label for="build">'.$product_build.'</label>
                <select id="status" name="build">
                    <option value="1" '.($product['build']==1?' selected':'').'>'.$enabled.'</option>
                    <option value="0" '.($product['build']==0?' selected':'').'>'.$disabled.'</option>
                </select>
                <label for="sales">'.$product_sales.'</label>
                <select id="status" name="salesflag">
                    <option value="1" '.($product['salesflag']==1?' selected':'').'>'.$enabled.'</option>
                    <option value="0" '.($product['salesflag']==0?' selected':'').'>'.$disabled.'</option>
                </select>
                <label for="sales">'.$view_asset_data_ranking.'</label>
                <select id="status" name="healthindex">
                    <option value="1" '.($product['healthindex']==1?' selected':'').'>'.$enabled.'</option>
                    <option value="0" '.($product['healthindex']==0?' selected':'').'>'.$disabled.'</option>
                </select>
            </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="'.$product['created'].'" readonly>
            <label for="productcode">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$product['createdby'].'" readonly>
            <label for="productcode">'.$general_updated.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updated.'" value="'.$product['updated'].'" readonly>
            <label for="productcode">'.$general_updatedby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updatedby.'" value="'.$product['updatedby'].'" readonly>
        </div>
    </div>';
$view .= '</form>';

$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;">';

            if ($media_responses && is_array($media_responses)){
                foreach ($media_responses as $media_response){
                    $view .= '
                            <img src="'.$media_response['full_path'].'" id="'.$media_response['rowID'].'" title="'.$media_response['title'].'" alt="'.$media_response['title'].'" 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 .= '<script>
            //POPUP FOR IMAGE SELECTION
            const dialog = document.getElementById(\'imageSelector\');
            image_source_id = 0;
            //const openButton = document.getElementById(\'openSelectorBtn\');

            function setSourceID(sourceid){
                image_source_id = "source_"+sourceid;
                image_source_src = "image_"+sourceid;
            }

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

            function selectImage(id,src) {

                if (image_source_id != 0){
                    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>';

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