<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name = "index?page=view";
$form_action = "insert";
$button_value = "Add";
$table_name = "set_mangmnt"; 
$page_name = "Add Set";
$query_string = "";


// Insert action
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert') {    
    utility::addslashesOnAllInput(array("query_string"));
    
    $description = $_REQUEST['description'];
    $set_number = $_REQUEST['set_number'];
	$preferred_set = $_REQUEST['preferred_set'] ?? 0;
	$use_both_tables = isset($_REQUEST['use_both_tables']) ? 1 : 0;
    
    $created_by = $_SESSION['user_id'];
    $created_on = date("Y-m-d H:i:s");	
    $updated_by = $_SESSION['user_id'];
	
    $sql = "INSERT INTO $table_name
			(description, set_number, preferred_set, use_both_tables, created_on, created_by, updated_by)
			VALUES
			('$description', '$set_number', '$preferred_set', '$use_both_tables', '$created_on', '$created_by', '$updated_by')";
    mysqli_query($conn, $sql);
    $set_id = mysqli_insert_id($conn);
     
    if(isset($_REQUEST['part_id']) && count($_REQUEST['part_id'])>0){	 
        foreach($_REQUEST['part_id'] as $key => $part_id){
            $part_id = $_REQUEST['part_id'][$key];			
            $ratio   = $_REQUEST['ratio'][$key];			

            if($part_id!=""){
                $sql1 = "INSERT INTO set_mangmnt_mapping (set_id,part_id,ratio) VALUES('$set_id','$part_id','$ratio')";
                mysqli_query($conn,$sql1);
            }
        }
    }
    $_SESSION['info_message'] = "Set added successfully";
    header("Location: $file_name");
    exit();
}

// Edit action
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
    $id = $_REQUEST['id'];
    $form_action = "update";
    $button_value = "Update";
    $page_name = "Edit Set";

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

    $description = $row_edit['description'];
    $set_number = $row_edit['set_number'];
	$preferred_set = $row_edit['preferred_set'];
	$use_both_tables = $row_edit['use_both_tables'];
}

// Update action
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update') {
    utility::addslashesOnAllInput(array("query_string"));
    
    $id = $_REQUEST['id'];
    $description = $_REQUEST['description'];
    $set_number = $_REQUEST['set_number'];
	$preferred_set = $_REQUEST['preferred_set'] ?? 0;
	$use_both_tables = isset($_REQUEST['use_both_tables']) ? 1 : 0;
    $updated_by = $_SESSION['user_id'];
	
	$sql = "UPDATE $table_name SET
				set_number = '$set_number',
				description = '$description',
				preferred_set = '$preferred_set',
				use_both_tables = '$use_both_tables',
				updated_by = '$updated_by'
			WHERE id = $id";
	mysqli_query($conn, $sql);
    if(isset($_REQUEST['part_id']) && count($_REQUEST['part_id'])>0){	
        foreach($_REQUEST['part_id'] as $key => $part_id){
            $part_id = $_REQUEST['part_id'][$key];		
            $ratio = $_REQUEST['ratio'][$key];		
            $referal_parent_mapping_id = isset($_REQUEST['referal_parent_mapping_id'][$key]) ? $_REQUEST['referal_parent_mapping_id'][$key] : '';			
                
            if(!empty($referal_parent_mapping_id) && mysqli_num_rows(mysqli_query($conn,"SELECT * FROM set_mangmnt_mapping WHERE id = '$referal_parent_mapping_id' ")) > 0){
                $sql1 = "UPDATE set_mangmnt_mapping SET part_id = '$part_id' ,ratio = '$ratio' WHERE id = '$referal_parent_mapping_id' ";
            }else{
                $sql1 = "INSERT INTO set_mangmnt_mapping (set_id,part_id,ratio)
                        VALUES('$id','$part_id','$ratio')";
            }
            mysqli_query($conn,$sql1);
        }
    }

    $_SESSION['info_message'] = "Set updated successfully";
    header("Location: $file_name");
    exit();
}
?>
<style>
em{color:red;font-size: 20px;position: absolute;}
.select2-container {width: 100% !important;}

.custom-trash {
    margin-bottom: 6px;
}
</style>

