<?php
session_start();
$where 					= " WHERE 1=1 ";
$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
} 
$item_id = utility::app_crypt($_REQUEST['item_id'],'d');
if($_REQUEST['id'] != $item_id){
	//die("Invaild URL");
}
$restricted_groups = [13, 14, 15, 16, 17, 19];
$can_view = !in_array($_SESSION['admin_group_id'], $restricted_groups);
###########################################  STRAT FILTER CONDITIONS    #####################################

/**
 * Walks the bom table and returns every sub_part_id used anywhere
 * beneath $main_product_id, at any depth. Guards against cyclic BOMs.
 */
/**
 * Walks the bom table upward and returns every main_product_id that
 * uses $sub_part_id as a component, at any level (direct or nested).
 * E.g. if A contains B, and B contains C, searching for C returns [B, A].
 * Guards against cyclic BOMs.
 */
function get_all_bom_parent_ids($conn, $sub_part_id) {
	$found   = array();
	$visited = array();
	$stack   = array($sub_part_id);

	while (count($stack) > 0) {
		$current_id = array_shift($stack);

		if (in_array($current_id, $visited)) {
			continue;
		}
		$visited[] = $current_id;

		$current_id_esc = mysqli_real_escape_string($conn, $current_id);
		$res = mysqli_query($conn, "SELECT main_product_id FROM bom WHERE sub_part_id = '$current_id_esc'");

		while ($row = mysqli_fetch_assoc($res)) {
			$parent_id = $row['main_product_id'];
			if (!in_array($parent_id, $found)) {
				$found[] = $parent_id;
			}
			$stack[] = $parent_id;
		}
	}

	return $found;
}

###########################################  STRAT FILTER CONITIONS    #####################################
###########################################  STRAT FILTER CONDITIONS    #####################################
 $part_number_input          = isset($_REQUEST['part_number']) ? trim($_REQUEST['part_number']) : "";
 $product_description_input  = isset($_REQUEST['product_description']) ? trim($_REQUEST['product_description']) : "";
 $part_id_input               = isset($_REQUEST['part_id']) ? trim($_REQUEST['part_id']) : "";

$bom_match_count = null;

if ($part_number_input !== "") {
	$part_number_esc = mysqli_real_escape_string($conn, $part_number_input);
	$where .= " AND im.part_number LIKE '%$part_number_esc%' ";
	$next_page_condition .= "&part_number=" . urlencode($part_number_input);
}

if ($product_description_input !== "") {
	$product_description_esc = mysqli_real_escape_string($conn, $product_description_input);
	$where .= " AND im.product_description LIKE '%$product_description_esc%' ";
	$next_page_condition .= "&product_description=" . urlencode($product_description_input);
}

if ($part_id_input !== "") {
	//echo "<br>";
	 $part_id_esc = mysqli_real_escape_string($conn, $part_id_input);

	$component_ids = get_all_bom_parent_ids($conn, $part_id_esc);
//print_r($component_ids);
	if (count($component_ids) > 0) {
		$component_ids_safe = array_map('intval', $component_ids);
		$where .= " AND im.id IN (" . implode(",", $component_ids_safe) . ") ";
		$bom_match_count = count($component_ids_safe);
	} else {
		$where .= " AND 1 = 0 ";
		$bom_match_count = 0;
	}

	$next_page_condition .= "&part_id=" . urlencode($part_id_input);
}
###########################################  	END  FILTER CONDITIONS 	#####################################
###########################################  	END  FILTER CONITIONS 	#####################################
###########################################  	END  FILTER CONITIONS 	#####################################
###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$table_name		= "item_management";
$paging_table_name	= $table_name;
$paging_query		= $where;
 $join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Item Management";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################
//$query = "SELECT * FROM $table_name $where ORDER BY id DESC LIMIT $eu, $limit";
//echo "<br>";
 $query = "
    SELECT im.*, IFNULL(inv.quantity_in_stock,0) AS quantity_in_stock
    FROM item_management im
    LEFT JOIN inventory inv ON inv.item_id = im.id
    $where
    ORDER BY im.id DESC
    LIMIT $eu, $limit
