<?php
session_start();
$where 					= " WHERE 1=1  ";
$next_page_condition 	= "";
$form_action 	= "insert";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
} 
####################################### ARCHIVING/UNARCHIVING CUSTOMER #######################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'archive'){	
	foreach($_REQUEST["warehouse_ids"] as $customer_id){
		mysqli_query($conn,"UPDATE warehouses SET is_archive = '1' WHERE id = '$customer_id' ");
	}
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
	$query_string = str_ireplace("action=archive", "", $query_string);
	$query_string = "&".$query_string;
	
	$_SESSION['info_message'] = "warehouse(s) archived sucessfully";
	header("Location: index?page=view_warehouse$query_string");
	exit();
}
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'unarchive'){	
	foreach($_REQUEST["warehouse_ids"] as $customer_id){
		mysqli_query($conn,"UPDATE warehouses SET is_archive = '0' WHERE id = '$customer_id' ");
	}
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
	$query_string = str_ireplace("action=unarchive", "", $query_string);
	$query_string = "&".$query_string;
	
	$_SESSION['info_message'] = "warehouse(s) unarchived sucessfully";
	header("Location: index?page=view_warehouse$query_string");
	exit();
}
################################################## END ARCHIVING/UNARCHIVING ORGANISATION ###################################
###########################################  STRAT FILTER CONITIONS    #####################################
$search 	= isset($_REQUEST['search']) ? $_REQUEST['search'] : "";
if($search) {
	$where	.= " AND name LIKE '%$search%' ";
	$next_page_condition.="&search=$search";
}

$product_template_id 	= isset($_REQUEST['product_template_id']) ? $_REQUEST['product_template_id'] : "";
if($product_template_id) {
    $where	.= " AND product_template_id = '$product_template_id' ";
    $next_page_condition.="&product_template_id=$product_template_id";
}

$is_archive 	= isset($_REQUEST['is_archive']) ? $_REQUEST['is_archive'] : "";
if($is_archive) {	
    $where	.= " AND is_archive = '$is_archive' ";
    $next_page_condition.="&is_archive=$is_archive";
}else{
	$where	.= "AND product_template_id ='".$_REQUEST['pro_temp_id']."' ";
}
/*$show_archive 	= isset($_REQUEST['show_archive']) ? $_REQUEST['show_archive'] : "";
if(!($show_archive)) {
	$archive_status_id = $config->archive_status_id;
    if(!$job_id){
		$where	.= " AND prospect_status != '$archive_status_id' ";
		$next_page_condition.="&show_archive=$show_archive";
	}
}else{
		$archive_status_id = $config->archive_status_id;
		$where	.= " AND prospect_status = '$archive_status_id' ";
		$next_page_condition.="&show_archive=$show_archive";
}*/
$from_date = isset($_REQUEST['from_date']) ? utility::setFormatedDate($_REQUEST['from_date']) : "";
$to_date = isset($_REQUEST['to_date']) ? utility::setFormatedDate($_REQUEST['to_date']) : "";
if($from_date && $to_date){
	$where .= " AND created_on BETWEEN '$from_date 00:00:00' and '$to_date 23:59:59' ";
	$next_page_condition.="&from_date=".$_REQUEST['from_date']."&to_date=".$_REQUEST['to_date']." ";
}else if($from_date){
	$where.= " AND created_on >= '$from_date' ";
	$next_page_condition.="&from_date=".$_REQUEST['from_date'];
}else if($to_date){
	$where.= " AND created_on <= '$to_date' ";
	$next_page_condition.="&to_date=".$_REQUEST['to_date'];
}

