<?php
include("../../../include/startup.php"); 
include("work_order_function.inc.php");

// Fetch spot_cost from item_management
if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_item_price'){
	$returnArray = array();
	$part_id = intval($_REQUEST['part_id']);
	
	$query = "SELECT standard_cost_ebq FROM item_management WHERE id = '$part_id' LIMIT 1";
	$result = mysqli_query($conn, $query);
	
	if($result && mysqli_num_rows($result) > 0){
		$row = mysqli_fetch_assoc($result);
		$returnArray["status"] = "success";
		$returnArray["price"] = $row['standard_cost_ebq'] ? $row['standard_cost_ebq'] : '0';
	} else {
		$returnArray["status"] = "failure";
		$returnArray["price"] = '0';
	}
	
	echo json_encode($returnArray);
	die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_po_item'){
	$returnArray = array();
	$po_item_mapping_id = $_REQUEST['po_item_mapping_id'];
	$delete_sql = "DELETE FROM purchase_order_items_mapping WHERE id = '$po_item_mapping_id'";
	if(mysqli_query($conn,$delete_sql)){
		$returnArray["status"] = "success";
	}else{
		$returnArray["status"] = "failure";
	}
	
echo json_encode($returnArray);
die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_group_items'){
    $part_id = $_POST['part_id'];
    $part_id_for_Qty = $_POST['part_id'];
    $set_check = $_POST['set_check'];
    $efficiency = $_POST['efficiency'];
    $orderQty = $_POST['order_qty'];

    $query = "SELECT DISTINCT gmm.group_id, gm.group_number, gm.group_type 
              FROM group_mangmnt_mapping gmm 
              JOIN group_mangmnt gm ON gmm.group_id = gm.id 
              WHERE gmm.part_id = $part_id";

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

    // Shows the full list of groups this part belongs to (mandatory and optional mixed).
    // Called whenever the part has 2+ groups total, so the user can always choose.
    if(mysqli_num_rows($result) > 0) {
        $part_number = utility::getTableFieldById("item_management","part_number","id",$part_id);
        $customer_reff = utility::getTableFieldById("production_planning","customer_reff","part_id",$part_id);

        $output = '<table class="table">
                        <tr><th>Group Number</th><th>Part Numbers</th><th>Type</th><th>Status</th></tr>';

        while ($row = mysqli_fetch_assoc($result)) {
            $group_id = $row['group_id'];
            $group_number = $row['group_number'];
            $group_type = $row['group_type'];

            $part_query = "SELECT part_id FROM group_mangmnt_mapping WHERE group_id = $group_id";
            $part_result = mysqli_query($conn, $part_query);

            $part_names = [];
            $part_ids = [];
            $not_matched_parts = [];

            while ($part_row = mysqli_fetch_assoc($part_result)) {
			   $loop_part_id = $part_row['part_id'];

			   $part_name = utility::getTableFieldById("item_management", "part_number", "id", $loop_part_id);
$part_names[] = $part_name;
$part_ids[]   = $loop_part_id;

				$check_query  = "SELECT COUNT(*) as count FROM production_planning WHERE part_id = '$loop_part_id'";
                $check_result = mysqli_query($conn, $check_query);
                $check_row = mysqli_fetch_assoc($check_result);

                if ($check_row['count'] == 0) {
                    $not_matched_parts[] = $part_name; 
                }
            }
            
            $part_names_list = implode(', ', $part_names);
            $part_id_list = implode(', ', $part_ids);
            
            if (!empty($not_matched_parts)) {
                $not_matched_list = implode(', ', $not_matched_parts);
                $highlighted_part_ids = "<span style='color: red; font-weight: bold;'>Not In List: $not_matched_list</span>";
            } else {
                $highlighted_part_ids = "<span style='color: green; font-weight: bold;'>In List</span>";
            }

            // Add group type badge
            $type_badge = ($group_type == 'mandatory') 
                ? '<span class="badge badge-danger">Mandatory</span>' 
                : '<span class="badge badge-warning">Optional</span>';

            $output .= '<tr class="group-item-row_1" data-group-id="' . $group_id . '" data-group-type="' . $group_type . '" data-orderqty-id="' . $orderQty . '" data-part-id="' . $part_id_for_Qty . '" style="cursor:pointer;">
                            <td>' . $group_number . '</td>
                            <td>' . $part_names_list . '</td>
                            <td>' . $type_badge . '</td>
                            <td>' . $highlighted_part_ids . '</td>
                            <td class="hide">
                                <input type="hidden" class="form-control set_check_value" value="' . $set_check . '" readonly>
                            </td>
                        </tr>';
        }

        $output .= '</table>';
        echo $output;
    } else {
        echo '<div class="alert alert-info">No groups found for this part.</div>';
    }
    die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_group_details'){
    $group_id = $_POST['group_id'];
    $part_id = $_POST['part_id'];
    $set_check = $_POST['set_check'];
    $efficiency = $_POST['efficiency'];
	$order_qty = !empty($_POST['OrderQty']) ? $_POST['OrderQty'] : (!empty($_POST['order_qty']) ? $_POST['order_qty'] : 1);
    
    // Get group type
    $group_type_query = "SELECT group_type FROM group_mangmnt WHERE id = $group_id";
    $group_type_result = mysqli_query($conn, $group_type_query);
    $group_type_row = mysqli_fetch_assoc($group_type_result);
    $group_type = $group_type_row['group_type'] ?? 'optional';
    
    $query = "SELECT part_id FROM group_mangmnt_mapping WHERE group_id = $group_id";
    $result = mysqli_query($conn, $query);

    $part_number = utility::getTableFieldById("item_management","part_number","id",$part_id);
    $customer_reff = utility::getTableFieldById("production_planning","customer_reff","part_id",$part_id);
    
    // Add main part number header
    $output = '<div class="alert alert-primary" style="background-color: #007bff; color: white; font-weight: bold; text-align: center;">';
    $output .= '<h5 style="margin: 0;">Main Part Number: ' . htmlspecialchars($part_number) . '</h5>';
    $output .= '</div>';
    
    // Add group type info to modal
    $type_display = ($group_type == 'mandatory') 
        ? '<div class="alert alert-info"><strong>Mandatory Group:</strong> All items must be produced together</div>' 
        : '<div class="alert alert-warning"><strong>Optional Group:</strong> You can choose to produce these items together</div>';
    
    $output .= $type_display;
    $output .= '<table class="table">
                    <tr><th>Part Number</th><th>Quantity</th></tr>';

    while ($row = mysqli_fetch_assoc($result)) {
        $current_part_id = $row['part_id'];
		$qty_value = ($group_type === 'mandatory') ? $order_qty : (($part_id == $current_part_id) ? $order_qty : 1);

        $part_name = utility::getTableFieldById("item_management", "part_number", "id", $current_part_id);
        
        $output .= '<tr class="group-item-row" data-group-item-id="' . $current_part_id . '">
                        <td>' . $part_name . '</td>
                        <td><input type="number" class="group-item-qty form-control" min="0" value="' . $qty_value . '"></td>
                        <td class="hide">
                            <input type="hidden" class="form-control set_check_value" value="' . $set_check . '" readonly>
                            <input type="hidden" class="form-control customer_reff" value="' . $customer_reff . '" readonly>
                            <input type="hidden" class="form-control efficiency" value="' . $efficiency . '" readonly>
                        </td>
                    </tr>';
    }

    $output .= '</table>';
    
    // For mandatory groups, add auto-submit functionality
    if ($group_type == 'mandatory') {
        $output .= '<div class="text-center">';
        $output .= '<button id="submitGroupOrder" class="btn btn-success">Submit Mandatory Group Order</button>';
        $output .= '</div>';
    } else {
        $output .= '<div class="text-center">';
        $output .= '<button id="submitGroupOrder" class="btn btn-success">Submit Order</button>';
        $output .= '<button type="button" class="btn btn-secondary ml-2" data-dismiss="modal">Cancel</button>';
        $output .= '</div>';
    }

    echo $output;
    die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='check_group_type'){
    // ------------------------------------------------------------------
    // UNIFIED RULE:
    //   - 0 groups            -> 'none'      (no group involvement at all)
    //   - exactly 1 group     -> auto-resolve, return its own type
    //                            ('mandatory' or 'optional') + group_id.
    //                            Nothing to choose between, so skip the picker.
    //   - 2 or more groups    -> 'multiple', regardless of whether the mix
    //                            is mandatory, optional, or both. The caller
    //                            (single-part flow or bulk flow) must always
    //                            show the group picker in this case.
    // ------------------------------------------------------------------
    $part_id = $_POST['part_id'];

    $query = "SELECT DISTINCT gmm.group_id, gm.group_type, gm.group_number
              FROM group_mangmnt_mapping gmm 
              JOIN group_mangmnt gm ON gmm.group_id = gm.id 
              WHERE gmm.part_id = $part_id";
    
    $result = mysqli_query($conn, $query);
    
    if(mysqli_num_rows($result) > 0) {
        $groups = [];
        while($row = mysqli_fetch_assoc($result)) {
            $groups[] = [
                'group_id'     => $row['group_id'],
                'group_type'   => $row['group_type'],
                'group_number' => $row['group_number']
            ];
        }

        if (count($groups) === 1) {
            // Only one group exists for this part (mandatory or optional) —
            // nothing to choose between, resolve it automatically.
            echo json_encode([
                'group_id'   => $groups[0]['group_id'],
                'group_type' => $groups[0]['group_type']
            ]);
        } else {
            // 2+ groups, any mix of mandatory/optional — always let the user choose.
            echo json_encode([
                'group_type' => 'multiple',
                'groups'     => $groups
            ]);
        }
    } else {
        echo json_encode(['group_type' => 'none']);
    }
    die;
}
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'fetch_set_items') {

    $orderData = json_decode($_POST['orderData'], true);

    $product_ids = [];
    foreach ($orderData as $item) {
        $product_ids[] = $item['groupItemId'];
    }

    $operations_ids = [];

    function processOrderHybridforset($product_ids, $conn, $depth = 0, $max_depth = 10)
    {
        global $operations_ids;

        foreach ($product_ids as $product_id) {
            $operations_ids[] = [
                'product_id' => $product_id,
            ];

            // Get BOM sub-parts
            $query = "SELECT sub_part_id FROM bom WHERE main_product_id = $product_id";
            $bom_parts = $conn->query($query);

            if ($bom_parts && $bom_parts->num_rows > 0 && $depth < $max_depth) {
                while ($bom = $bom_parts->fetch_assoc()) {
                    $sub_part_id = $bom['sub_part_id'];
                    $operations_ids[] = [
                        'product_id' => $sub_part_id,
                        'parent_ids' => [$product_id]
                    ];

                    // Recursive check for sub-parts
                    processOrderHybridforset([$sub_part_id], $conn, $depth + 1, $max_depth);
                }
            }
        }

        return true;
    }

    processOrderHybridforset($product_ids, $conn);

    // Collect unique product IDs
    $productIds = [];
    foreach ($operations_ids as $operation) {
        $productIds[$operation['product_id']] = true;
    }
    $productIds = array_keys($productIds);

    $productDetails = [];

    foreach ($productIds as $productId) {
        $sqlMapping = "
        SELECT 
            sm.set_id, 
            sm.part_id, 
            sm.ratio, 
            smm.description, 
            smm.set_number 
        FROM 
            set_mangmnt_mapping sm
        INNER JOIN 
            set_mangmnt smm 
        ON 
            sm.set_id = smm.id
        WHERE 
			sm.part_id = '$productId'
			AND smm.preferred_set = 0
        ";
        $result = mysqli_query($conn, $sqlMapping);

        if ($result && mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $row['part_name'] = utility::getTableFieldById("item_management", "part_number", "id", $row['part_id']);
                $productDetails[] = $row;
            }
        }
    }

    // Group by set_id
    $groupedSets = [];
    foreach ($productDetails as $item) {
        $setId = $item['set_id'];

        if (!isset($groupedSets[$setId])) {
            $groupedSets[$setId] = [
                'set_number' => $item['set_number'],
                'description' => $item['description'],
                'set_id' => $item['set_id'],
                'parts' => []
            ];
        }

        // Prevent duplicate parts in same set
        $exists = false;
        foreach ($groupedSets[$setId]['parts'] as $existingPart) {
            if ($existingPart['part_id'] == $item['part_id']) {
                $exists = true;
                break;
            }
        }

        if (!$exists) {
            $groupedSets[$setId]['parts'][] = [
                'part_id' => $item['part_id'],
                'part_name' => $item['part_name'],
                'ratio' => $item['ratio']
            ];
        }
    }

    // Get main part numbers from orderData for header
    $main_part_numbers = [];
    foreach ($orderData as $item) {
        $part_id = $item['groupItemId'];
        $part_number = utility::getTableFieldById("item_management", "part_number", "id", $part_id);
        if ($part_number) {
            $main_part_numbers[] = $part_number;
        }
    }
    $main_part_display = implode(', ', $main_part_numbers);

    // Build output with main part number header
    $output = '<div class="alert alert-primary" style="background-color: #007bff; color: white; font-weight: bold; text-align: center;">';
    $output .= '<h5 style="margin: 0;">Main Part Number: ' . htmlspecialchars($main_part_display) . '</h5>';
    $output .= '</div>';
    
    // Build output table
    $output .= '<table class="table table-bordered table-striped" style="font-size:12px;">
                <thead>
                    <tr>
                        <th style="width:30%">Part Numbers</th>
                        <th style="width:17%">Set Number</th>
                        <th style="width:45%">Description</th>
                        <th style="width:8%">Select</th>
                    </tr>
                </thead><tbody>';

    if (empty($groupedSets)) {
        $output .= '<tr><td colspan="4" class="text-center">No set items found.</td></tr>';
    } else {
        foreach ($groupedSets as $set) {
            $part_names = array_column($set['parts'], 'part_name');
            $part_names_string = implode(', ', $part_names);
            
            // Create individual part names with inventory quantities for popover
            $parts_with_quantities = [];
            foreach ($set['parts'] as $part) {
                // Get inventory quantity for each part
                $inv_query = "SELECT quantity_in_stock FROM inventory WHERE item_id = '" . mysqli_real_escape_string($conn, $part['part_id']) . "'";
                $inv_result = mysqli_query($conn, $inv_query);
                $quantity = 0;
                
                if ($inv_result && mysqli_num_rows($inv_result) > 0) {
                    $inv_row = mysqli_fetch_assoc($inv_result);
                    $quantity = $inv_row['quantity_in_stock'];
                }
                
                $parts_with_quantities[] = htmlspecialchars($part['part_name']) . ' (Stock: ' . number_format($quantity, 0) . ')';
            }
            
            // Create popover content for part names
            $parts_popover_content = implode('<br>', $parts_with_quantities);
            
            // Truncate long description for better display
            $description_display = $set['description'];
            $description_short = strlen($description_display) > 50 ? substr($description_display, 0, 50) . '...' : $description_display;
            
            $part_ids = array_column($set['parts'], 'part_id');
            $part_ids_string = implode(',', $part_ids);

            $output .= '
                <tr class="set-item-row" 
                    data-set-id="' . htmlspecialchars($set['set_id']) . '" 
                    data-part-ids="' . htmlspecialchars($part_ids_string) . '">
                    <td style="text-align:left;">
                        <span class="set-parts-popover" 
                              data-toggle="popover" 
                              data-placement="top" 
                              data-html="true" 
                              data-content="' . htmlspecialchars($parts_popover_content, ENT_QUOTES) . '"
                              style="cursor:pointer; color:#007bff; text-decoration:underline;">
                            ' . htmlspecialchars($part_names_string) . '
                            <span class="badge badge-info" style="margin-left:5px;">' . count($set['parts']) . ' parts</span>
                        </span>
                    </td>
                    <td>' . htmlspecialchars($set['set_number']) . '</td>
                    <td style="text-align:left;">
                        <span class="set-description-popover" 
                              data-toggle="popover" 
                              data-placement="top" 
                              data-html="true" 
                              data-content="' . htmlspecialchars($set['description'], ENT_QUOTES) . '"
                              style="cursor:pointer; color:#555;">
                            ' . htmlspecialchars($description_short) . '
                            <i class="fa fa-info-circle" style="margin-left:5px; color:#007bff;"></i>
                        </span>
                    </td>
                    <td>
                        <input type="checkbox" 
                               class="part-checkbox set-group-checkbox" 
                               data-set-id="' . htmlspecialchars($set['set_id']) . '" 
                               checked>
                    </td>
                </tr>';
        }
    }

    $output .= '</tbody><tr>';
    $output .= '<button id="submitSetOrder" class="btn btn-success mt-2">Submit</button>';
    $output .= '<input type="hidden" id="orderDataHidden" value=\'' . json_encode($orderData) . '\' />';
    $output .= '<style>
        .set-parts-popover:hover, .set-description-popover:hover {
            opacity: 0.8;
        }
        .popover {
            max-width: 400px;
            font-size: 12px;
        }
        .popover-body {
            max-height: 300px;
            overflow-y: auto;
        }
    </style>';

    echo $output;
    exit;
}

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

    $customer_id = 1;
    $check_for_insert = 1;
    $group_id = intval($_REQUEST['group_id'] ?? 0);

   
    $shift_ids = [];
    $result = $conn->query("SELECT id FROM working_hours");
    while ($row = $result->fetch_assoc()) {
        $shift_ids[] = $row['id'];
    }
    $shift_idss = implode(",", $shift_ids);

    
    $orderData = json_decode($_REQUEST['orderData'], true);
    $setorderData = json_decode($_REQUEST['setorderData'], true);
	
	
	
