<?php
session_start();
include "config.php";

// Include shared order processing functions
require_once 'order_processing_functions.php';

$file_name   = "index?page=view";
$form_action = "insert";
$button_value = "Add";
$page_name = "Add Production Planning";

$id = "";
$created_on = date("Y-m-d H:i:s");
$created_by = $_SESSION['engineer_id'] ?? 0;
$updated_by = $_SESSION['engineer_id'] ?? 0;

/* ================= INSERT ================= */
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert') {
    
    // Get shift IDs for processOrderHybrid
    $shift_ids = [];
    $shift_result = $conn->query("SELECT id FROM working_hours");
    if ($shift_result) {
        while ($shift_row = $shift_result->fetch_assoc()) {
            $shift_ids[] = (int)$shift_row['id'];
        }
    }
    
    // Initialize set_ids (empty for now, can be enhanced later)
    $set_ids = [];
    
    // Initialize global operations array
    global $operations;
    $operations = [];
    
    if(count($_REQUEST['part_id']) > 0){
        foreach($_REQUEST['part_id'] as $key => $part_id){
            
            if($part_id != ""){
                $customer_id    = intval($_POST['customer_reff'][$key]);
                $ReqDate_Date   = $_POST['req_date'][$key];
				$item_price   = floatval($_POST['item_price'][$key]);
                $ReqQty         = intval($_POST['req_qty'][$key]);
                $RefSalesCode   = mysqli_real_escape_string($conn, $_POST['RefSalesCode'][$key]);

                $sql = "
                    INSERT INTO production_planning 
					SET part_id='$part_id',
						customer_reff='$customer_id',
						req_date='$ReqDate_Date',
						req_qty='$ReqQty',
						item_price='$item_price',         
						RefSalesCode='$RefSalesCode',
						created_on='$created_on',
						created_by='$created_by',
						updated_by='$updated_by'
                ";

                if(mysqli_query($conn, $sql)){
                    $last_id = mysqli_insert_id($conn);
                    $work_order_id = $last_id;
                    
                    // Calculate required date (2 working days before req_date)
                    $required_date = getPreviousWorkingDate($ReqDate_Date, $shift_ids, $conn, 2);
                    
                    // Call processOrderHybrid for BOM explosion, purchase list, and routing
                    processOrderHybrid(
                        [$part_id],
                        [$ReqQty],
                        $shift_ids,
                        $conn,
                        $required_date,
                        $work_order_id,
                        1, // simulateOnly = 1 to insert into purchase_list
                        $set_ids
                    );
                }
            }
        }
    }

    $_SESSION['info_message'] = "Production planning added successfully";
    header("Location: $file_name");
    exit();
}
?>

<style>
em{color:red;font-size: 20px;position: absolute;}
</style>

<!-- Hidden Template for Cloning -->
<div class="col-sm-12 col-lg-12 col-12" id="production_div_to_clone" style="display:none;">
    <div class="row">
        <div class="col-sm-2"> 
            <label class="control-label" for="Part">&nbsp;<em></em></label> 
            <?= $gsi->getPartNumberList("part_id[]", "", "100%", false, "form-control select2 part_select", "required"); ?>
        </div>
        <div class="col-sm-2"> 
            <label class="control-label" for="Customer">&nbsp;<em></em></label> 
            <?= $gsi->getCustomercodeListNew("customer_reff[]", "", "100%", false, "form-control select2", "required"); ?>
        </div>
        <div class="col-sm-1"> 
            <label class="control-label" for="Price">&nbsp;<em></em></label> 
            <input type="text" class="form-control item_price" name="item_price[]" placeholder="Price">
        </div>
        <div class="col-sm-2"> 
            <label class="control-label" for="Required Date">&nbsp;<em></em></label>   
            <input type="date" class="form-control" name="req_date[]" required>
        </div>
        <div class="col-sm-1"> 
            <label class="control-label" for="Required Qty">&nbsp;<em></em></label> 
            <input type="number" class="form-control" name="req_qty[]" min="1" placeholder="Required Qty" required>
        </div>
        <div class="col-sm-3"> 
            <label class="control-label" for="Sales Reference">&nbsp;<em></em></label> 
            <input type="text" class="form-control" name="RefSalesCode[]" placeholder="Sales Reference Code" autocomplete="off">  
        </div>
        <div class="col-sm-1" style="margin-top:35px;"> 
            <div class="custom-trash">
                <label class="control-label"></label> 
                <span class="fa fa-trash delete_production_row" style="cursor:pointer;color: red;"></span>
            </div>
        </div>
    </div>
</div>

<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 text-right">
                <button type="button" class="btn btn-primary" onclick="window.location.href='<?= $file_name ?>'">Back</button>
            </div>
        </div>
    </div>
</section>

<?php if(isset($_SESSION['info_message'])){ ?>
<div class="alert alert-info alert-primary">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <?php echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
</div>
<?php } ?>

