<?php
session_start();
$where 					= " WHERE 1=1 AND item_not_exist = 1 ";
$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
}
###########################################  STRAT FILTER CONITIONS    #####################################
$country 	= isset($_REQUEST['country']) ? $_REQUEST['country'] : "";
if($country) {
    $where	.= " AND country LIKE '%$country%' ";
    $next_page_condition.="&country=$country";
}
###########################################  	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		= "production_planning";
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Part Number CSV Import";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################
$query = "SELECT * FROM $table_name $where ORDER BY id ASC 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));
#################################   DELETE    #########################################
// when we click on delete this area of php code will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete')
{
	$sql=mysql_query("DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	$_SESSION['info_message'] = "IteM deleted sucessfully";
	header("location: $file_name?page=view_country".$next_page_condition.$paging);
	exit;
}
#################################  END DELETE    #########################################
?>
<section class="content-header">
  <h1>
	<?=$page_header;?>
  </h1>
</section>
<section class="content">
	<div class="row">
		<div class="col-lg-12">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-success 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="box">
				<div class="box-body">
				<!-- search form -->
				<?php //include_once('country_search_options.inc.php');?>
				<!-- /.search form -->
				Total No. of Items: <?=($total_no_of_records);?>
				   <div style="float:right;margin-bottom:4px;margin-right: 10px;">Bulk Import&nbsp;&nbsp;<a href="index?page=sales_order_bulk_import" target="_blank"><i class="fa fa-upload" style="font-size:20px;"></i></a></div>
					<form action="index?page=add_country" method="post" name="form1" id="form1">
					<div class="box-footer">
					   <button type="submit" name="add" class="hide btn btn-success">Add Country</button>
					</div>
					<? if($result>0){?>
					 <table id="example1" class="table table-bordered table-striped">
						<thead>
						  <tr>
							<th>Part Number</th>
							<th>Customers Ref</th>
							<th>Req Date </th>
							<th>Req Qty</th>
							<th>Part Not Present</th>
							<th class="hide">Edit</th>
							<th>Delete</th>
						  </tr>
						</thead>
						<tbody>
							<?php
								while($row = mysqli_fetch_array($sql)){ 
								echo $row['id'];
									// If item_not_exist = 1 → use item_name_if_not_exist and red background
									$isNotExist = ($row['item_not_exist'] == 1);
									$partName = $isNotExist 
										? $row['item_name_if_not_exist'] 
										: utility::getTableFieldById("item_management", "part_number", "id", $row['part_id']);
									
									// Check if part exists in item_management table
									$partExists = false;
									if (!$isNotExist && $row['part_id']) {
										// If we have part_id, check if it exists
										$checkPartQuery = "SELECT COUNT(*), id as count FROM item_management WHERE id = '" . $row['part_id'] . "'";
										$checkResult = mysqli_query($conn, $checkPartQuery);
										if ($checkResult) {
											$checkRow = mysqli_fetch_assoc($checkResult);
											$partExists = ($checkRow['count'] > 0);
											echo $checkRow['id'];
										}
									} else if ($isNotExist) {
										// For items that don't exist, check if part_number exists in item_management
										$checkPartQuery = "SELECT COUNT(*) as count,id FROM item_management WHERE part_number = '" . mysqli_real_escape_string($conn, $partName) . "'";
										$checkResult = mysqli_query($conn, $checkPartQuery);
										if ($checkResult) {
											$checkRow = mysqli_fetch_assoc($checkResult);
											$partExists = ($checkRow['count'] > 0);
											echo $checkRow['id'];
										}
									}
							?>
							<tr style="<?= $isNotExist ? 'background-color: #ffcccc;' : '' ?>">
								<td>
									<?php if ($isNotExist): ?>
										<!-- Make it a link to the item management page with the part number -->
										<a href="<?= $config->frontEndURL . '/admin/item_management/index?page=add&part_number=' . urlencode($partName) . '&source=importcsv' ?>" 
										   title="Click to add this item to the system" style="color: #d9534f; font-weight: bold;">
										   <?= htmlspecialchars($partName) ?>
										</a>
									<?php else: ?>
										<?= htmlspecialchars($partName) ?>
									<?php endif; ?>
								</td>
								<td><?php echo ucfirst($row["customer_reff"]);?></td>
								<td><?php echo date('d-m-Y', strtotime($row['req_date'])); ?></td>
								<td><?php echo ucfirst($row['req_qty']); ?></td>
								<td style="text-align: center;">
    <?php 
	echo $checkRow['id'];
	if ($partExists): ?>
        <a href="#" 
           class="trigger-part-import" 
           data-id="<?= $row['id'] ?>" 
           data-part="<?= htmlspecialchars($checkRow['id']) ?>" 
           data-customer="<?= htmlspecialchars($row['customer_reff']) ?>" 
           data-reqdate="<?= htmlspecialchars($row['req_date']) ?>" 
           data-qty="<?= htmlspecialchars($row['req_qty']) ?>"
           style="color: #d9534f; font-weight: bold; text-decoration: underline; cursor: pointer;">
           Part Not Exist
        </a>
    <?php else: ?>
        <span style="color: #5cb85c; font-weight: bold;">Part Exist</span>
    <?php endif; ?>
</td>

								<td class="hide">
									<a href="index?page=add_country&action=edit&id=<?= $row['id'].$next_page_condition.$paging; ?>">
										<img src="../images/edit.gif" border="0" />
									</a>
								</td>
								<td>
									<a href="index?page=view_country&action=delete&id=<?= $row['id'].$next_page_condition.$paging; ?>" 
									   onclick="return confirm('Are you sure! You want to delete');">
										<img src="../images/del.gif" border="0" />
									</a>
								</td>
							</tr>
							<?php } ?>
							
							<!-- Paging starts here  -->
							<?php 
								$next_page_condition .="&page=view";
								include("paging/paging_row.inc.php") 
							?>
							<!-- Paging ends here  -->
						</tbody>

					 </table>
					 <? }else{ ?>
						No Items found...
					 <? } ?>
					 
				</div>
				<div class="box-footer">
                   <button type="submit" name="add" class="hide btn btn-success">Add Country</button>
                </div>
				</form>
			</div>
		</div>
	</div>
</section>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).on("click", ".trigger-part-import", function(e){
    e.preventDefault();

    const btn = $(this);
    const id = btn.data("id");
    const part = btn.data("part");
    const customer = btn.data("customer");
    const reqdate = btn.data("reqdate");
    const qty = btn.data("qty");

    if (!confirm("Are you sure you want to import and process this missing part?")) return;

    btn.text("Processing...").css("pointer-events", "none");

    $.ajax({
		url: site_url + "/modules/production_planning/index.php?page=ajax_actions_part_not_exist&action=ajax_process_missing_part",
       // url: "ajax_process_missing_part.php",
        type: "POST",
        data: {
            id: id,
            part_number: part,
            CustomersRef: customer,
            ReqDate: reqdate,
            ReqQty: qty
        },
        success: function(response){
            try {
                const res = JSON.parse(response);
                if (res.status === "success") {
                    alert("Part imported successfully!");
                    location.reload();
                } else {
                    alert("Error: " + res.message);
                }
            } catch(e) {
                alert("Unexpected response: " + response);
            }
        },
        error: function(){
            alert("AJAX request failed.");
        }
    });
});
</script>