// Remove zero quantity items
$orderData = array_filter($orderData, function($item){
    return isset($item['quantity']) && floatval($item['quantity']) > 0;
});

// Re-index array
$orderData = array_values($orderData);

$product_ids = array_column($orderData, 'groupItemId');
$order_quantities = array_column($orderData, 'quantity');



    
    if (!empty($setorderData)) {
        $set_check = 1;
        $setproduct_ids = array_column($setorderData, 'setItemId');
        $set_ids = array_column($setorderData, 'setId');
        $setproduct_ids_str = implode(",", $setproduct_ids);
        $set_ids_str = implode(",", $set_ids);
    } else {
        $set_check = 0;
        $setproduct_ids_str = '';
        $set_ids_str = '';
    }


$monday = date('Y-m-d', strtotime('monday this week'));

$globalEarliestReqDate = null; 
$production_planning_updates = [];
$selectedCustomerReff = null;

foreach ($orderData as $item) {

    $partId = (int)$item['groupItemId'];
    $availableQty = (float)$item['quantity'];
    $remainingQty = $availableQty;

    $query = "SELECT id, req_qty, produce_qty, status, req_date, customer_reff 
              FROM production_planning 
              WHERE part_id = $partId 
              AND status IN (0,2)
              ORDER BY status DESC, req_date ASC, id ASC";

    $result = mysqli_query($conn, $query);
    $records = [];

    while ($row = mysqli_fetch_assoc($result)) {
        $records[] = $row;
    }

    foreach ($records as $record) {
        if ($remainingQty <= 0) break;

        $recordQty   = (float)$record['req_qty'];
        $alreadyDone = (float)$record['produce_qty'];

        $pendingQty = $recordQty - $alreadyDone;

        // Skip if already fully produced
        if ($pendingQty <= 0) continue;

        if ($remainingQty >= $pendingQty) {

            //FULL FILL
            $producedQty = $pendingQty;
            $remainingQty -= $pendingQty;

            $production_planning_updates[] = [
                'id' => $record['id'],
                'status' => 1
            ];

            $updateQuery = "UPDATE production_planning 
                            SET status = 1, 
                                produce_qty = produce_qty + $producedQty 
                            WHERE id = " . $record['id'];
            mysqli_query($conn, $updateQuery);

        } else {

            //PARTIAL FILL
            $producedQty = $remainingQty;

            $production_planning_updates[] = [
                'id' => $record['id'],
                'status' => 2
            ];

            $updateQuery = "UPDATE production_planning 
                            SET status = 2, 
                                produce_qty = produce_qty + $producedQty 
                            WHERE id = " . $record['id'];
            mysqli_query($conn, $updateQuery);

            $remainingQty = 0;
        }

        // 🔹 Date & customer tracking — captured at the moment we touch the
        // record that sets the new earliest date, so selectedCustomerReff
        // always matches globalEarliestReqDate (not just "whatever record
        // happened to be processed last").
        $currentDate = $record['req_date'];
        $currentcustomer_reff = $record['customer_reff'];

        if ($globalEarliestReqDate === null || $currentDate < $globalEarliestReqDate) {
            $globalEarliestReqDate = $currentDate;
            $selectedCustomerReff = $currentcustomer_reff;
        }
    }
}

