<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name      = "index?page=view";
$form_action    = "insert";
$button_value   = "Add";
$table_name     = "work_order";
$id = "";
$page_name      = "Edit Work Order";
$from = $_REQUEST['from'] ?? "";

// --- START INSERT ---
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){    
    utility::addslashesOnAllInput(array("query_string","engineer_id"));
    $holiday_name       = $_REQUEST['holiday_name'];
    $from_date          = utility::setFormatedDate($_REQUEST['from_date']);
    $to_date            = utility::setFormatedDate($_REQUEST['to_date']);
    $holiday_type_id    = $_REQUEST['holiday_type_id'];
    $engineer_id        = implode(",",$_REQUEST['engineer_id']); 
    $created_by         = $_SESSION['user_id'];
    $created_on         = date("Y-m-d H:i:s");    
    $updated_by         = $_SESSION['user_id'];

    $sql = "holiday_name = '".$holiday_name."', from_date = '".$from_date."',to_date = '".$to_date."',holiday_type_id = '".$holiday_type_id."', engineer_id = '".$engineer_id."',created_on = '".$created_on."', created_by = '".$created_by."', updated_by = '".$updated_by."'";
    $sql= "INSERT INTO $table_name SET ".$sql;
    mysqli_query($conn,$sql);
    $holiday_id = mysqli_insert_id($conn);
    
    if(count($_REQUEST['engineer_id']) > 0){
        foreach($_REQUEST['engineer_id'] as $engineer_id){
            $sql_engineertype_insert= "INSERT INTO engineer_type_mapping (holiday_id,engineer_id,created_by,created_on,updated_by) VALUES('$holiday_id','$engineer_id','$created_by','$created_on','$updated_by')";            
            mysqli_query($conn,$sql_engineertype_insert);
        }
    }
    
    $_SESSION['info_message'] = "Holiday added successfully";
    header("Location: $file_name");
    exit();
}

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
    $id = $_REQUEST['id'];
    $form_action  = "update";
    $button_value = "Update";
    $page_name    = "Edit Work Order";
    $query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];

    $sql = "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn, $sql);
    $row_edit = mysqli_fetch_array($result_edit);
    $row_edit = utility::validate_crypt_data($row_edit);

    $customer_id    = $row_edit['customer_id'];
    $product_id     = $row_edit['product_id'];
    $order_quantity = $row_edit['order_quantity'];
    $required_date  = $row_edit['require_date'];
    $shift_id       = explode(",", $row_edit['shift_ids']);
}
// --- END EDIT ---

// --- START UPDATE ---
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update') {

  echo   $id = $_REQUEST['id'];
  echo  $work_order_id = $_REQUEST['id'];
  

    // Incoming data
    $product_ids = $_REQUEST['product_id'];       // Array
    $order_quantities = $_REQUEST['order_quantity']; // Array
    $require_datee = utility::setFormatedDate($_REQUEST['required_date']);

    $updated_by = $_SESSION['user_id'] ?? 'system';
    $check_for_insert = 1;

    include("work_order_function.inc.php");

    // 🔹 Function to calculate previous working date
    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');
    }

    // 🔹 Compute Required Date
    $sql_shift = "SELECT id FROM working_hours";
    $result_result = $conn->query($sql_shift);
    $shift_ids = [];
    while ($row = $result_result->fetch_assoc()) {
        $shift_ids[] = $row['id'];
    }
    $shift_idss = implode(",", $shift_ids);

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

    // 🔹 Fetch data for update process
    $workOrderData = getWorkOrderDataForEdit($id, $conn);
    $setorderData = $workOrderData['setorderData'];

    // 🔹 Update work_order main record
    echo $sql_update = "
        UPDATE $table_name SET 
            require_date = '$require_datee',
            updated_by = '$updated_by'
        WHERE id = '$id'";

    mysqli_query($conn, $sql_update);

    // 🔹 Update work_order_customer_ref_mapping
  // Loop through each product and its corresponding quantity
