<?php
session_start();

if ($_REQUEST['from'] == "planner") {
    $part_id = isset($_REQUEST['part_id']) ? utility::app_crypt($_REQUEST['part_id'], 'd') : "";
    $where = " WHERE id IN (
        SELECT work_order_id FROM work_order_customer_ref_mapping 
        WHERE product_id = '$part_id'
    )";
    $next_page_condition = "&part_id=" . $_REQUEST['part_id'];
} else {
    $where = " WHERE 1=1 ";
    $next_page_condition = "";
}
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
} 
$restricted_groups = [13, 15, 16, 19, 21];
$can_view = !in_array($_SESSION['admin_group_id'], $restricted_groups);
##################################  STRAT FILTER CONITIONS    ###############################

$order_ref = isset($_REQUEST['order_ref']) ? $_REQUEST['order_ref'] : "";

if ($order_ref) {
    $order_ref = trim($order_ref);

    $where .= " AND id IN (
        SELECT wom.work_order_id 
        FROM work_order_customer_ref_mapping wom
        WHERE wom.product_id IN (
            SELECT im.id 
            FROM item_management im
            WHERE im.part_number LIKE '%$order_ref%'
        )
    )";

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

################################# END FILTER CONDITIONS ################################

###########################################  PAGING WITH PER PAGE  #####################################

$orderby = " ORDER BY id DESC ";
$file_name		= "index";
$table_name		= "work_order";
$paging_table_name	= $table_name;
$paging_query		= $where;

$join_query_for_paging = "SELECT * FROM $table_name $where";
$page_header = "Customer Order";
include("paging/paging_query.inc.php");
################################## END PAGING WITH PER PAGE  ################################

$query = "SELECT * FROM $table_name $where $orderby LIMIT $eu, $limit";

$sql = mysqli_query($conn, $query);
$result = mysqli_num_rows($sql);

$total_no_of_purchase_order = mysqli_num_rows(mysqli_query($conn, $join_query_for_paging));

#################################   DELETE    #########################################
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_revers'){
	
    $work_order_id = $_REQUEST['id'];

    $query = "SELECT * FROM work_order_detail WHERE work_order_id = $work_order_id";
    $result = $conn->query($query);

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $product_id  = intval($row['product_id']);
            $quantity    = intval($row['quantity']);
            $process_type = intval($row['process_type']);

            if ($process_type == 12) { 
                $query = "UPDATE inventory SET quantity_in_stock = quantity_in_stock + $quantity WHERE item_id = $product_id";
                $conn->query($query);	   	
            }

            if ($process_type == 4) { 
                $query = "DELETE FROM purchase_list WHERE item_id = $product_id AND work_order_id = $work_order_id";
                $conn->query($query);
            }
        }
    }

    $conn->query("DELETE FROM work_order_detail WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM work_order WHERE id = $work_order_id"); 
    $conn->query("DELETE FROM manufacture_machine_table WHERE work_order_id = $work_order_id");

    mysqli_query($conn, "DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	
    $_SESSION['info_message'] = "Work order and associated details have been deleted successfully undone.";
    header("location: $file_name?page=view".$next_page_condition.$paging);
    exit();
}

if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete'){
	
    $work_order_id = $_REQUEST['id'];
    $work_order_id = (int)$_REQUEST['id'];

