<?php
include "pin/header.php";
include "pin/sidenav.php";

$user_id = $_SESSION['user_id'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];


$edit = mysqli_fetch_assoc(mysqli_query($db, "select * from asset_management where id='$_GET[edit]'"));

$asset_details = json_decode($edit['asset_details'], true) ?? [];


?>


<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="mt-5"></div>

            <div class="row">
                <div class="col-lg-12">
                    <form class="parsley-examples" id="form_submit">
                        <div class="card mb-3">
                            <div class="card-body p-4">
                                <div class="w-100 d-flex justify-content-between align-items-center">
                                    <h4 class="header-title mt-1 mb-4">
                                        Add Assigned Asset
                                    </h4>
                                    <div>
                                        <button type="button" class="btn btn-success add_section" style="height:fit-content; padding-top: 0.5rem; padding-bottom: 0.3rem;" title="Add More Assets"><i class="uil uil-plus"></i></button>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group m-0">
                                            <label for="asset_type">Asset Type<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="asset_type" class="form-control custom-select-picker" data-placeholder="Select Asset Type" id="asset_type" required>
                                                <option></option>
                                                <?php
                                                    $assets = mysqli_query($db,"SELECT * FROM asset_types");
                                                    while($a = mysqli_fetch_assoc($assets)){
                                                ?>
                                                <option <?php echo ($edit['asset_type']==$a['id'])?'selected':''; ?> value="<?php echo $a['id']; ?>"><?php echo $a['type']; ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                        <div class="all_sections row">
                            <?php
                            if(sizeof($asset_details)>0){
                                foreach ($asset_details as $key => $value) {
                            ?>
                            <div class="section col-12">
                                <div class="card position-relative">
                                    <div class="bg-danger rounded-circle position-absolute remove_section" style="padding: 4px 5px 1px 5px; top:-5px; right:-5px; cursor:pointer;" title="Remove Asset Section"><i class="uil uil-times text-white"></i></div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <h4 class="header-title m-0 asset_count_heading">Asset No. <?php echo ($key+1); ?> Details</h4>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group">
                                                    <!-- <label for="asset_serial_number">Asset Sr. No.<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_serial_number[]" required placeholder="Enter Asset Sr. No." class="form-control" id="asset_serial_number" value="<?php echo $value['serial_number']; ?>">
                                                </div>
                                            </div>

                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group">
                                                    <!-- <label for="asset_name">Asset Name<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_name[]" required placeholder="Enter Asset Name" class="form-control" id="asset_name" value="<?php echo $value['name']; ?>">
                                                </div>
                                            </div>

                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group">
                                                    <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_brand[]" required placeholder="Enter Asset Brand" class="form-control" id="asset_brand" value="<?php echo $value['brand']; ?>">
                                                </div>
                                            </div>
                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group mb-md-0">
                                                    <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_invoice_number[]" required placeholder="Enter Asset Invoice Number" class="form-control" id="asset_invoice_number" value="<?php echo $value['invoice_number']; ?>">
                                                </div>
                                            </div>
                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group mb-sm-0">
                                                    <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                    <input type="date" name="asset_invoice_date[]" required placeholder="Enter Asset Invoice Date" class="form-control" id="asset_invoice_date" value="<?php echo $value['invoice_date']; ?>">
                                                </div>
                                            </div>

                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group m-0">
                                                    <!-- <label for="asset_quantity">Asset Quantity<span class="text-danger">*</span></label> -->
                                                    <input type="number" name="asset_quantity[]" required placeholder="Enter Quantity" class="form-control" id="asset_quantity" value="<?php echo $value['quantity']; ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php }
                            }else{ ?>
                            <div class="section col-12">
                                <div class="card position-relative">
                                    <div class="bg-danger rounded-circle position-absolute remove_section" style="padding: 4px 5px 1px 5px; top:-5px; right:-5px; cursor:pointer;" title="Remove Asset Section"><i class="uil uil-times text-white"></i></div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <h4 class="header-title m-0 asset_count_heading">Asset No. 1 Details</h4>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group">
                                                    <!-- <label for="asset_serial_number">Asset Sr. No.<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_serial_number[]" required placeholder="Enter Asset Sr. No." class="form-control" id="asset_serial_number" value="">
                                                </div>
                                            </div>

                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group">
                                                    <!-- <label for="asset_name">Asset Name<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_name[]" required placeholder="Enter Asset Name" class="form-control" id="asset_name" value="">
                                                </div>
                                            </div>

                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group">
                                                    <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_brand[]" required placeholder="Enter Asset Brand" class="form-control" id="asset_brand" value="">
                                                </div>
                                            </div>
                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group mb-md-0">
                                                    <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                    <input type="text" name="asset_invoice_number[]" required placeholder="Enter Asset Invoice Number" class="form-control" id="asset_invoice_number" value="">
                                                </div>
                                            </div>
                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group mb-sm-0">
                                                    <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                    <input type="date" name="asset_invoice_date[]" required placeholder="Enter Asset Invoice Date" class="form-control" id="asset_invoice_date" value="">
                                                </div>
                                            </div>

                                            <div class="col-md-4 col-sm-6 px-1">
                                                <div class="form-group m-0">
                                                    <!-- <label for="asset_quantity">Asset Quantity<span class="text-danger">*</span></label> -->
                                                    <input type="number" name="asset_quantity[]" required placeholder="Enter Quantity" class="form-control" id="asset_quantity" value="">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php } ?>

                        </div>


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

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="holding_period">Holding Period<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="holding_period" class="form-control custom-select-picker" data-placeholder="Select Holding Period" id="holding_period" required>
                                                <option></option>
                                                <option <?php echo ($edit['holding_period']=='Temporary')?'selected':''; ?> value="Temporary">Temporary</option>
                                                <option <?php echo ($edit['holding_period']=='Permanent')?'selected':''; ?> value="Permanent">Permanent</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="assigned_date">Assigned Date<span class="text-danger">*</span></label>
                                            <input type="date" name="assigned_date" required placeholder="Enter Asset Brand" class="form-control" id="assigned_date" value="<?php echo $edit['assigned_date']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="assigned_to">Assigned To<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="assigned_to" class="form-control custom-select-picker" data-placeholder="Select Assigned To" id="assigned_to" required>
                                                <option></option>
                                                <?php
                                                    $today_date = date('Y-m');
                                                    $users = mysqli_query($db, "select name,employee_id from users where (COALESCE(joining_date,'') = '' OR DATE_FORMAT(STR_TO_DATE(joining_date, '%Y-%m-%d'),'%Y-%m') <= '$today_date') AND (COALESCE(working_status_date,'')='' or DATE_FORMAT(STR_TO_DATE(working_status_date, '%Y-%m-%d'),'%Y-%m')>='$today_date') ");
                                                    while ($user = mysqli_fetch_assoc($users)) {
                                                        echo "<option value='". $user['employee_id']. "'>". $user['name']. "</option>";
                                                    }
                                                ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="form-group">
                                            <label for="asset_desc">Asset Discription<span class="text-danger">*</span></label>
                                            <textarea name="asset_desc" id="asset_desc" rows="5" class="form-control" placeholder="Enter Asset Description..." required><?php echo $edit['asset_desc']; ?></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <?php if (isset($edit['id'])) { ?>
                            <input type="hidden" name="asset_edit_id" value="<?php echo $edit['id']; ?>">
                            <input class="btn btn-primary mr-1" name="update_assets" id="update_assets" type="hidden">
                        <?php } else { ?>
                            <input class="btn btn-primary mr-1" name="add_assets" id="add_assets" type="hidden">
                        <?php } ?>

                        <div class="form-group text-right mb-0 mt-4">
                            <?php if (isset($edit['id'])) { ?>
                                <button class="btn btn-primary mr-1" name="update_assets" id="update_assets" type="submit">Update Assets</button>
                            <?php } else { ?>
                                <button class="btn btn-primary mr-1" name="add_assets" id="add_assets" type="submit">Save Assets</button>
                            <?php } ?>
                            <!-- <button type="reset" class="btn btn-secondary">Cancel</button> -->
                        </div>
                    </form>
                </div>
                <!-- end col -->

            </div>
            <!-- end row -->

        </div>
    </div> <!-- content -->

</div>



<?php
include "pin/footer.php";
?>
<script>

    $(document).on("click", ".add_section", function() {
        let body = $(".all_sections");
        let section_count = $(body).children().length+1;
        $(body).append(`<div class="section col-12">
                            <div class="card position-relative">
                                <div class="bg-danger rounded-circle position-absolute remove_section" style="padding: 4px 5px 1px 5px; top:-5px; right:-5px; cursor:pointer;" title="Remove Asset Section"><i class="uil uil-times text-white"></i></div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <h4 class="header-title m-0 asset_count_heading">Asset No. ${section_count} Details</h4>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-4 col-sm-6 px-1">
                                            <div class="form-group">
                                                <!-- <label for="asset_serial_number">Asset Sr. No.<span class="text-danger">*</span></label> -->
                                                <input type="text" name="asset_serial_number[]" required placeholder="Enter Asset Sr. No." class="form-control" id="asset_serial_number" value="">
                                            </div>
                                        </div>

                                        <div class="col-md-4 col-sm-6 px-1">
                                            <div class="form-group">
                                                <!-- <label for="asset_name">Asset Name<span class="text-danger">*</span></label> -->
                                                <input type="text" name="asset_name[]" required placeholder="Enter Asset Name" class="form-control" id="asset_name" value="">
                                            </div>
                                        </div>

                                        <div class="col-md-4 col-sm-6 px-1">
                                            <div class="form-group">
                                                <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                <input type="text" name="asset_brand[]" required placeholder="Enter Asset Brand" class="form-control" id="asset_brand" value="">
                                            </div>
                                        </div>
                                        <div class="col-md-4 col-sm-6 px-1">
                                            <div class="form-group mb-md-0">
                                                <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                <input type="text" name="asset_invoice_number[]" required placeholder="Enter Asset Invoice Number" class="form-control" id="asset_invoice_number" value="">
                                            </div>
                                        </div>
                                        <div class="col-md-4 col-sm-6 px-1">
                                            <div class="form-group mb-sm-0">
                                                <!-- <label for="asset_brand">Asset Brand<span class="text-danger">*</span></label> -->
                                                <input type="date" name="asset_invoice_date[]" required placeholder="Enter Asset Invoice Date" class="form-control" id="asset_invoice_date" value="">
                                            </div>
                                        </div>

                                        <div class="col-md-4 col-sm-6 px-1">
                                            <div class="form-group m-0">
                                                <!-- <label for="asset_quantity">Asset Quantity<span class="text-danger">*</span></label> -->
                                                <input type="number" name="asset_quantity[]" required placeholder="Enter Quantity" class="form-control" id="asset_quantity" value="">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>`);
    });
    $(document).on("click", ".remove_section", function() {
        let body = $(this).parent().parent().remove();
        let section_count = $(".all_sections").children().length;
        for (let i=0; i<section_count; i++) {
            $(".all_sections").children().eq(i).find('.asset_count_heading').text(`Asset No. ${i+1} Details`);
        }
    });

    function hasEmptyFields(form) {
        // Get all input elements within the form
        const inputs = form.querySelectorAll('input, select, textarea');

        // Check if any input is empty or null
        return Array.from(inputs).some(input => {
                // console.log(input.required, input.value.trim(), input.id);
                return input.required && input.value.trim() === ''
            }
        );
    }

    $('#form_submit').submit(function (e) {
        e.preventDefault();
        let form = document.getElementById('form_submit');
        // let form_data = new FormData(form);
        let form_data = $('#form_submit').serialize();
        // console.log(form_data);

        if(hasEmptyFields(form)){
            failedMessage('Please, Fill all the Fields.','<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        $.ajax({
            url: 'fun/function',
            type: 'POST',
            data: form_data,
            dataType: 'json',
            success: function(res) {
                // console.log(res);
                if (res.status === 200) {
                    successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    setTimeout(() => {
                        location.href ='all_assets';
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });

</script>