";
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_records = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
#################################   dublicateBOM    #########################################

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'dublicateBOM') {

    $originalId = intval($_POST['original_id']);
    $newPartNumber = mysqli_real_escape_string($conn, $_POST['part_number']);
    $newPartDescription = mysqli_real_escape_string($conn, $_POST['part_description']);

    $itemQuery = "
        INSERT INTO item_management (
            part_number, part_number_id, product_description, part_status, usual_source,
            stock_uom, drawing_number, product_group, man_lead_time, standard_cost_ebq, pack_quantity, 
            pack_weight, pallet_quantity, standard_cost, nominal_code_sales, nominal_code_purchase, 
            date_time_amended, date_time_amended_utc, packing_code, recycle_code, drawing_issue, uph, 
            cnc_program_no, customer_code, master_sample_location, tool_location, checking_fixture_location, 
            type, spec, grade, format, density, mpe, length_mm, width_mm, thickness, mks, gross, net, 
            scrap_percent, uom, price_uom, unit_cost, scrap_value, type_2, created_by, created_on, updated_by, updated_on
        )
        SELECT 
            '$newPartNumber', part_number_id, '$newPartDescription', part_status, usual_source,
            stock_uom, drawing_number, product_group, man_lead_time, standard_cost_ebq, pack_quantity, 
            pack_weight, pallet_quantity, standard_cost, nominal_code_sales, nominal_code_purchase, 
            date_time_amended, date_time_amended_utc, packing_code, recycle_code, drawing_issue, uph, 
            cnc_program_no, customer_code, master_sample_location, tool_location, checking_fixture_location, 
            type, spec, grade, format, density, mpe, length_mm, width_mm, thickness, mks, gross, net, 
            scrap_percent, uom, price_uom, unit_cost, scrap_value, type_2, created_by, NOW(), updated_by, NOW()
        FROM item_management
        WHERE id = $originalId
    ";
    if (mysqli_query($conn, $itemQuery)) {
        $newItemId = mysqli_insert_id($conn);

        $productQuery = "
            INSERT INTO product_name (
                pro_id, group_number, group_code, group_name, cost, labour_cost, labour_hours, qty, unit, 
                machine_cost, machine_hours
            )
            SELECT 
                '$newItemId', '$newPartNumber', group_code, '$newPartDescription', cost, labour_cost, labour_hours, 
                qty, unit, machine_cost, machine_hours
            FROM product_name
            WHERE pro_id = $originalId
        ";
        if (mysqli_query($conn, $productQuery)) {
            $newProductId = mysqli_insert_id($conn);

            mysqli_query($conn, "UPDATE item_management SET part_number_id = '$newProductId' WHERE id = '$newItemId'");

            // Recursive BOM Duplication
            duplicateBom($conn, $originalId, $newItemId);

            $_SESSION['info_message_del'] = "Item duplicated successfully.";
            header("location: ?page=view");
            exit();
        } else {
            die("Error duplicating product: " . mysqli_error($conn));
        }
    } else {
        die("Error duplicating item: " . mysqli_error($conn));
    }
}

// Recursive function to duplicate BOM
function duplicateBom($conn, $originalParentId, $newParentId) {
    $bomQuery = "SELECT * FROM bom WHERE main_product_id = $originalParentId";
    $result = mysqli_query($conn, $bomQuery);

    if ($result && mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $insertQuery = "
                INSERT INTO bom (
                    main_product_id, sub_part_id, sub_part_name, quantity_required, type, unit_cost, 
                    adjusted_quantity, total_cost, product_labour_cost, product_labour_hours, machine_cost, machine_hours
                )
                VALUES (
                    $newParentId,
                    {$row['sub_part_id']},
                    '" . mysqli_real_escape_string($conn, $row['sub_part_name']) . "',
                    {$row['quantity_required']},
                    '{$row['type']}',
                    {$row['unit_cost']},
                    {$row['adjusted_quantity']},
                    {$row['total_cost']},
                    {$row['product_labour_cost']},
                    {$row['product_labour_hours']},
                    {$row['machine_cost']},
                    {$row['machine_hours']}
                )
            ";
            if (mysqli_query($conn, $insertQuery)) {
                $newSubPartId = mysqli_insert_id($conn);

              //  duplicateBom($conn, $row['sub_part_id'], $newSubPartId);
            } else {
                die("Error duplicating BOM: " . mysqli_error($conn));
            }
        }
    }
}