$selectedReqDate = $globalEarliestReqDate ?? null;

    function getPreviousWorkingDate($targetDate, $shift_ids, $conn, $days_to_subtract = 2)
    {
        $working_hours = calculateShiftHours($shift_ids, $conn);

        $holidays = [];
        $result = $conn->query("SELECT holiday_date FROM admin_holidays");
        while ($row = $result->fetch_assoc()) {
            $holidays[$row['holiday_date']] = true;
        }

        $date = new DateTime($targetDate);
        $working_days_subtracted = 0;

        while ($working_days_subtracted < $days_to_subtract) {
            $date->modify('-1 day');
            $day_index = (int)$date->format('w');
            $date_str = $date->format('Y-m-d');
            if (isset($holidays[$date_str])) continue;
            if (empty($working_hours[$day_index]) || $working_hours[$day_index] <= 0) continue;
            $working_days_subtracted++;
        }

        return $date->format('Y-m-d');
    }

    $required_date = getPreviousWorkingDate($selectedReqDate, $shift_ids, $conn, 2);

   
    $rr_row = $conn->query("SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_order FROM work_order_customer_ref_mapping")->fetch_assoc();
    $work_order_name = 'order-' . str_pad($rr_row['new_order'], 3, '0', STR_PAD_LEFT);

    
    $query_work_order = "
        INSERT INTO work_order 
        (customer_id, work_order_no, product_id, order_quantity, require_date, set_product_ids, set_ids, shift_ids, group_id)
        VALUES (
            '$selectedCustomerReff',
            '$work_order_name',
            '" . implode(",", $product_ids) . "',
            '" . implode(",", $order_quantities) . "',
            '$selectedReqDate',
            '$setproduct_ids_str',
            '$set_ids_str',
            '$shift_idss',
            '$group_id'
        )";
    $conn->query($query_work_order);
    $work_order_id = $conn->insert_id;
   foreach ($production_planning_updates as $update_record) {
        $updateQuery = "UPDATE production_planning 
                        SET work_order_id = $work_order_id 
                        WHERE id = " . $update_record['id'];
        mysqli_query($conn, $updateQuery);
    }

    foreach ($product_ids as $index => $product_id) {
        $rr_row = $conn->query("SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_customer_ref_mapping")->fetch_assoc();
        $work_order_no = 'CCO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
        $quantity = $order_quantities[$index];
        $conn->query("INSERT INTO work_order_customer_ref_mapping (work_order_no, work_order_id, quantity, product_id) VALUES ('$work_order_no', '$work_order_id', '$quantity', '$product_id')");
    }

   
    $flag = 1;
    processOrderHybrid($product_ids, $order_quantities, $shift_ids, $conn, $required_date, $work_order_id, $flag, $setorderData);

    global $operations;
    $grouped_operations = [];
    foreach ($operations as $operation) {
        $grouped_operations[$operation['product_code']][] = $operation;
    }


	foreach ($grouped_operations as $ops) {
		foreach ($ops as $op) {
			if (in_array($op['process_type'], [6, 4, 12, 21])) {
				$parent_ids = is_array($op['parent_ids']) ? implode(',', $op['parent_ids']) : $op['parent_ids'];

				// 🔹 Add new variables for creation info
				$created_on = date('Y-m-d H:i:s');
				$created_by = $_SESSION['user_id'] ?? 'system'; // change to actual session/user variable

				// ✅ Updated query with created_on & created_by
				$query = "
					INSERT INTO work_order_detail 
					(work_order_id, product_code, product_name, operation_description, product_id, quantity, required_date, process_type, parent_ids, machine, shift_idss, total_time, created_on, created_by)
					VALUES (
						'$work_order_id',
						'{$op['product_code']}',
						'{$op['product_name']}',
						'{$op['operation']}',
						'{$op['product_id']}',
						'{$op['qty']}',
						'{$op['required_date']}',
						'{$op['process_type']}',
						'$parent_ids',
						'{$op['machine']}',
						'$shift_idss',
						'{$op['total_time']}',
						'$created_on',
						'$created_by'
					)";
				$conn->query($query);
			}
		}
	}


    