<!-- HIDDEN TEMPLATE FOR CLONE -->
<div id="new_assest_div_to_clone" style="display:none;">
    <div class="initial_row_for_na row mt-2" data-na_count="0">
        <div class='col-6'>
            <div>
                <? $gsi->getPartNumberListNew("part_id[]","","100%",false,"form-control select2 part_id","required"); ?>
            </div>
        </div>
        <div class="col-lg-4">
            <div>
                <input type="number" name="ratio[]" value="" class="form-control" placeholder="ratio" required>
            </div>
        </div>
        <div class='col-1'>
            <div class="custom-trash">
                <span class="fa fa-trash delete_new_assest text-danger" alt=""></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-4">
                <?php 
                if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
                    include("add_route_used_with_ajax.inc.php");
                } 
                ?>
            </div>
            <div class="col-sm-2">
                <?
                $query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
                $query_string = str_ireplace("page=add", "page=view", $query_string);
                ?>
                <button type="button" id="back" name="back" value="back"  style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-primary" onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <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&action=<?php echo $form_action; ?>" 
                      onsubmit="return validateForm(this)" enctype="multipart/form-data">
                    <div class="card-body">

                        <div class="row">
                            <div class="col-lg-2">
								<label for="set_number" class="control-label">Set Number<em>*</em></label>
								<div style="position:relative;">
									<input type="text" id="set_number" name="set_number" 
										   value="<?php echo $set_number; ?>" 
										   class="form-control" placeholder="Set Number" required>
									<!-- Add this span below the input -->
									<span id="set_number_error" style="color:red; font-size:13px; display:none;">
										<i class="fa fa-exclamation-circle"></i> This set number already exists.
									</span>
									<span id="set_number_ok" style="color:green; font-size:13px; display:none;">
										<i class="fa fa-check-circle"></i> Available
									</span>
									<span id="set_number_checking" style="color:gray; font-size:13px; display:none;">
										<i class="fa fa-spinner fa-spin"></i> Checking...
									</span>
								</div>
							</div>
							<div class="col-lg-2">
								<label for="preferred_set" class="control-label">Preferred Set</label>
								<div>
									<select name="preferred_set" id="preferred_set" class="form-control">
										<option value="0" <?= (isset($preferred_set) && $preferred_set == 0) ? 'selected' : ''; ?>>Preferred</option>
										<option value="1" <?= (isset($preferred_set) && $preferred_set == 1) ? 'selected' : ''; ?>>Non Preferred</option>
									</select>
								</div>
							</div>
                            <div class="col-lg-6">
                                <label for="description" class="control-label">Set Description<em>*</em></label>
                                <div>
                                    <textarea class="form-control" rows="1" id="description" name="description" placeholder="Set Description" required><?php echo stripslashes($description); ?></textarea>
                                </div>
                            </div>
							<div class="col-lg-2">
								<label class="control-label d-block">Use Both Tables</label>
								<div class="form-check mt-2">
									<input class="form-check-input"
										   type="checkbox"
										   id="use_both_tables"
										   name="use_both_tables"
										   value="1"
										   <?= (!empty($use_both_tables)) ? 'checked' : ''; ?>>
								</div>
							</div>
                        </div>

                        <div id="part_numbers_container">
                        <?php	
                        $map_hc = mysqli_query($conn,"SELECT * FROM set_mangmnt_mapping WHERE set_id='".$id."'");
                        $i = 1;
                        $map_cot = mysqli_num_rows($map_hc);
                        if($map_cot>0){
                            while($map_row = mysqli_fetch_array($map_hc)){
                                $values = $map_row['id'];
                        ?>
                        <div class="initial_row_for_na row mt-2" id="new_assest<?=$values;?>" data-na_count="<?=$i;?>">
                            <div class='col-6'> 
                                <label class="control-label">Part Number</label>
                                <div> 
                                    <? $gsi->getPartNumberListNew("part_id[]",$map_row['part_id'],"100%",false,"form-control select2 part_id","required"); ?>
                                </div> 
                            </div>
                            <div class="col-lg-4">
                                <label for="ratio" class="control-label">Ratio<em>*</em></label>
                                <div>
                                    <input type="number" name="ratio[]" value="<?php echo $map_row['ratio']; ?>" 
                                           class="form-control" placeholder="ratio" required>
                                </div>
                            </div>
                            <div class="col-lg-2 d-flex align-items-end"> 
                                <div class="custom-trash">
                                    <input type="hidden" name="referal_parent_mapping_id[]" value="<?php echo $map_row['id'];?>">
                                    <span class="fa fa-trash delete_new_assest text-danger" alt="<?php echo $map_row['id'];?>"></span>
                                    <i class="fa fa-refresh fa-spin" id="load_new_assest_<?=$map_row['id'];?>" style="font-size: 10px;display:none;"></i>
                                    <i class="fa fa-check" id="status_update_done_<?=$map_row['id'];?>" style="color:#bad23a;font-size: 10px;display:none;"></i>
                                </div>
                            </div>
                        </div>
                        <?php $i++; } } else { ?>
                        <div class="initial_row_for_na row mt-2" id="new_assest1" data-na_count="1">
                            <div class='col-6'> 
                                <label class="control-label">Part Number</label>
                                <div> 
                                    <? $gsi->getPartNumberListNew("part_id[]","","100%",false,"form-control select2 part_id","required"); ?>
                                </div> 
                            </div>
                            <div class="col-4">
                                <label for="ratio" class="control-label">Ratio<em>*</em></label>
                                <div>
                                    <input type="number" name="ratio[]" value="" class="form-control" placeholder="ratio" required>
                                </div>
                            </div>
                        </div>
                        <?php }?>	
                        </div>

                        <div class="form-group col-sm-12 new_assest_div_to_append">	
                            <label class="add_one_more_new_assest text-primary" style="cursor:pointer">
                                <span class="fa fa-plus"></span> Add More
                            </label>
                        </div>

                    </div>

                    <div class="card-footer">
                        <input type="hidden" id="id" name="id" value="<?php echo $id; ?>">
                        <input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string; ?>">
                        <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>
        </div>
    </div>