<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card box-primary">
                    <form class="form-horizontal" method="post" name="form1" id="form1" 
                          action="index?page=add_part_number_manually&action=<?php echo $form_action; ?>" 
                          enctype="multipart/form-data">
                        
                        <div class="card-body">
                            <div class="form-section mt-2">
                                
                                <!-- Initial Row -->
                                <div class="col-sm-12 col-lg-12 col-12 initial_production_row" id="production_row0" data-row_count="0">
                                    <div class="row">
                                        <div class="col-sm-2">
                                            <label for="part_id" class="control-label">Part<em>*</em></label>
                                            <div class="">
                                                <?= $gsi->getPartNumberList("part_id[]", "", "100%", false, "form-control select2 part_select", "required"); ?>
                                            </div>
                                        </div>
                                        <div class="col-sm-2">
                                            <label for="customer_reff" class="control-label">Customer code<em>*</em></label>
                                            <div class="">
                                                <?= $gsi->getCustomercodeListNew("customer_reff[]", "", "100%", false, "form-control select2", "required"); ?>
                                            </div>
                                        </div>
                                        <div class="col-sm-1"> 
                                            <label class="control-label" for="item_price">Price</label> 
                                            <div class="">
                                                <input type="text" class="form-control item_price" name="item_price[]" placeholder="Price">
                                            </div>
                                        </div>
                                        <div class="col-sm-2"> 
                                            <label class="control-label" for="req_date">Required Date<em>*</em></label> 
                                            <div class="">
                                                <input type="date" class="form-control" name="req_date[]" required>
                                            </div>
                                        </div>
                                        <div class="col-sm-1"> 
                                            <label class="control-label" for="req_qty">Required Qty<em>*</em></label>
                                            <div class="">
                                                <input type="number" class="form-control" name="req_qty[]" min="1" placeholder="Required Qty" required>
                                            </div>
                                        </div>
                                        <div class="col-sm-3">
                                            <label for="RefSalesCode" class="control-label">Sales Reference Code</label>
                                            <div class="">
                                                <input type="text" class="form-control" name="RefSalesCode[]" placeholder="Sales Reference Code" autocomplete="off">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Add More Button -->
                                <div class="form-group col-sm-12 production_div_to_append">	
                                    <label class="add_one_more_production" style="margin-left:0%;cursor:pointer;color: #a423a4;"><span class="fa fa-plus"></span> Add More</label>
                                </div>

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

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

<script type="text/javascript">
$(function(){
    // Disable submit button on form submission
    $('#form1').submit(function(){
        $("#submit").attr("disabled", true);
        $('#page_load_div').show();
    });
    
    // Function to fetch price for a part
    function fetchItemPrice(partSelect) {
        var part_id = $(partSelect).val();
        var priceInput = $(partSelect).closest('.row').find('.item_price');
        
        console.log('Fetching price for part_id:', part_id);
        
        if(part_id && part_id != '-1') {
            $.ajax({
                //url: 'index.php?page=ajax_actions&action=fetch_item_price',
			  url: site_url + "/modules/production_planning/index.php?page=ajax_actions&action=fetch_item_price",

                type: 'POST',
                data: {
                    action: 'fetch_item_price',
                    part_id: part_id
                },
                dataType: 'json',
                success: function(response) {
                    console.log('Response:', response);
                    if(response.status == 'success') {
                        priceInput.val(response.price);
                    } else {
                        priceInput.val('0');
                    }
                },
                error: function(xhr, status, error) {
                    console.log('Error:', error);
                    console.log('Response:', xhr.responseText);
                    priceInput.val('0');
                }
            });
        } else {
            priceInput.val('');
        }
    }
    
    // Event handler for part selection on initial row and dynamically added rows
    $(document).on('change', '.part_select', function() {
        console.log('Part select changed');
        fetchItemPrice(this);
    });
    
    // Add More Production Row
    $('.production_div_to_append').on('click', '.add_one_more_production', function() { 
        $('#production_div_to_clone').show();
        var div_count = $('.initial_production_row').last().attr("data-row_count");
        div_count++;
        
        var cloned_div = $('#production_div_to_clone').clone()
            .addClass("initial_production_row")
            .attr("id", "production_row" + div_count)
            .attr("data-row_count", div_count);
        
        // Destroy select2 before cloning if it exists
        cloned_div.find('.select2-hidden-accessible').each(function() {
            $(this).select2('destroy');
        });
        
        // Remove any select2 generated elements
        cloned_div.find('.select2-container').remove();
        
        $('.production_div_to_append').before(cloned_div);
        
        // Reinitialize select2 for cloned selects
        cloned_div.find('.select2').each(function() {
            $(this).select2({
                width: '100%',
                placeholder: 'Select an option'
            });
        });
        
        $('#production_div_to_clone').hide();
    });
    
    // Delete Production Row
    $("#form1").on("click", ".delete_production_row", function() {
        if(confirm('Are you sure you want to delete this row?')){		
            $(this).closest('.initial_production_row').remove();
        }
    });
});
</script>