function normalizeParentIds($parent_ids) {
    if (empty($parent_ids)) return [];

    // Remove unwanted text like "Array,"
    $parent_ids = str_replace('Array,', '', $parent_ids);

    // Split into array
    $ids = array_map('trim', explode(',', $parent_ids));

    // Keep only numeric values
    return array_filter($ids, 'is_numeric');
}

// ------------------------------------------------------
// UPDATE SET ID IN work_order_detail
// ------------------------------------------------------
if ($set_check == 1) {
    foreach ($setorderData as $setitem) {
        $conn->query("
            UPDATE work_order_detail 
            SET set_id = '{$setitem['setId']}' 
            WHERE product_id = '{$setitem['setItemId']}' 
              AND work_order_id = '$work_order_id'
        ");
    }
}

// ------------------------------------------------------
// INSERT INTO MANUFACTURE TABLES
// ------------------------------------------------------
if ($check_for_insert == 1) {

    $result_p = $conn->query("
        SELECT 
            product_id,
            quantity,
            required_date,
            machine,
            shift_idss,
            parent_ids,
            set_id,
            product_name,
            total_time
        FROM work_order_detail
        WHERE process_type = 6
          AND work_order_id = $work_order_id
    ");

    $grouped_data = [];

    while ($row_p = $result_p->fetch_assoc()) {

        $set_id = (int)$row_p['set_id'];
		$product_id = (int)$row_p['product_id'];
        $set_number = '';

       if ($set_id > 0) {
			$setRes = $conn->query("
				SELECT description, set_number 
				FROM set_mangmnt 
				WHERE id = $set_id 
				LIMIT 1
			");

			if ($setRes && $setRes->num_rows > 0) {
				$setRow = $setRes->fetch_assoc();
				$set_number = $setRow['set_number'];
				$description = $setRow['description'];
			}

		} else {
			// Fetch from item_management using product_id
			$itemRes = $conn->query("
				SELECT part_number, product_description
				FROM item_management
				WHERE id = $product_id
				LIMIT 1
			");

			if ($itemRes && $itemRes->num_rows > 0) {
				$itemRow = $itemRes->fetch_assoc();
				$part_number = $itemRow['part_number'];
				$description = $itemRow['product_description'];
			}
		}


        $key = ($set_id > 0) ? "set_$set_id" : "product_{$row_p['product_id']}";

        if (!isset($grouped_data[$key])) {
            $grouped_data[$key] = [
                'work_order_id' => $work_order_id,
                'set_id'        => $set_id,
                'set_number'    => $set_number,
                'product_ids'   => [],
                'highest_qty'   => (float)$row_p['quantity'],
                'data_row'      => $row_p
            ];
        }

        $grouped_data[$key]['product_ids'][] = $row_p['product_id'];

        if ((float)$row_p['quantity'] > $grouped_data[$key]['highest_qty']) {
            $grouped_data[$key]['highest_qty'] = (float)$row_p['quantity'];
            $grouped_data[$key]['data_row'] = $row_p;
        }
    }

    // ------------------------------------------------------
    // INSERT DATA
    // ------------------------------------------------------
    foreach ($grouped_data as $data) {

        $row_p = $data['data_row'];

        // Fetch shift names
        $shift_ids = $row_p['shift_idss'];
        $shift_names = '';
        if (!empty($shift_ids)) {
            $shiftRes = $conn->query("
                SELECT GROUP_CONCAT(shift_name) AS shift_names 
                FROM working_hours 
                WHERE FIND_IN_SET(id, '$shift_ids')
            ");
            $shift_names = $shiftRes->fetch_assoc()['shift_names'];
        }

        // Normalize parent IDs
        $parentIds = normalizeParentIds($row_p['parent_ids']);
        $parent_ids_str = implode(',', $parentIds);

        // Product name handling (Set or Normal)
        $product_name_to_store = ($data['set_id'] > 0)
            ? 'Set-' . $data['set_number']
            : $row_p['product_name'];

        // --------------------------------------------------
        // INSERT INTO manufacture_machine_table
        // --------------------------------------------------
        $conn->query("
    INSERT INTO manufacture_machine_table (
        work_order_id,
        part_id,
        end_date,
        quantity,
        machine_id,
        parent_ids,
        product_name,
        description,
        set_id,
        total_hours
    ) VALUES (
        '{$work_order_id}',
        '{$row_p['product_id']}',
        '{$row_p['required_date']}',
        '{$row_p['quantity']}',
        '{$row_p['machine']}',
        '{$parent_ids_str}',
        '{$product_name_to_store}',
        '".$conn->real_escape_string($description)."',
        '{$row_p['set_id']}',
        '{$row_p['total_time']}'
    )
");

        foreach ($parentIds as $parent_id) {
            $conn->query("
                INSERT INTO manufacture_machine_children (
                    work_order_id,
                    part_id,
                    child_part_id
                ) VALUES (
                    '{$work_order_id}',
                    '{$parent_id}',
                    '{$row_p['product_id']}'
                )
            ");
        }

        // --------------------------------------------------
        // CREATE WORK ORDER NAME
        // --------------------------------------------------
        $rr_row = $conn->query("
            SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_name, 4) AS UNSIGNED)), 0) + 1 AS new_enq 
            FROM work_order_name
        ")->fetch_assoc();

        $new_work_order_name = 'WO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);

        $conn->query("
            INSERT INTO work_order_name (
                work_order_id,
                part_id,
                work_order_name
            ) VALUES (
                '{$work_order_id}',
                '{$row_p['product_id']}',
                '{$new_work_order_name}'
            )
        ");
    }
	// ------------------------------------------------------
// HANDLE CHILD PROCESS TYPE 4 FOR SAME SET
// ------------------------------------------------------

$result_child = $conn->query("
    SELECT 
        id,
        product_id,
        parent_ids
    FROM work_order_detail
    WHERE process_type = 4
      AND work_order_id = $work_order_id
");

while ($child = $result_child->fetch_assoc()) {

    $child_id = $child['id'];
    $parentIds = normalizeParentIds($child['parent_ids']);

    if (!empty($parentIds)) {

        $parent_ids_str = implode(",", $parentIds);

        // Get parent set_id from process_type 6
        $parentRes = $conn->query("
            SELECT set_id
            FROM work_order_detail
            WHERE product_id IN ($parent_ids_str)
              AND process_type = 6
              AND work_order_id = $work_order_id
            LIMIT 1
        ");

        if ($parentRes && $parentRes->num_rows > 0) {

            $parentRow = $parentRes->fetch_assoc();
            $parent_set_id = $parentRow['set_id'];

            // Update child with parent set_id
            $conn->query("
                UPDATE work_order_detail
                SET set_id = '$parent_set_id'
                WHERE id = '$child_id'
            ");
        }		
		
    }
}





// ------------------------------------------------------
// STORE PROCESS_TYPE = 4 IN SEPARATE TABLE (SMART GROUPING)
// ------------------------------------------------------

$result_pt4 = $conn->query("
    SELECT 
        id,
        set_id,
        product_id,
        product_name,
        operation_description,
        quantity,
        required_date
    FROM work_order_detail
    WHERE process_type = 4
      AND work_order_id = $work_order_id
");

$grouped = [];

while ($row = $result_pt4->fetch_assoc()) {

    $set_id = (int)$row['set_id'];

    if ($set_id > 0) {
        // 👉 GROUP BY SET
        $key = "set_" . $set_id . "_" . $row['product_id'];

        if (!isset($grouped[$key])) {
            $grouped[$key] = $row;
            $grouped[$key]['quantity'] = 0;
        }

        $grouped[$key]['quantity'] += (float)$row['quantity'];

        // keep earliest required_date
        if ($row['required_date'] < $grouped[$key]['required_date']) {
            $grouped[$key]['required_date'] = $row['required_date'];
        }

    } else {
        // 👉 NO SET → store individually
        $key = "row_" . $row['id'];
        $grouped[$key] = $row;
    }
}

// ------------------------------------------------------
// INSERT INTO NEW TABLE
// ------------------------------------------------------

foreach ($grouped as $data) {

    $set_id = (int)$data['set_id'];
    $quantity = (float)$data['quantity'];

    // 👉 Apply CEIL ONLY when set exists
    if ($set_id > 0) {
        $quantity = ceil($quantity);
    }

    $product_name = $conn->real_escape_string($data['product_name']);
    $operation_description = $conn->real_escape_string($data['operation_description']);

    $conn->query("
        INSERT INTO work_order_raw_matrial (
            work_order_id,
            set_id,
            product_id,
            product_name,
            operation_description,
            quantity,
			quantity_produce,
            required_date
        ) VALUES (
            '$work_order_id',
            '$set_id',
            '{$data['product_id']}',
            '$product_name',
            '$operation_description',
            '$quantity',
			'$quantity',
            '{$data['required_date']}'
        )
    ");
}









}

    echo json_encode(['status' => 'success', 'message' => 'Order processed successfully!']);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else if(isset($_REQUEST['action']) && $_REQUEST['action']=='work_order_fuction_old'){
    $customer_id =1;
	$check_for_insert = 1;
  
	
    $sql = "SELECT id FROM working_hours";
$result = $conn->query($sql);

$shift_ids = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $shift_ids[] = $row['id'];
    }
}
$shift_idss = implode(",", $shift_ids);
	
    $orderData = json_decode($_REQUEST['orderData'], true);
	
    $product_ids = [];
    $order_quantities = [];

    foreach ($orderData as $item) {
        $product_ids[] = $item['groupItemId'];
        $order_quantities[] = $item['quantity'];
    }
	
$setorderData = json_decode($_REQUEST['setorderData'], true);
   $set_check = 1;

$setproduct_ids = [];
$set_ids = [];

/*if (empty($setorderData)) {
    $set_check = 0; // If $setorderData is empty, set this to 0
} else {
    foreach ($setorderData as $setitem) {
        $setproduct_ids[] = $setitem['setItemId'];
        $set_ids[] = $setitem['setId'];
    }
}*/

if (empty($setorderData)) {
    $set_check = 0; // If $setorderData is empty, set this to 0
    $setproduct_ids_str = '';
    $set_ids_str = '';
} else {
    foreach ($setorderData as $setitem) {
        $setproduct_ids[] = $setitem['setItemId'];
        $set_ids[] = $setitem['setId'];
    }

    // Convert to comma-separated strings
    $setproduct_ids_str = implode(",", $setproduct_ids);
    $set_ids_str = implode(",", $set_ids);
}





/* update production planning status */
$monday = date('Y-m-d', strtotime('monday this week'));

foreach ($orderData as $item) {
    $partId = $item['groupItemId'];
    $availableQty = $item['quantity'];

    $lastMatchedReqDate = null;
    $lastMatchedCustomerReff = null;

    $query = "SELECT * FROM production_planning 
              WHERE part_id = $partId 
              AND status = 0 
              AND req_date >= '$monday' 
              ORDER BY req_date ASC";
    $result = mysqli_query($conn, $query);

    while ($row = mysqli_fetch_assoc($result)) {
        $planningId = $row['id'];
        $reqQty = $row['req_qty'];
        $reqDate = $row['req_date'];
        $customerReff = $row['customer_reff'];

        if ($availableQty >= $reqQty) {
            $update = "UPDATE production_planning SET status = 0 WHERE id = $planningId";
            mysqli_query($conn, $update);

            $availableQty -= $reqQty;

            // Store last matched info
            $lastMatchedReqDate = $reqDate;
            $lastMatchedCustomerReff = $customerReff;
        } else {
            continue;
        }
    } 
}
/* end update production planning status */
 if ($lastMatchedReqDate !== null && $lastMatchedCustomerReff !== null) {
      $customer_id =$lastMatchedCustomerReff;
        $require_dateet = $lastMatchedReqDate;
	   }

 
	//$set_check = '1';
     $required_date = date('Y-m-d', strtotime($lastMatchedReqDate . ' -2 days'));
	// $required_date = date('Y-m-d', strtotime('2025-09-25'));
	function getPreviousWorkingDate($targetDate, $shift_ids, $conn, $days_to_subtract = 2) {
    // Get working hours per day (Mon–Sun)
    $working_hours = calculateShiftHours($shift_ids, $conn);
    
    // Get list of holidays
    $holiday_query = "SELECT holiday_date FROM admin_holidays";
    $holiday_result = $conn->query($holiday_query);
    $holidays = [];
    if ($holiday_result && $holiday_result->num_rows > 0) {
        while ($row = $holiday_result->fetch_assoc()) {
            $holidays[] = $row['holiday_date'];
        }
    }

    $date = new DateTime($targetDate);
    $working_days_subtracted = 0;

    // Move backward until 2 working days are subtracted
    while ($working_days_subtracted < $days_to_subtract) {
        $date->modify('-1 day');
        $day_index = (int) $date->format('w'); // 0=Sunday, 6=Saturday
        $date_str = $date->format('Y-m-d');

        // Skip if holiday or no working hours
        if (in_array($date_str, $holidays)) {
            continue;
        }
        if (!isset($working_hours[$day_index]) || $working_hours[$day_index] <= 0) {
            continue;
        }

        // Valid working day → count it
        $working_days_subtracted++;
    }

    return $date->format('Y-m-d');
}

// Use this function instead of direct strtotime
$required_date = getPreviousWorkingDate($require_dateet, $shift_ids, $conn, 2);



	$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_order FROM work_order_customer_ref_mapping");
	$rr_row = mysqli_fetch_assoc($rr_query);
	$work_order_name = 'order-' . str_pad($rr_row['new_order'], 3, '0', STR_PAD_LEFT);
   // $work_order_no = "coo767"; 


    /*$query_work_order = "INSERT INTO work_order (customer_id, work_order_no, product_id, order_quantity, require_date, setorderData, shift_ids) 
          VALUES ('$customer_id', '$work_order_name', '" . implode(",", $product_ids) . "', '" . implode(",", $order_quantities) . "', '$required_date', '$$setorderData', '$shift_idss')";*/
		  
		  
		  $query_work_order = "INSERT INTO work_order 
    (customer_id, work_order_no, product_id, order_quantity, require_date, set_product_ids, set_ids, shift_ids) 
    VALUES (
        '$customer_id', 
        '$work_order_name', 
        '" . implode(",", $product_ids) . "', 
        '" . implode(",", $order_quantities) . "', 
        '$lastMatchedReqDate', 
        '$setproduct_ids_str',
        '$set_ids_str',
        '$shift_idss'
    )";
		  
		  
    $conn->query($query_work_order);
    $work_order_id = mysqli_insert_id($conn);
	
	
	
	
	foreach ($product_ids as $index => $product_id) {

		$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_customer_ref_mapping");
		$rr_row = mysqli_fetch_assoc($rr_query);
		$work_order_no = 'CCO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
		$quantity = $order_quantities[$index];

		 $insert_query = "INSERT INTO work_order_customer_ref_mapping (work_order_no, work_order_id, quantity, product_id) VALUES ('$work_order_no', '$work_order_id', '$quantity', '$product_id')";
		mysqli_query($conn, $insert_query);
    }
	

    $flag = 1;
    
    processOrderHybrid($product_ids, $order_quantities, $shift_ids, $conn, $required_date, $work_order_id, $flag, $setorderData);
    $grouped_operations = [];

    foreach ($operations as $operation) {
          $grouped_operations[$operation['product_code']][] = [
        'description' => $operation['operation'],
		'product_name' => $operation['product_name'],
        'product_id' => $operation['product_id'] ?? null,
        'quantity' => $operation['qty'] ?? 0,
		'process_type' => $operation['process_type'] ?? 0,
		'machine' => $operation['machine'] ?? 0,
		'Start_Date' => $operation['Start_Date'] ?? null,
        'required_date' => $operation['required_date'] ?? null,
		'parent_ids' => $operation['parent_ids'] ?? 0,
		'highlight' => $operation['highlight'] ?? 0,
		'total_time' => $operation['total_time'] ?? 0,
		'p_name' => $operation['p_name'] ?? null,
		'allocated_dates' => $operation['allocated_dates'] ?? null
    ];
    }

    foreach ($grouped_operations as $product_code => $ops) {
        foreach ($ops as $op) {
            $operation_description = $op['description'];
            $product_name = $op['product_name'];
            $product_id = $op['product_id'] ?? null; 
            $quantity = $op['quantity'] ?? 0;
            $process_type = $op['process_type'] ?? 0;
            $machine = $op['machine'] ?? 0;
            $Start_Date = $op['Start_Date'] ?? null;
            $required_datee = $op['required_date'] ?? null;
			$highlight = $op['highlight'] ?? 0;
			$total_time = $op['total_time'] ?? 0;
			$allocated_dates = $op['allocated_dates'] ?? null;
            $parent_ids = implode(', ', $op['parent_ids']) ?? 0;

         /*   if ($process_type == 6) {
                $rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_name, 4) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_name");
                $rr_row = mysqli_fetch_assoc($rr_query);
                
                $work_order_name = 'WO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
                
                $query = "INSERT INTO work_order_name (work_order_id, part_id, work_order_name) 
                  VALUES ($work_order_id, $product_id, '$work_order_name')";
                $conn->query($query);
            }
        */
           
			
	if ($process_type == 6 || $process_type == 4 || $process_type == 12 || $process_type == 21) {
 
		 $parent_ids = str_replace("Array,", "", $parent_ids);
       $query = "INSERT INTO work_order_detail (work_order_id, product_code, product_name, operation_description, product_id, quantity, required_date, process_type, parent_ids, machine, shift_idss, total_time) 
                  VALUES ($work_order_id, '$product_code', '$product_name', '$operation_description', '$product_id', $quantity, '$required_datee', '$process_type', '$parent_ids', '$machine', '$shift_idss', '$total_time')";

        $conn->query($query);
    }
	/*	if ($process_type === 7) {  
	  if ($highlight === 131){
		   $sql = "UPDATE work_order_detail SET end_date = '$allocated_dates' WHERE product_id = $product_id And work_order_id = $work_order_id ";


    $conn->query($sql);  
		  
	  }	  
	 /* if ($highlight === 121){
		   $sql = "UPDATE work_order_detail SET check_date = '$allocated_dates' WHERE product_id = $product_id And work_order_id = $work_order_id ";


    $conn->query($sql);  
		  
	  }
    
}*/




        }
    }
	
	
	
	
if ($set_check == 1) { 
     foreach ($setorderData as $setitem) {
        $setproduct_ids[] = $setitem['setItemId'];
        $set_ids[] = $setitem['setId'];
		
		$sql_for_set = "UPDATE work_order_detail SET set_id = '" . $setitem['setId'] . "' WHERE product_id = " . $setitem['setItemId'] . " AND work_order_id = $work_order_id";

		$conn->query($sql_for_set);
    }
}



if ($check_for_insert == 1) {	
$query_p = "
    SELECT 
        product_id, quantity, required_date, end_date, check_date, 
        machine, shift_idss, parent_ids, set_id, set_part, 
        product_name, total_time 
    FROM work_order_detail 
    WHERE process_type = 6 
      AND work_order_id = $work_order_id
";
$result_p = $conn->query($query_p);

$grouped_data = [];

if ($result_p && $result_p->num_rows > 0) {
    while ($row_p = $result_p->fetch_assoc()) {
        $set_id = intval($row_p['set_id']);
        $key = ($set_id > 0) ? 'set_' . $set_id : 'product_' . $row_p['product_id'];

        // Initialize group if not exists
        if (!isset($grouped_data[$key])) {
            $grouped_data[$key] = [
                'work_order_id' => $work_order_id,
                'set_id'        => $set_id,
                'product_ids'   => [],
                'highest_qty'   => floatval($row_p['quantity']),
                'data_row'      => $row_p, // store entire row for highest qty
            ];
        }

        // Always add to list
        $grouped_data[$key]['product_ids'][] = $row_p['product_id'];

        // If current product has higher quantity, replace stored info
        if (floatval($row_p['quantity']) > $grouped_data[$key]['highest_qty']) {
            $grouped_data[$key]['highest_qty'] = floatval($row_p['quantity']);
            $grouped_data[$key]['data_row'] = $row_p;
        }
    }

    // Insert grouped results
    foreach ($grouped_data as $key => $data) {
        $row_p = $data['data_row']; // pick the row with highest quantity
        $shift_ids = $row_p['shift_idss'];

        // Convert shift IDs → names
        $sql = "SELECT GROUP_CONCAT(shift_name) AS shift_names 
                FROM working_hours 
                WHERE FIND_IN_SET(id, '$shift_ids')";
        $result = $conn->query($sql);
        $row    = $result->fetch_assoc();
        $shift_names = $row['shift_names'];

        // Handle children
        $child_ids = [];
        $product_list = implode(',', $data['product_ids']);

        $child_query = "
            SELECT product_id AS child_id
            FROM work_order_detail
            WHERE parent_ids IN ($product_list)
              AND work_order_id = $work_order_id
        ";
        $child_result = $conn->query($child_query);
        if ($child_result && $child_result->num_rows > 0) {
            while ($row_c = $child_result->fetch_assoc()) {
                $child_ids[] = $row_c['child_id'];
            }
        }

        // Insert into manufacture_machine_children
        foreach ($data['product_ids'] as $pid) {
            foreach ($child_ids as $child_id) {
                $conn->query("
                    INSERT INTO manufacture_machine_children (work_order_id, part_id, child_part_id)
                    VALUES ('{$work_order_id}', '{$pid}', '{$child_id}')
                ");
            }
        }

        // Final insert
        $child_ids_str = implode(',', $child_ids);
        $product_name_to_store = ($data['set_id'] > 0)
            ? 'Set-' . $data['set_id']
            : $row_p['product_name']; // Changed from 'Product-' . implode(',', $data['product_ids'])

        $query_insert = "
            INSERT INTO manufacture_machine_table 
                (work_order_id, part_id, start_date, end_date, check_date, quantity, 
                 machine_id, shift_ids, parent_ids, child_ids, product_name, 
                 set_id, set_part, total_hours)
            VALUES 
                ('{$work_order_id}', '{$row_p['product_id']}', '{$row_p['end_date']}', 
                 '{$row_p['required_date']}', '{$row_p['check_date']}', '{$row_p['quantity']}', 
                 '{$row_p['machine']}', '{$shift_names}', '{$row_p['parent_ids']}', 
                 '{$child_ids_str}', '{$product_name_to_store}', 
                 '{$row_p['set_id']}', '{$row_p['set_part']}', '{$row_p['total_time']}')
        ";
        $conn->query($query_insert);
		$rr_query = mysqli_query($conn, "
			SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_name, 4) AS UNSIGNED)), 0) + 1 AS new_enq 
			FROM work_order_name
		");
		$rr_row = mysqli_fetch_assoc($rr_query);

		$new_work_order_name = 'WO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);

		$insert_wo_name = "
			INSERT INTO work_order_name (work_order_id, part_id, work_order_name)
			VALUES ('{$work_order_id}', '{$row_p['product_id']}', '{$new_work_order_name}')
		";
		$conn->query($insert_wo_name);
    }
}
}






	echo json_encode(['status' => 'success', 'message' => 'Order processed successfully!']);

}





?>
<?php
/*
include("../../../include/startup.php"); 
include("work_order_function.inc.php");

if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_po_item'){
	$returnArray = array();
	$po_item_mapping_id = $_REQUEST['po_item_mapping_id'];
	$delete_sql = "DELETE FROM purchase_order_items_mapping WHERE id = '$po_item_mapping_id'";
	if(mysqli_query($conn,$delete_sql)){
		$returnArray["status"] = "success";
	}else{
		$returnArray["status"] = "failure";
	}
	
echo json_encode($returnArray);
die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_group_items'){
		$part_id = $_POST['part_id'];
		$query = "SELECT g.part_number FROM group_mangmnt_mapping g WHERE g.group_id = (SELECT group_id FROM group_mangmnt_mapping WHERE part_number = $part_id)";
		$result = mysqli_query($conn, $query);

		$output = '<table class="table">
						<tr><th>Part Number</th><th>Quantity</th></tr>';

		while ($row = mysqli_fetch_assoc($result)) {
			$output .= '<tr class="group-item-row" data-group-item-id="' . $row['part_number'] . '">
							<td>' . $row['part_number'] . '</td>
							<td><input type="number" class="group-item-qty form-control" min="1" value="1"></td>
						</tr>';
		}

		$output .= '</table>';
		$output .= '<button id="submitGroupOrder" class="btn btn-success">Submit</button>';

		echo $output;
die;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='work_order_fuction'){

    $require_datee = '2025-04-24';
    $required_date = date('Y-m-d', strtotime($require_datee . ' -2 days'));
	
    $shift_ids = [7,8,9,10,11,15,16,17,18,19,20,21];
    $shift_idss = implode(",", $shift_ids);
	
    $orderData = json_decode($_POST['orderData'], true);
	
    $product_ids = [];
    $order_quantities = [];

    foreach ($orderData as $item) {
        $product_ids[] = $item['groupItemId'];
        $order_quantities[] = $item['quantity'];
    }
	
	
	
	
	
	
	
	
    $work_order_no = "coo767"; 





	
    
    // Insert work order
    $query_work_order = "INSERT INTO work_order (customer_id, work_order_no, product_id, order_quantity, require_date, shift_ids) 
          VALUES ('$customer_id', '$work_order_no', '" . implode(",", $product_ids) . "', '" . implode(",", $order_quantities) . "', '$require_datee', '$shift_idss')";
    $conn->query($query_work_order);
    $work_order_id = mysqli_insert_id($conn);
	
	
	
	
	foreach ($product_ids as $index => $product_id) {
    // Generate new work_order_no for each product_id
    $rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_customer_ref_mapping");
    $rr_row = mysqli_fetch_assoc($rr_query);
    $work_order_no = 'CCO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
    $quantity = $order_quantities[$index];
    // Insert new work_order_no along with product_id and quantity into the table
     $insert_query = "INSERT INTO work_order_customer_ref_mapping (work_order_no, work_order_id, quantity) VALUES ('$work_order_no', '$work_order_id', '$quantity')";
    mysqli_query($conn, $insert_query);
    }
	
	
	
	
	
	

    $flag = 1;
    
    // Process all products simultaneously
    processOrderHybrid($product_ids, $order_quantities, $shift_ids, $conn, $required_date, $work_order_id, $flag);
    $grouped_operations = [];

    foreach ($operations as $operation) {
        $grouped_operations[$operation['product_code']][] = [
            'description' => $operation['operation'],
            'product_name' => $operation['product_name'],
            'product_id' => $operation['product_id'] ?? null,
            'quantity' => $operation['qty'] ?? 0,
            'process_type' => $operation['process_type'] ?? 0,
            'machine' => $operation['machine'] ?? 0,
            'Start_Date' => $operation['Start_Date'] ?? null,
            'required_date' => $operation['required_date'] ?? null,
            'parent_ids' => $operation['parent_ids'] ?? 0,
            'p_name' => $operation['p_name'] ?? null
        ];
    }

    foreach ($grouped_operations as $product_code => $ops) {
        foreach ($ops as $op) {
            $operation_description = $op['description'];
            $product_name = $op['product_name'];
            $product_id = $op['product_id'] ?? null; 
            $quantity = $op['quantity'] ?? 0;
            $process_type = $op['process_type'] ?? 0;
            $machine = $op['machine'] ?? 0;
            $Start_Date = $op['Start_Date'] ?? null;
            $required_datee = $op['required_date'] ?? null;
            $parent_ids = implode(', ', $op['parent_ids']) ?? 0;

            if ($process_type == 6) {
                $rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_name, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_name");
                $rr_row = mysqli_fetch_assoc($rr_query);
                
                $work_order_name = 'WO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
                
                $query = "INSERT INTO work_order_name (work_order_id, part_id, work_order_name) 
                  VALUES ($work_order_id, $product_id, '$work_order_name')";
                $conn->query($query);
            }

           
			
	if ($process_type == 6 || $process_type == 4 || $process_type == 12 || $process_type == 21) {
        // Prepare the SQL query
		 $parent_ids = str_replace("Array,", "", $parent_ids);
       $query = "INSERT INTO work_order_detail (work_order_id, product_code, product_name, operation_description, product_id, quantity, required_date, process_type, parent_ids, machine, shift_idss) 
                  VALUES ($work_order_id, '$product_code', '$product_name', '$operation_description', '$product_id', $quantity, '$required_date', '$process_type', '$parent_ids', '$machine', '$shift_idss')";

        // Execute the query
        $conn->query($query);
    }
        }
    }

	echo json_encode(['status' => 'success', 'message' => 'Order processed successfully!']);

}



*/

?>