if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete')
{ 
    $id =$_REQUEST['id'];
  
	$usual_source = utility::getTableFieldById("item_management","usual_source","id",$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."' ");
	
	
	
	if($usual_source == "Manufactured"){
	    mysqli_query($conn,"DELETE FROM bom WHERE main_product_id = '".$_REQUEST['id']."' ");
	    mysqli_query($conn,"DELETE FROM bom WHERE sub_part_id = '".$_REQUEST['id']."' ");
	}else{
		mysqli_query($conn,"DELETE FROM bom WHERE sub_part_id = '".$_REQUEST['id']."' ");
	}
	$_SESSION['info_message_del'] = "Item deleted sucessfully";
	header("location: ?page=view".$next_page_condition.$paging);
	exit();
}
#################################  END DELETE    #########################################
#################################  Export CSV    #########################################
if(isset($_REQUEST['action']) && $_REQUEST['action']=='export_item_management'){
  include("export_item_management_to_csv.inc.php");
}
###########################################  End Export  #####################################
?>
<style>
#duplicateModal {
  border-radius: 8px;
  max-width: 400px;
  width: 90%;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 7px 15px;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}
.table-responsive {
    max-height: 600px;   /* adjust height as needed */
    overflow-y: auto;
}

.table thead th {
    position: sticky;
    top: 0;
    background: #fff;    /* important so text is visible */
    z-index: 2;
    box-shadow: 0 2px 2px -1px rgba(0,0,0,0.1);
}

</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="">
					<!----------------------- Message ------------------------------->
					<? if(isset($_SESSION['info_message'])){ ?>
					  <div class="alert alert-info alert-dismissable">
						<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
						<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
					  </div>
					  <? } ?>
					<!----------------------- End Message ------------------------------->
					<div class="card">
						<div class="card-body">
						<!-- search form -->
						<?php include_once('item_management_search_options.inc.php');?>
						<!-- /.search form -->
						Total No. of Items: <?=$total_no_of_records;?>
<div style="float:right;margin-bottom:4px;">
    <a href="index?page=view&action=export_item_management<?=$next_page_condition;?>">
        Export to CSV&nbsp;&nbsp;<i class="fa fa-download" style="font-size:20px;"></i>
    </a>