// 🔴 RESET allocation before delete
	mysqli_query($conn, "
		UPDATE production_planning 
		SET 
			produce_qty = 0,
			status = 0,
			work_order_id = NULL
		WHERE work_order_id = '$work_order_id'
	");
    $conn->query("DELETE FROM work_order_detail WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM work_order_customer_ref_mapping WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM work_order_name WHERE work_order_id = $work_order_id");
	$conn->query("DELETE FROM work_order_raw_matrial WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM manufacture_machine_table WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM vac_machine_table WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM cnc_machine_table WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM pu_machine_table WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM assbly_machine_table WHERE work_order_id = $work_order_id");	
    $conn->query("DELETE FROM assypu_machine_table WHERE work_order_id = $work_order_id");

    $updateQuery = "UPDATE production_planning SET work_order_id = 0, status = 0 WHERE work_order_id = $work_order_id";
    $sql_delete_children = "DELETE FROM manufacture_machine_children WHERE work_order_id = $work_order_id";

    mysqli_query($conn, $sql_delete_children);
    mysqli_query($conn, $updateQuery);
    mysqli_query($conn, "DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	
    $_SESSION['info_message'] = "Work order and associated details have been deleted successfully.";
    header("location: $file_name?page=view".$next_page_condition.$paging);
    exit();
}
#################################  END DELETE    #########################################
?>

<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>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
        <div class="">
            <!----------------------- Message ------------------------------->
            <?php 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>
                <?php echo $_SESSION['info_message']; unset($_SESSION['info_message']); ?>
            </div>
            <?php } ?>
            <!----------------------- End Message ------------------------------->

            <div class="card">
                <div class="card-body">

                <!-- search form -->
                <?php include_once('Work_order_search_options.inc.php'); ?>
                <!-- /.search form -->

                Total No. of Customer Orders: <?=$total_no_of_purchase_order;?>
				<?php if($can_view){ ?>
                <div style="margin-bottom: 10px;">
                        <a href="index?page=create" class="btn btn-primary">
                            <i class="fa fa-plus"></i> Create Manual Work Order
                        </a>
                    </div>
				
				<?php } ?>
				<?php if($can_view){ ?>
                <div class="text-right" style="margin-top:5px;">
				<form method="POST" action="index?page=clear_all_tables"  
					  onsubmit="return confirm('WARNING: This will delete ALL DATA from all listed tables. Are you sure?');"
					  style="margin-top:15px;">

					<button type="submit" class="btn btn-danger">
						<i class="fa fa-trash"></i> Clear All Tables
					</button>

				</form>
                </div>
				
				<?php } ?>
				
                <form action="index?page=add_work_order" method="post" name="form1" id="form1">
                <div class="card-footer hide">
                    <button type="submit" name="add" class="btn btn-primary">Add Customer Order</button>
                </div>

                <?php if($result > 0){ ?>
                <div class="table-responsive">
                    <table id="example1" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Customer Ref.</th>
                                <th>Products</th>
                                <th>Sets</th>
                                <th>Groups</th>
                                <th>Quantity</th>
                                <th>Required Date</th>
                               <!-- <th>Sales Ref</th>-->
                                <th>Customer</th>
                                <?php if($can_view){ ?>
                                <th>Edit</th>
                                <th class="hide">Undo</th>
                                <th>Delete</th>
                                <?php } ?>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                        while($row = mysqli_fetch_array($sql)){ 
                            $row = utility::validate_crypt_data($row);

                            $work_order_nos        = [];
                            $work_order_quantity   = [];
                            $product_ids           = [];

                            // ── CUSTOMER REF MAPPING ─────────────────────────────────────────
                            $sql_for_customer_ref = "SELECT work_order_no, product_id, quantity 
                                                     FROM work_order_customer_ref_mapping 
                                                     WHERE work_order_id = '".$row['id']."'";

                            $result_for_cust_ref = mysqli_query($conn, $sql_for_customer_ref);

                            if ($result_for_cust_ref) {
                                while ($row_cust_ref = mysqli_fetch_assoc($result_for_cust_ref)) {
                                    $work_order_nos[]      = $row_cust_ref['work_order_no'];
                                    $product_ids[]         = $row_cust_ref['product_id'];
                                    $work_order_quantity[] = $row_cust_ref['quantity'];
                                }
                                $comma_separated_work_cust_ref       = implode(", ", $work_order_nos);
                                $comma_separated_work_order_quantity = implode(", ", $work_order_quantity);
                            }

                            // ── PRODUCTS: fetch part_number from item_management ─────────────
                            $part_numbers = [];
                            foreach ($product_ids as $pid) {
                                $pid = intval($pid);
                                if ($pid <= 0) continue;
                                $prod_res = mysqli_query($conn, "SELECT id, part_number FROM item_management WHERE id = '$pid'");
                                if ($prod_res && $prod_row = mysqli_fetch_assoc($prod_res)) {
                                    $part_numbers[] = htmlspecialchars($prod_row['part_number']);
                                } else {
                                    $part_numbers[] = $pid;
                                }
                            }
                            $comma_separated_part_numbers = implode(", ", array_unique($part_numbers));

                            // ── SETS: parse set_ids, fetch unique set_number for each ────────
                            $set_numbers = [];
                            if (!empty($row['set_ids'])) {
                                $raw_sets = $row['set_ids'];
                                // Support both JSON array "[1,2,3]" and plain "1,2,3"
                                if (substr(trim($raw_sets), 0, 1) === '[') {
                                    $set_id_array = json_decode($raw_sets, true);
                                } else {
                                    $set_id_array = array_map('trim', explode(',', $raw_sets));
                                }

                                // Remove duplicate IDs before querying
                                $set_id_array = array_unique($set_id_array);

                                foreach ($set_id_array as $sid) {
                                    $sid = intval($sid);
                                    if ($sid <= 0) continue;
                                    $set_res = mysqli_query($conn, "SELECT set_number FROM set_mangmnt WHERE id = '$sid' ORDER BY set_number ASC");
                                    if ($set_res && $set_row = mysqli_fetch_assoc($set_res)) {
                                        $set_numbers[] = htmlspecialchars($set_row['set_number']);
                                    }
                                }
                            }
                            // Also apply unique on set_numbers in case of any duplicate values
                            $comma_separated_set_numbers = implode(", ", array_unique($set_numbers));

                            // ── GROUPS: fetch group_number from group_mangmnt ────────────────
                            $group_number_display = "";
                            if (!empty($row['group_id'])) {
                                $gid = intval($row['group_id']);
                                $grp_res = mysqli_query($conn, "SELECT group_number FROM group_mangmnt WHERE id = '$gid' ORDER BY group_number ASC");
                                if ($grp_res && $grp_row = mysqli_fetch_assoc($grp_res)) {
                                    $group_number_display = htmlspecialchars($grp_row['group_number']);
                                }
                            }

                            // ── CUSTOMER: fetch customer_code from client_management ─────────
                            $customer_display = "";
                            if (!empty($row['customer_id'])) {
                                $cust_id  = intval($row['customer_id']);
                                $cust_res = mysqli_query($conn, "SELECT customer_code FROM client_management WHERE id = '$cust_id'");
                                if ($cust_res && $cust_row = mysqli_fetch_assoc($cust_res)) {
                                    $customer_display = htmlspecialchars($cust_row['customer_code']);
                                }
                            }
                        ?>
                        <tr>
                            <td nowrap>
                                <a href="index?page=view_work_order_detail&from=view&work_order_id=<?=urlencode(utility::app_crypt($row['id'],'e'));?>&id=<?=$row['id'].$next_page_condition.$paging;?>" class="text-primary">
                                    <?php echo $comma_separated_work_cust_ref; ?>
                                </a>
                            </td>
                            <td><?php echo $comma_separated_part_numbers; ?></td>
                            <td><?php echo $comma_separated_set_numbers; ?></td>
                            <td><?php echo $group_number_display; ?></td>
                            <td><?php echo $comma_separated_work_order_quantity; ?></td>
                            <td><?php echo utility::getFormatedDate($row['require_date']); ?></td>
                           <!-- <td><?php echo $row["customer_id"]; ?></td>-->
                            <td><?php echo $customer_display; ?></td>
                            <?php if($can_view){ ?>
                            <td>
                                <a href="index?page=edit_work_order&action=edit&work_order_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 class="hide">
                                <a href="index?page=view&action=delete_revers&id=<?=$row['id'].$next_page_condition.$paging; ?>" 
                                   onclick="javascript:return confirm('Are you sure you want to undo this Work Order?');" 
                                   <?=$edit_delete_display;?>>
                                    <i class="fa fa-fw fa-undo text-primary"></i>
                                </a>
                            </td>
                            <td>
                                <a href="index?page=view&action=delete&id=<?=$row['id'].$next_page_condition.$paging; ?>" 
                                   onclick="javascript:return confirm('Are you sure you want to delete?');" 
                                   <?=$edit_delete_display;?>>
                                    <i class="fa fa-fw fa-trash text-danger"></i>
                                </a>
                            </td>
                            <?php } ?>
                        </tr>
                        <?php } ?>
                        </tbody>
                    </table>
                </div>
                <?php } else { ?>
                    No Work Order found...
                <?php } ?>

                <div class="box-footer clearfix">
                    <!-- Paging starts here -->
                    <?php 
                        $next_page_condition .= "&page=view";
                        include("paging/paging_row.inc.php"); 
                    ?>
                    <!-- Paging ends here -->
                </div>

                </form>
            </div>
            <!-- /.card-body -->

            <div class="card-footer hide">
                <button type="submit" name="add" class="btn btn-primary">Add Purchase List</button>
            </div>

            </div>
        </div>
        </div>
    </div>
    </div>
</section>

<script type="text/javascript">
$(function () {
    $(".close_button").click(function(){
        $(".modal_iframe").attr("src","");
        location.reload();
    });
});
</script>