if (!empty($product_ids) && !empty($order_quantities)) {
    foreach ($product_ids as $index => $product_id) {
        $quantity = $order_quantities[$index] ?? 0;
        $product_id = (int)$product_id;

        // Update each product's quantity
        $update_query = "
            UPDATE work_order_customer_ref_mapping 
            SET quantity = '$quantity' 
            WHERE work_order_id = '$work_order_id' 
              AND product_id = '$product_id'
        ";

        mysqli_query($conn, $update_query);

        echo "<p>🔄 Updated work_order_customer_ref_mapping → Product ID: <b>$product_id</b>, Quantity: <b>$quantity</b></p>";
    }
}


    // 🔹 Recalculate operations using hybrid process logic
    $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
        ];
    }

    // 🔹 Debug log (DO NOT REMOVE)
    echo "<h4>Levels Log:</h4>";
    foreach ($grouped_operations as $product_code => $ops) {
        echo "<h3>Level for $product_code:</h3><ul>";
        foreach ($ops as $op) {
            echo "<li>{$op['description']} (Qty: {$op['quantity']}, parent_iddddd: " . implode(', ', $op['parent_ids']) . ", Required Date: {$op['required_date']}, P_name: {$op['p_name']}, total_time: {$op['total_time']}, process_type: {$op['process_type']})</li>";

            $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;

            // ✅ Update only for key process types
            if (in_array($process_type, [6, 4, 12, 21])) {
                $parent_ids = str_replace("Array,", "", $parent_ids);
                $created_on = date('Y-m-d H:i:s');
                $created_by = $updated_by;

                // ✅ Update existing record (if exists)
                $check_exist = $conn->query("SELECT id FROM work_order_detail WHERE work_order_id = $work_order_id AND product_id = '$product_id'");
                if ($check_exist->num_rows > 0) {
                    // Update existing record
					echo "<br>";
                echo    $query = "
                        UPDATE work_order_detail 
                        SET 
                            product_code = '$product_code',
                            product_name = '$product_name',
                            operation_description = '$operation_description',
                            quantity = $quantity,
                            required_date = '$required_datee',
                            process_type = '$process_type',
                            parent_ids = '$parent_ids',
                            machine = '$machine',
                            shift_idss = '$shift_idss',
                            total_time = '$total_time',
                            updated_on = '$created_on',
                            updated_by = '$created_by'
                        WHERE work_order_id = $work_order_id 
                          AND product_id = '$product_id'";
						  $conn->query($query);
                } else {
                    // Insert new record if it doesn't exist
                    $parent_ids_clean = is_array($parent_ids) ? implode(',', $parent_ids) : $parent_ids;
                    echo "<br>";
                    echo $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',
                            '$product_code',
                            '$product_name',
                            '$operation_description',
                            '$product_id',
                            '$quantity',
                            '$required_datee',
                            '$process_type',
                            '$parent_ids_clean',
                            '$machine',
                            '$shift_idss',
                            '$total_time',
                            '$created_on',
                            '$created_by'
                        )";
                    $conn->query($query);
                } 

                
            }
        }
        echo "</ul>";
    }
	
	    if ($check_for_insert == 1) {
        echo "<h3>🔁 Updating manufacture_machine_table and work_order_name...</h3>";

        // Fetch process_type = 6 operations
        $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 = '';
            $description = '';

            // Fetch set_number and description based on set_id
            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,
                    'description' => $description,
                    '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;
            }
        }

        // Update records
        foreach ($grouped_data as $data) {
            $row_p = $data['data_row'];
            $shift_ids = $row_p['shift_idss'];

            // Get shift names
            $shift_result = $conn->query("SELECT GROUP_CONCAT(shift_name) AS shift_names FROM working_hours WHERE FIND_IN_SET(id, '$shift_ids')");
            $shift_row = $shift_result->fetch_assoc();
            $shift_names = $shift_row['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'];

            $updated_on = date('Y-m-d H:i:s');
            $updated_by = $_SESSION['user_id'] ?? 'system';

            // 🔹 Update manufacture_machine_table
			echo "<br>";
       echo     $update_sql = "
                UPDATE manufacture_machine_table 
                SET 
                    end_date = '{$row_p['required_date']}',
                    quantity = '{$row_p['quantity']}',
                    machine_id = '{$row_p['machine']}',
                    parent_ids = '{$parent_ids_str}',
                    product_name = '{$product_name_to_store}',
                    description = '".$conn->real_escape_string($data['description'])."',
                    set_id = '{$row_p['set_id']}',
                    total_hours = '{$row_p['total_time']}'
                WHERE work_order_id = '{$work_order_id}'
                  AND part_id = '{$row_p['product_id']}'
            ";

            $conn->query($update_sql);
            echo "<p>✅ Updated manufacture_machine_table for part_id: <b>{$row_p['product_id']}</b></p>";

            // 🔹 Update manufacture_machine_children
            // First, delete existing children for this part
            $conn->query("
                DELETE FROM manufacture_machine_children 
                WHERE work_order_id = '{$work_order_id}' 
                  AND part_id = '{$row_p['product_id']}'
            ");

            // Insert new children
            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']}'
                    )
                ");
            }

        }

        echo "<br><b>✅ All manufacture_machine_table & work_order_name records updated successfully!</b>";
    }

    // 🔹 Update SET ID in work_order_detail
    $set_check = 1; // Assuming set check is enabled for edit
    if ($set_check == 1 && !empty($setorderData)) {
        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'
            ");
        }
    }

    echo "<br><b>Update completed successfully!</b>";
	 $_SESSION['info_message'] = "Work Order updated successfully";
    header("Location: $file_name");
    exit();
}

// ------------------------------------------------------
// HELPER FUNCTION: Normalize Parent IDs
// ------------------------------------------------------
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');
}

// --- END UPDATE ---