$admin_id_search 	= isset($_REQUEST['admin_id_search']) ? $_REQUEST['admin_id_search'] : "";
if($_REQUEST['admin_id_search']){
	$consultant_ids = "";
	$sql1 = "select job_id FROM job_admin_mapping where admin_id = '".$admin_id_search."' ";
	$rs1 =  mysqli_query($conn,$sql1);
	if(mysqli_num_rows($rs1) > 0){
		while($row1 = mysqli_fetch_assoc($rs1)){
			$consultant_ids .= $row1["job_id"].",";
		}
		$consultant_ids = substr($consultant_ids,0,-1);
	}
	$where 	.= " AND id IN($consultant_ids) ";
	$next_page_condition.="&admin_id_search=".$_REQUEST['admin_id_search'];
}
###########################################  	END  FILTER CONITIONS 	#####################################
$admin_in = "";
$admin_in_ids = "";
if($show_only_my_things  == 1){
	$sql1 = "select job_id FROM job_admin_mapping where admin_id = '".$_SESSION['user_id']."' ";
	$rs1 =  mysqli_query($conn,$sql1);
	if(mysqli_num_rows($rs1) > 0){
		while($row1 = mysqli_fetch_assoc($rs1)){
			$admin_in_ids .= $row1["job_id"].",";
		}
		$admin_in_ids = substr($admin_in_ids,0,-1);
	}
	
	if($admin_in_ids){
		$admin_in = " AND id IN($admin_in_ids)";
	}
	
	$where.=$admin_in;
}
###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index?page=view_pro_template"; // this is file name which is used during paging  , included at the bottom of the page
$table_name		= "product_main";
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Product Management";
include("../admin/paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################
$query = "SELECT * FROM $table_name $where ORDER BY id DESC LIMIT $eu, $limit";
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_organisations = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
#################################   DELETE    #########################################
// when we click on delete this area of php code will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete')
{   $id =$_REQUEST['id'];
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	$product_group_id = utility::getTableFieldById("product_name","id","pro_id",$id);
	mysqli_query($conn,"DELETE FROM product_name WHERE pro_id = '".$_REQUEST['id']."' ");
	mysqli_query($conn,"DELETE FROM product_link WHERE parent_id = '".$product_group_id."' ");
	
	$_SESSION['info_message_del'] = "Product deleted sucessfully";
	header("location: ?page=view_product&pro_temp_id=".$_REQUEST['pro_temp_id'].$next_page_condition.$paging);
	exit();
}
#################################  END DELETE    #########################################
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ To dublicate @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//
if(isset($_REQUEST['action']) && $_REQUEST['action']=='duplicate'){
	include('duplicate.inc.php');
}
//@@@@@@@ Dublicate End @@@@@@@@@@@@@@@//
###########################################  End dublicate  #####################################
#################################  Export CSV    #########################################
if(isset($_REQUEST['action']) && $_REQUEST['action']=='export_job_details'){
  include("export_organisation_details_to_csv.inc.php");
}
###########################################  End Export  #####################################

################################################# END INSERT #################################################

?>

<style>


</style>
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-12">
                <h1 class="m-0"><?=$page_header;?></h1>
            </div>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
</div>
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="">
                    <!----------------------- End Message ------------------------------->
                    <div class="card">
					<!----------------------- Message ------------------------------->
					
						<?php if(isset($_SESSION['info_message'])) { ?>
							<script>
								$(document).ready(function(){
									Toastify({
										text: "<?php echo $_SESSION['info_message']; ?>",duration: 4000,close: true,gravity: "top",position: 'right',backgroundColor: "#28a745",style: {borderBottom: "3px solid white",},
									}).showToast();
									<?php unset($_SESSION['info_message']); ?>
								});
							</script>
						<?}?>
						<?php if(isset($_SESSION['info_message_del'])) { ?>
						  <script>
							$(document).ready(function(){
								Toastify({
									text: "<?php echo $_SESSION['info_message_del']; ?>",duration: 4000, close: true,gravity: "top",position: 'right', backgroundColor: "#E24D4C",style: {borderBottom: "3px solid white"},
								}).showToast();
								<?php unset($_SESSION['info_message_del']); ?>
							});
						 </script>
					  <?} ?>
                        <div class="card-body">
                            <!-- search form -->
                            <?php include_once('product_management_search_options.inc.php');
							
							   $path="";
								echo $path='<b><a href="index?page=view_pro_template" class="text-primary">Product Template List</a> -> <a href="index?page=view_pro_attr&pro_temp_id='.$_REQUEST["pro_temp_id"].'"class="text-primary">Product Template Attributes</a> -></b>';
							?><br>
                            <!-- /.search form -->
                            Total No. of Products <?=$total_no_of_organisations;?>
                            <div class='hide' style="float:right;margin-bottom:4px;">Export warehouse Details
                                &nbsp;&nbsp;<a
                                    href="index?page=view&action=export_job_details<?=$next_page_condition;?>"><i
                                        class="fa fa-download" style="font-size:20px;"></i></a></div>

                            <form action="index?page=add_product&pro_temp_id=<?=$_REQUEST['pro_temp_id'];?>" method="post" name="form1" id="form1">
                                <div class="card-footer">
                                    <button type="submit" name="add" class="btn btn-primary">Add Product</button>
                                    <? if(!$is_archive){ ?>
                                    <button type="button" name="archive_warehouse" id="archive_warehouse"
                                        class="btn btn-warning pull-right hide">Archive</button>
                                    <? }else{ ?>
                                    <button type="button" name="unarchive_warehouse" id="unarchive_warehouse"
                                        class="btn btn-warning pull-right">Unarchive</button>
                                    <? } ?>
                                </div>
                                <? if($result>0){?>
                                <div class="table-responsive">
                                    <table id="example1" class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
												<th class="">Part Number</th>
                                                <th>Product </th>
                                               
                                                <th class="">Template</th>
                                                <th>Edit</th>
                                                <th>Delete</th>
                                                <th class="no-sort hide" style="text-align:center;">
                                                    <div class="icheck-primary d-inline">
                                                        <input type="checkbox" name="check_all" id="check_all">
                                                        <label for="check_all"></label>
                                                    </div>
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?
												while($row =mysqli_fetch_array($sql)){ 
												$row=utility::validate_crypt_data($row);
											?>
                                            <tr class="activity<?php echo $status;?>" alt="<?php echo $bg_color_key;?>"
                                                style="background-color:<?=$bg_color;?>;">
                                               
												<td class="hide"><?php echo $gsi->getProductTempateById($row['product_template_id']);?></td>
												
												<td class=" "> <a href='#' data-toggle='modal' class="p-1 text-primary" data-target='#ShowModal1' id="" alt="<?=$row['part_number']?>"><?=$p_name = utility::getTableFieldById("product_name","group_number","id",$row['part_number']);?></a></td>
												<td><a href="index?page=view_product_details&from=view_product&pro_temp_id=<?php echo $_REQUEST['pro_temp_id']?>&id=<?php echo $row['id'].$next_page_condition.$paging;?>"class="text-primary"><?php echo ucfirst($row['name']);?></a></td>
												<td class="text-center hide"><?=$p_name = utility::getTableFieldById("product_name","group_number","id",$row['part_number']);?></td>
												<td class="text-center">
													
													<?php 
														if(isset($row['product_template_id']) && $row['product_template_id'] !=""){
															echo $gsi->getProductTempateById($row['product_template_id']); 
													}?>
                                                </td>
												
                                                <td class=""><a href="index?page=add_product&action=edit&id=<?php echo $row['id']?>&pro_temp_id=<?php echo $row['product_template_id'].$next_page_condition.$paging;?>"><i class="fa fa-fw fa-edit text-primary"></i> </a></td>
                                                <td><a href="index?page=view_product&action=delete&id=<?php echo $row['id']?>&pro_temp_id=<?php echo $row['product_template_id'].$next_page_condition.$paging; ?>"onclick=" javascript:return confirm('Are you sure! You want to delete');"><i class="fa fa-fw fa-trash text-danger"></i> </a></td>
                                                <td align="center" class='hide'>
                                                    <div class="icheck-primary d-inline">
                                                        <input class="checkbox" type="checkbox"
                                                            name="warehouse_ids[<?php echo $row['id']?>]"
                                                            value="<?php echo $row['id']?>" id="primary">
                                                        <label for="primary"></label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <? } ?>

                                        </tbody>
                                    </table>
                                </div>
                                <? }else{ ?>
                                No Products found...
                                <? } ?>
                                <div class="box-footer clearfix">
                                    <!-- Paging starts here  -->
                                    <? 
									$next_page_condition .="&page=view_warehouse";
									include("paging/paging_row.inc.php") 
								?>
                                    <!-- Paging ends starts here  -->
                                </div>
								<div class="card-footer hide">
									<button type="submit" name="add" class="btn btn-primary ms-2">Add Product </button>
								</div>
                        </div>
                        
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<div class="modal fade" id="ShowModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable" role="document" style="width:75%; max-width:80%">
	<div class="modal-content">
	  <div class="modal-header">
		<h5 class="modal-title" id="exampleModalScrollableTitle" style="float:left">Group Tree</h5>
		<button type="button" class="close" data-dismiss="modal" aria-label="Close">
		  <span aria-hidden="true">&times;</span>
		</button>
	  </div>
	  <div class="modal-body">
		<!--<h5 class="modal-title" id="exampleModalScrollableTitle">Q->Quantity, C->Cost, LC->Labour Cost, TC->Total Cost, TLC->Total Labour Cost</h5>-->
		<div id="group_tree1" style="">
		</div>
	  </div>
	  <div class="modal-footer">
		<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
		
	  </div>
	</div>
  </div>
</div>
<script type="text/javascript">
$(function() {
	$('#ShowModal1').on('show.bs.modal', function (e) {
	  create_group_tree1(e.relatedTarget.attributes.alt.value);
   })
	
   function create_group_tree1(id) {
    $.ajax({
        url: site_url + "/modules/daynmic_product_management/index.php?page=ajax_actions&action=get_group_list&id=" + id,
        method: "POST",
        dataType: "json",
        success: function(data) {
            $('#group_tree1').treeview({
                data: data,
                levels: 1,
                collapseIcon: "fa fa-angle-down",
                expandIcon: "fa fa-angle-right",
                nodeIcon: "fa fa-share-alt-square",
                showBorder: false,
                enableLinks: true,
                preventUnselect: true,
                showTags: true
            });
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Something went wrong");
        }
    });
	}
	
});
</script>