</div>
						
							<form action="index?page=add" method="post" name="form1" id="form1">
							<div class="card-footer">
							<?php if($can_view){ ?>
							   <button type="submit" name="add" class="btn btn-primary">Add Item</button>
							<?php } ?>   
							   <?/* if(!$is_archive){ ?>
								<button type="button" name="archive_cause" id="archive_cause" class="btn btn-warning pull-right" style="float:right;">Archive</button>
								<? }else{ ?>
								<button type="button" name="unarchive_cause" id="unarchive_cause" class="btn btn-warning pull-right" style="float:right;">Unarchive</button>
								<? }*/ ?>
							</div>
							<? if($result>0){?>
							<div class="table-responsive">
							 <table id="example1" class="table table-bordered table-striped">
								<thead>
								  <tr>
									<!--<th>#</th>-->
									<th>Part Number</th>
									<th style="width:400px;">Product Description</th>
									<th>Product Group</th>
									<th>Usual Source</th>
									<th>Inventory</th>
									<th class="">BOM</th>
									<th class="">Stock Forecasting</th>
									<?php if($can_view){ ?>
									<th class="text-center">Duplicate</th>
									<?php } ?>
									<?php if($can_view){ ?>
									<th>Edit</th>
									<?php } ?>
									<?php if($can_view){ ?>
									<th>Delete</th>
									<?php } ?>
								  </tr>
								</thead>
								<tbody>
									<?
										while($row =mysqli_fetch_array($sql)){ 
										$row=utility::validate_crypt_data($row);
									?>
								  <tr>
								    <td nowrap>
										<a href="index?page=view_item_details&from=view_item&item_id=<?=urlencode(utility::app_crypt($row['id'],'e'));?>&id=<?=$row['id'].$next_page_condition.$paging;?>" class="text-primary"><?php echo ucfirst($row["part_number"]);?>
										</a>
									</td>
									
									<td><?php echo $row["product_description"];?></td>
									<td><?php echo $gsi->getProductGroupById($row["product_group"]);?></td>
									
									<td><?php echo $row["usual_source"];?></td>
									<td>
										<?php echo number_format($row["quantity_in_stock"], 2); ?>
									</td>
									<td class=" "> <a href='#' data-toggle='modal' class="p-1 text-info text-bold" data-target='#ShowModal1' id="" alt="<?=$row['part_number_id']?>">View</a></td>
									<td class=" ">
									  <a href="#" 
										 class="p-1 text-info text-bold view-raw-material" 
										 data-id="<?= $row['id']; ?>" 
										 data-toggle="modal" 
										 data-target="#ShowModal11">
										 View
									  </a>
									</td>
																		
									<?php if($can_view){ ?>
									<!-- Table Row Example -->
									<td class="text-center">
									  <a href="#" 
										 onclick="openDuplicatePopup(<?= $row['id']; ?>, '<?= $row['part_number']; ?>', '<?= $row['product_description']; ?>'); 
												  return false;" >
										<i class="fa fa-fw fa-clone text-primary"></i>
									  </a>
									</td>

									<td><a href="index?page=add&action=edit&item_id=<?=urlencode(utility::app_crypt($row['id'],'e'));?>&id=<?=$row['id'].$next_page_condition.$paging;?>"> <i class="fa fa-fw fa-edit text-primary"></i> </a></td>
								
									<td><a href="index?page=view&action=delete&item_id=<?=urlencode(utility::app_crypt($row['id'],'e'));?>&id=<?=$row['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>
									<?php } ?>
									
								  </tr>
									<? } ?>
									
								</tbody>
							 </table>
							 </div>
							 <? }else{ ?>
								No Item found...
							 <? } ?>
							<div class="box-footer clearfix">
								<!-- Paging starts here  -->
								<? 
								$next_page_condition .="&page=view";
								include("paging/paging_row.inc.php") 
								?>
								<!-- Paging ends starts here  -->
							</div>
						</div>
						<div class="card-footer hide">
						<?php if($can_view){ ?>
						   <button type="submit" name="add" class="btn btn-primary">Add Item</button>
						<?php } ?>   
						</div>
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<!-- Duplicate Modal -->
<div id="modalOverlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0, 0, 0, 0.5); z-index:9998;"></div>
<div id="duplicateModal" style="display:none; position:fixed; top:20%; left:50%; transform:translate(-50%, -20%); width:50%; background:#fff; z-index:9999; padding:20px; border-radius:8px;">
  <h3 class="">Duplicate Item </h3>
  <hr style="background-color: #9c4893; height:1px; margin-top: 0; margin-bottom: 1;">  
  <form action="index?page=view&action=dublicateBOM" method="POST"  >
    <input type="hidden" id="originalId" name="original_id">
    <div>
      <label for="modalPartNumber" class="control-label">Part Number</label>
      <input type="text" id="modalPartNumber" class="form-control"  name="part_number" >
    </div>
    <div>
      <label for="modalPartDescription" class="control-label">Part Description</label>
      <input type="text" id="modalPartDescription" class="form-control"  name="part_description" >
    </div>
    <div style="margin-top:20px;">
      <button type="submit" class="bg-success">Duplicate</button>
      <button type="button" onclick="closeDuplicatePopup()" class="bg-danger">Cancel</button>
    </div>
  </form>