</section>
<script type="text/javascript">
$(document).ready(function(){

    var setNumberExists = false; // Global flag to block submit

    initializeAllSelect2();
    
    function initializeAllSelect2() {
        $('.part_id').each(function() {
            if (!$(this).hasClass('select2-hidden-accessible')) {
                $(this).select2();
            }
        });
    }

    var setNumberTimer = null;

    $('#set_number').on('input change', function() {
        var set_number = $.trim($(this).val());
        var id         = $('#id').val() || 0;   // 0 on insert, record id on update

        // Hide all status spans
        $('#set_number_error, #set_number_ok, #set_number_checking').hide();

        if(set_number === '') return;

        // Debounce – wait 400ms after user stops typing
        clearTimeout(setNumberTimer);
        setNumberTimer = setTimeout(function() {
            $('#set_number_checking').show();

            $.ajax({
                type : 'POST',
                url  : site_url + '/modules/set_management/index.php?page=ajax_actions&action=check_set_number',
                data : { set_number: set_number, id: id },
                dataType: 'json',
                success: function(response) {
                    $('#set_number_checking').hide();
                    if(response.exists) {
                        $('#set_number_error').show();
                        setNumberExists = true;
                    } else {
                        $('#set_number_ok').show();
                        setNumberExists = false;
                    }
                },
                error: function() {
                    $('#set_number_checking').hide();
                    setNumberExists = false;
                }
            });
        }, 400);
    });

    if($('#set_number').val() !== '') {
        $('#set_number').trigger('change');
    }

    $('#form1').on('submit', function(e) {
        if(setNumberExists) {
            e.preventDefault();
            $('#set_number_error').show();
            $('#set_number').focus();
            alert('Please fix the errors before submitting. Set number already exists.');
            return false;
        }
        initializeAllSelect2();
    });
    $('.add_one_more_new_assest').click(function() {
        var div_count = $('.initial_row_for_na').last().attr("data-na_count");
        div_count = parseInt(div_count) + 1;

        var cloned_div = $('#new_assest_div_to_clone').children().clone();
        cloned_div.attr("id", "new_assest" + div_count)
                  .attr("data-na_count", div_count);

        $('.new_assest_div_to_append').before(cloned_div);
        $('#new_assest' + div_count).find('.part_id').select2();
    });

    $(document).on("click", ".delete_new_assest", function() {
        if(confirm('Are you sure! You want to delete?')){
            var altValue = $(this).attr("alt");

            if(altValue != "" && altValue != undefined){
                var na_mapping_id = altValue;
                $('#load_new_assest_' + na_mapping_id).show();

                $.ajax({
                    async   : true,
                    type    : "POST",
                    url     : site_url + "/modules/set_management/index.php?page=ajax_actions&action=delete_set_mapping",
                    data    : { na_mapping_id: na_mapping_id },
                    success : function(result) {
                        try {
                            var resultObj = jQuery.parseJSON(result);
                            if(resultObj.status == "success"){
                                $('#status_update_done_' + na_mapping_id).show();
                                $('#load_new_assest_' + na_mapping_id).hide();
                                setTimeout(function() {
                                    $('#status_update_done_' + na_mapping_id).hide();
                                    $('#new_assest' + na_mapping_id).find('select').select2('destroy');
                                    $('#new_assest' + na_mapping_id).remove();
                                }, 1000);
                            } else {
                                $('#load_new_assest_' + na_mapping_id).hide();
                                alert('Error: ' + (resultObj.message || 'Failed to delete'));
                            }
                        } catch(e) {
                            $('#load_new_assest_' + na_mapping_id).hide();
                            alert('Error processing response');
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#load_new_assest_' + na_mapping_id).hide();
                        alert('AJAX Error: ' + error);
                    }
                });
            } else {
                var row = $(this).closest('.initial_row_for_na');
                row.find('select').select2('destroy');
                row.remove();
            }
        }
    });
});
</script>