<?php
//include("../../database.inc.php"); //database.inc.php is databse connection file which will be included
include("../../../include/startup.php"); 
ob_clean();
function is_cyclic($parent,$child){
	global $conn;
	$adj_list=array();
	$adj_list[]=$parent;
	$stack[]=$child;
	
	while(count($stack)>0){
		$id=$stack[0];
		$adj_list[]=$id;
		array_splice($stack, 0, 1);
		$sql="select * from product_link where parent_id='".$id."'";
		$res=mysqli_query($conn,$sql);
		while($row=mysqli_fetch_assoc($res)){
			if(in_array($row["child_id"], $adj_list)){
				//echo "Cyclic";
				return 1;
			}else{
				$stack[]=$row["child_id"];
			}
			
		}
		
	}
	//echo "Not Cyclic ".$parent."->".$child;
	return 0;
}

function get_parent_list($id){
	global $conn;
	$parent_list=array();
	$stack=array();
	$stack[]=$id;
	while(count($stack)>0){
		$id=$stack[0];
		$parent_list[]=$id;
		array_splice($stack, 0, 1);
		$sql="select * from product_link where parent_id='".$id."'";
		$res=mysqli_query($conn,$sql);
		while($row=mysqli_fetch_assoc($res)){
			$stack[]=$row["child_id"];
		}
		
	}
	return implode(",",$parent_list);
}
function calculate_child_cost($id){
	global $conn;
	$total_cost=0;
	$total_labour_cost=0;
	
	$stack=array();
	$stack[]=$id;
	while(count($stack)>0){
		$id=$stack[0];
		array_splice($stack, 0, 1);
		$sql="select * from product_name where id='".$id."'";
		$res=mysqli_query($conn,$sql);
		$row=mysqli_fetch_assoc($res);
		$total_cost=$total_cost + ($row["cost"] * $row["qty"]);
		$total_labour_hours=$total_labour_hours + ($row["labour_hours"]);
		$total_labour_cost=$total_labour_cost + ($row["labour_cost"] * 1);
		$total_final_cost = $total_cost + $total_labour_cost;
		$sql="select * from product_link where parent_id='".$id."'";
		$res=mysqli_query($conn,$sql);
		while($row=mysqli_fetch_assoc($res)){
			$stack[]=$row["child_id"];
		}
		
	}
	
	return array($total_labour_hours,$total_cost,$total_labour_cost,$total_final_cost);
}
if(isset($_REQUEST['action']) && $_REQUEST['action']=='change_status'){
  $page_id = $_REQUEST['page_id'];  
  $new_status = ($_REQUEST['status'] == 0) ? 1 : 0; 
  if($page_id){
    $update_page = "UPDATE pages SET live ='".$new_status."' WHERE id='".$page_id."' ";
    if(mysqli_query($conn,$update_page)){
      echo "Page status changed";
    }
  }else{
    echo "Page status not changed";
  }
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='check_country_exist'){
	$part_num_category = $_REQUEST['part_num_category'];
	$id = $_REQUEST['id'];
	$where = "";
	if(isset($id) && $id !=""){
		$where = " AND id != '$id' ";
	}
	$returnArray = array();
	$sql = "SELECT * FROM part_num_category WHERE part_num_category = '$part_num_category' $where ";
	$rs = mysqli_query($conn,$sql);
	if(mysqli_num_rows($rs) > 0){
		$row = mysqli_fetch_assoc($rs);
		$returnArray['status'] = "failure";
	}else{
		$returnArray['status'] = "success";
	}
	echo json_encode($returnArray);	
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_product_mapping'){
	$id = $_REQUEST['na_mapping_id'];
	//echo "DELETE FROM job_enquiry_mapping WHERE id = '$id' ";
	mysqli_query($conn,"DELETE FROM product_group_mapping WHERE id = '$id' ");
	$returnArray["status"] = "success";
	echo json_encode($returnArray);
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='get_cyclic_status'){
	$parent=$_REQUEST["parent_id"];
	$child=$_REQUEST["child_id"];
	$dataArray=array();
	$dataArray["status"]="sucess";
	$dataArray["result"]=is_cyclic($parent,$child);	
	echo json_encode($dataArray);
    die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='get_group_details'){
	$id = $_REQUEST['id'];
	$data=array();
	$sql="SELECT * FROM product_name order by id DESC";
	$res = mysqli_query($conn,$sql);
	
	if(mysqli_num_rows($res) > 0){
		while($row = mysqli_fetch_array($res)){
			$child_cost = calculate_child_cost($row["id"]);
			$checked_status=0;
			$cycle_status=1;
			if($_REQUEST["page_edit"]="edit"){
				$sql="select * from product_link where parent_id='".$id."' and child_id='".$row["id"]."'";
				//echo "<br/>".$sql;
				$res1=mysqli_query($conn,$sql);
				if(mysqli_num_rows($res1)>0){
					$checked_status=1;
				}
				$row1=mysqli_fetch_array($res1);
				if($id!=$row["id"]){
					//echo "<br/>R".$row["id"];
					$cycle_status=is_cyclic($id,$row["id"]);
				}
			}
			$data[]=array("checked_status"=>$checked_status,
							"cycle_status"=>$cycle_status,
							"chk_val"=>$row["id"],
							"group_code"=>strtoupper($row["group_code"]),
							"group_name"=>"<a href='#' data-toggle='modal' data-target='#ShowModal' alt='".$row["id"]."' class='text-primary'>".ucwords($row["group_name"])."</a>",
							"qty"=>$row["qty"].'   '.$row["unit"],
							"cost"=>$row["cost"],
							"labour_cost"=>$row["labour_cost"],
							"labour_hours"=>$row["labour_hours"],
							"group_number"=>$row["group_number"],
							"total_cost"=>$child_cost[1],
							"total_labour_cost"=>$child_cost[2],
							"total_final_cost"=>$child_cost[1]+$child_cost[2]
							);
		}
	}
	
	$finaldata["data"]=$data;
	//echo "<pre>";
	//print_r($finaldata);
	//echo "</pre>";
    
	echo json_encode($finaldata);
   
}elseif(isset($_REQUEST['action']) && $_REQUEST['action']=='get_group_list'){
	//$data[]="Ajax Call Data";
	//echo json_encode($data);
    //die;
	$id=$_REQUEST["id"];
	$parent_id_list=get_parent_list($id);
	/*$query = "SELECT product_name.*,case when product_link.parent_id is NULL then 0 else product_link.parent_id end as parent_id FROM product_name
				left join product_link on product_link.child_id=product_name.id
				where product_link.parent_id='".$id."' or product_name.id='".$id."'
				order by product_link.parent_id,product_name.group_name";*/
	$query = "select product_name.*,'0' parent_id FROM product_name where product_name.id='".$id."'
				union
				SELECT product_name.*,case when product_link.parent_id is NULL then 0 else product_link.parent_id end as parent_id FROM product_name
				left join product_link on product_link.child_id=product_name.id
				where product_link.parent_id in (".$parent_id_list.")
				order by parent_id,group_name;
				";
	//echo "<br/>".$query;
    $result = mysqli_query($conn, $query);
    //$output = array();
    while($row = mysqli_fetch_array($result))
    {
		$child_cost=calculate_child_cost($row["id"]);
        $sub_data["id"] = $row["id"];
        $sub_data["name"] = ucwords($row["group_name"]);
        $sub_data["text"]=ucwords($row["group_name"]);    
        if($row["parent_id"]=="0"){
            $sub_data["class"]="font-bold";
        }else{
            $sub_data["class"]="";
        }
        //$sub_data["text"]=$sub_data["text"]."'/><input type='button' class='no_background_border' value='Delete Folder' style='color:blue;float:right;font-size:12px;font-style:italic;' onclick='return delete_category(this,".$row["id"].");'/><input type='button' class='no_background_border' value='Add Sub Folder' style='color:blue;float:right;font-size:12px;font-style:italic;' onclick='return add_sub_category(".$row["id"].");'/>";
        
        $sub_data["parent_id"] = $row["parent_id"];
        //$total_file=find_total_files($row["id"]);
        $sub_data["tags"]=array("Qty : ".$row["qty"].",  Cost : ".$row["cost"].", Labour Cost : ".$row["labour_cost"].",Labour Hours : ".$row["labour_hours"].", Total Labour Hours : ".$child_cost[0].",Total Components Cost : ".$child_cost[1].", Total Labour Cost : ".$child_cost[2].", Total Cost : = " .$child_cost[3]);
        
        $data[] = $sub_data;
    }
    foreach($data as $key => &$value)
    {
        $output[$value["id"]] = &$value;
    }
    foreach($data as $key => &$value)
    {
        if($value["parent_id"] && isset($output[$value["parent_id"]]))
        {
            $output[$value["parent_id"]]["nodes"][] = &$value;
        }
    }
    foreach($data as $key => &$value)
    {
        if($value["parent_id"] && isset($output[$value["parent_id"]]))
        {
            unset($data[$key]);
        }
    }
	//echo "<pre>";
	//print_r($data);
	//echo "</pre>";
    echo json_encode($data);
    die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete_job_notes'){
    $notes_id = $_REQUEST['notes_id'];

    // First, let's delete the entry with ID = $notes_id from product_name table
    mysqli_query($conn, "DELETE FROM product_name WHERE id = '$notes_id'");

    // Now, let's find and delete all related entries in product_link table where parent_id = $notes_id
    mysqli_query($conn, "DELETE FROM product_link WHERE parent_id = '$notes_id'");

    // Now, let's find and delete all related entries in product_link table where child_id = $notes_id
    mysqli_query($conn, "DELETE FROM product_link WHERE child_id = '$notes_id'");

    // Also, let's check if there are any child links for $notes_id, and delete those records as well
    $child_ids_query = mysqli_query($conn, "SELECT child_id FROM product_link WHERE parent_id = '$notes_id'");
    if(mysqli_num_rows($child_ids_query) > 0){
        while($row = mysqli_fetch_assoc($child_ids_query)) {
            $child_id = $row['child_id'];

            // Delete child link records
            mysqli_query($conn, "DELETE FROM product_link WHERE child_id = '$child_id'");

            // Delete corresponding entries from product_name table
            mysqli_query($conn, "DELETE FROM product_name WHERE id = '$child_id'");
        }
    }

    // Finally, let's return success status
    $returnArray["status"] = "success";
    echo json_encode($returnArray);
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='check_product_group_exist'){
	$product_group_name = $_REQUEST['product_group_name'];
	$id = $_REQUEST['id'];
	$where = "";
	if(isset($id) && $id !=""){
		$where = " AND id != '$id' ";
	}
	$returnArray = array();
	$sql = "SELECT * FROM product_group WHERE product_group_name = '$product_group_name' $where ";
	$rs = mysqli_query($conn,$sql);
	if(mysqli_num_rows($rs) > 0){
		$row = mysqli_fetch_assoc($rs);
		$returnArray['status'] = "failure";
	}else{
		$returnArray['status'] = "success";
	}
	echo json_encode($returnArray);	
}

die;
?>