</div>

<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">Bill Of Materils 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>
<style>
  .bg-custom-purple {
    background-color: #912791;
    color: white; /* Ensures good contrast */
  }
</style>
<!-- Raw Material Modal -->
<div class="modal fade" id="ShowModal11" tabindex="-1" role="dialog" aria-labelledby="rawMaterialModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl" role="document">
    <div class="modal-content">
    <div class="modal-header bg-custom-purple">
        <h5 class="modal-title" id="rawMaterialModalLabel">Stock Forecasting</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span>&times;</span>
        </button>
      </div>
      <div class="modal-body" id="rawMaterialModalBody">
        <!-- Content will be loaded here via AJAX -->
        <div class="text-center">
          <span class="spinner-border text-warning" role="status"></span> Loading...
        </div>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">function openDuplicatePopup(id, partNumber, partDescription) {
  
  const isConfirmed = confirm('You are about to duplicate the item. Do you want to proceed?');

  if (isConfirmed) {
    document.getElementById('originalId').value = id;
    document.getElementById('modalPartNumber').value = partNumber;
    document.getElementById('modalPartDescription').value = partDescription;

    document.getElementById('duplicateModal').style.display = 'block';
    document.getElementById('modalOverlay').style.display = 'block';
  }

}

function closeDuplicatePopup() {
  document.getElementById('duplicateModal').style.display = 'none';
  document.getElementById('modalOverlay').style.display = 'none';
}
$(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/item_management/index.php?page=ajax_actions&action=get_group_list&id=" + id,
        method: "POST",
        dataType: "json",  // Assuming your PHP script returns JSON data
        success: function(data) {
            if (data.status === 'success') {
                // Populate the #group_tree div with the received data
                $("#group_tree1").html(data.htmlContent);  // Assume the PHP script sends back HTML content for the tree

                // Show the modal
                $('#ShowModal1').modal('show');
            } else {
                alert("No data available");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Something went wrong: " + textStatus + " - " + errorThrown);
        }
    });

};
	 });
$(function () {
	$(".close_button").click(function(){
		$(".modal_iframe").attr("src","");
	});
	///////////////////////////// START ARCHIVING/UNARCHIVING cause///////////////////////////////////////
	$("#archive_cause").click(function(){
		if ($(".checkbox:checked").length == 0){
			alert("Please select cause");
			return false;
		}
		if(confirm("Are you sure you want archive the selected cause(s).")){
			$('#form1').attr("action","index?page=view&action=archive<?=$next_page_condition.$paging;?>");
			$('#form1').submit();
		}
	});
	$("#unarchive_cause").click(function(){
		if ($(".checkbox:checked").length == 0){
			alert("Please select cause");
			return false;
		}
		if(confirm("Are you sure you want unarchive the selected cause(s).")){
			$('#form1').attr("action","index?page=view&action=unarchive<?=$next_page_condition.$paging;?>");
			$('#form1').submit();
		}
	});
	///////////////////////////// START ARCHIVING/UNARCHIVING cause///////////////////////////////////////
	$('#check_all').click(function(){
        if($("#check_all:checked").length == 1){
            $('.checkbox').prop( "checked", true );
        }else{
            $('.checkbox').prop( "checked", false );
        }
    });
	
	
});
</script>
<script>
$(document).ready(function() {
  $('.view-raw-material').on('click', function() {
    const partNumberId = $(this).data('id');
	//alert(partNumberId);

    // Show loading spinner
    $('#rawMaterialModalBody').html('<div class="text-center"><span class="spinner-border text-warning" role="status"></span> Loading...</div>');

    $.ajax({
     
	   url: site_url + "/modules/item_management/index.php?page=ajax_actions&action=raw_matrial_fetch",
      type: 'POST',
      data: { part_number_id: partNumberId },
      success: function(response) {
        $('#rawMaterialModalBody').html(response);
      },
      error: function() {
        $('#rawMaterialModalBody').html('<div class="alert alert-danger">Error loading data.</div>');
      }
    });
  });
});
</script>