function getWorkOrderDataForEdit($work_order_id, $conn) {
    $orderData = [];
    $setorderData = [];

    $work_order_id = (int)$work_order_id;

    $orderQuery = "SELECT product_id, quantity FROM work_order_customer_ref_mapping WHERE work_order_id = $work_order_id";
    $orderResult = mysqli_query($conn, $orderQuery);
    if ($orderResult) {
        while ($orderRow = mysqli_fetch_assoc($orderResult)) {
            $orderData[] = [
                'groupItemId' => $orderRow['product_id'],
                'quantity' => (int)$orderRow['quantity']
            ];
        }
    }

    $setQuery = "SELECT set_product_ids, set_ids FROM work_order WHERE id = $work_order_id";
    $setResult = mysqli_query($conn, $setQuery);
    if ($setResult && $setRow = mysqli_fetch_assoc($setResult)) {
        $set_product_ids = array_filter(explode(',', $setRow['set_product_ids']));
        $set_ids = array_filter(explode(',', $setRow['set_ids']));
        foreach ($set_product_ids as $index => $product_id) {
            if (isset($set_ids[$index])) {
                $setorderData[] = [
                    'setItemId' => trim($product_id),
                    'setId' => trim($set_ids[$index])
                ];
            }
        }
    }

    return [
        'orderData' => $orderData,
        'setorderData' => $setorderData
    ];
}
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<style>
em { color:red; font-size: 20px; position: absolute; }
.product-row { background: #f9f9f9; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; border-radius: 8px; }
.remove-btn { float: right; color: red; cursor: pointer; font-weight: bold; }
</style>

<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1><?= $page_name; ?></h1>
            </div>
            <div class="col-sm-6">
            <?php
            $query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
            if(isset($from) && $from == "view_holiday_details"){
                $query_string = str_ireplace("page=add", "page=view_holiday_details", $query_string);
            } else {
                $query_string = str_ireplace("page=edit_work_order", "page=view", $query_string);
            }
            ?>
            <button type="button" id="back" class="btn btn-success" style="float:right;margin-right:5px;margin-bottom:8px;" onclick="window.location.href = 'index?<?= $query_string; ?>'">Back</button>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="row">
        <div class="col-12">
            <?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 } ?>

            <div class="card">
                <form method="post" name="form1" id="form1" action="index?page=edit_work_order&action=<?= $form_action; ?>" enctype="multipart/form-data">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-lg-12 col-sm-12">
                                <div class="form-group">
                                    <label>Customer <em>*</em></label>
                                    <?php $gsi->getCustomerList("customer_id",$customer_id,"100%",false,"form-control select2 customer_id",""); ?>
                                </div>

                                <!-- Dynamic Product List -->
                                <h5 class="mt-3 mb-2">Products</h5>
                                <div id="productContainer">
                                    <?php 
                                    $workOrderData = getWorkOrderDataForEdit($id, $conn);
                                    $orderData = $workOrderData['orderData'];

                                    if (!empty($orderData)) {
                                        foreach ($orderData as $index => $item) {
                                            $productId = $item['groupItemId'];
                                            $quantity  = $item['quantity'];
                                    ?>
                                    <div class="product-row">
                                        <span class="remove-btn" onclick="this.parentNode.remove();">&times;</span>
                                        <div class="form-group">
                                            <label>Product ID <em>*</em></label>
                                            <?php 
                                            $gsi->getworkItemList("product_id[]",$productId,"100%",false,"form-control select2 product_id","");
                                            ?>
                                        </div>
                                        <div class="form-group">
                                            <label>Order Quantity <em>*</em></label>
                                            <input type="number" class="form-control" name="order_quantity[]" value="<?= $quantity; ?>" placeholder="Order Quantity" autocomplete="off">
                                        </div>
                                    </div>
                                    <?php 
                                        }
                                    } else { 
                                    ?>
                                    <div class="product-row">
                                        <span class="remove-btn" onclick="this.parentNode.remove();">&times;</span>
                                        <div class="form-group">
                                            <label>Product ID <em>*</em></label>
                                            <?php $gsi->getworkItemList("product_id[]","100%",false,"form-control select2 product_id",""); ?>
                                        </div>
                                        <div class="form-group">
                                            <label>Order Quantity <em>*</em></label>
                                            <input type="number" class="form-control" name="order_quantity[]" value="" placeholder="Order Quantity" autocomplete="off">
                                        </div>
                                    </div>
                                    <?php } ?>
                                </div>
                                <!--<button type="button" class="btn btn-sm btn-success" id="addProductRow">+ Add Product</button>-->

                                <div class="form-group"> <label class="control-label" for="Required Date">Required Date<em></em></label> <div> <input type="text" class="form-control datepicker" id="required_date" name="required_date" value="<?php echo (isset($required_date) && $required_date != "") ? utility::getFormatedDate($required_date) : ""; ?>" placeholder="DD-MM-YYYY" autocomplete="off"> </div> </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-footer">
                        <input type="hidden" name="id" value="<?= $id; ?>">
                        <input type="hidden" name="from" value="<?= $from; ?>">
                        <input type="hidden" name="query_string" value="<?= $query_string; ?>">
                        <button type="submit" class="btn btn-primary"><?= $button_value; ?>
                            <i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>

<script>
//flatpickr(".datepicker", { dateFormat: "d-m-Y" });

document.getElementById('addProductRow').addEventListener('click', function () {
    const container = document.getElementById('productContainer');
    const newRow = container.firstElementChild.cloneNode(true);

    newRow.querySelectorAll('input').forEach(i => i.value = '');
    container.appendChild(newRow);
});
</script>
