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

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

if (isset($_GET['delete'])) {
    $q = mysqli_query($db, "DELETE FROM asset_management WHERE id='$_GET[delete]' ");

    echo "<script>alert('Asset Deleted Successfully !');</script>";
    echo "<script>location.href='all_assets';</script>";
}

?>


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

<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="mt-4"></div>
            <?php if ($user_role < 2) { ?>
            <div class="row mb-3" id="filter_block">
                <?php if ($user_role == 0) { ?>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="added_by">Added By</label>
                            <select data-plugin="customselect" name="added_by" class="form-control custom-select-picker-ajax" data-search="employees" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Added By" id="added_by" required>
                                <option></option>
                            </select>
                        </div>
                    </div>
                <?php } ?>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="assigned_to">Assigned To</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
                                $users = mysqli_query($db, "select name,employee_id from users ");
                                while ($user = mysqli_fetch_assoc($users)) {
                                    echo "<option value='". $user['employee_id']. "'>". $user['name']. "</option>";
                                }
                            ?>
                        </select>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="mb-3">
                        <label for="assigned_date">Assigned Date</label>
                        <input type="text" name="assigned_date" id="assigned_date" data-isDate='true' class="form-control flatpickr_date">
                    </div>
                </div>

                <div class="col-md-2">
                    <div class="d-flex flex-column mb-3">
                        <button type="button" class="btn btn-danger btn-padding mb-1" name="clear_filter" id="clear_filter">Clear</button>
                        <button class="btn btn-success btn-padding" type="button" name="search_filter" id="search_filter">Search</button>
                    </div>
                </div>

                <div class="col-sm-12">
                    <div id="filter_options" class="d-flex align-items-center flex-wrap" style="gap:0.25rem"></div>
                </div>

            </div>
            <?php } ?>

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-0 mb-1 mb-4">
                                All Assigned Assets
                            </h4>

                            <table id="basic-datatable" class="table dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Asset Type</th>
                                        <th>Added By</th>
                                        <?php if ($user_role < 2) { ?>
                                        <th>Assigned To</th>
                                        <?php } ?>
                                        <th>Asset Details</th>
                                        <th>Holding Period</th>
                                        <th>Assigned Date</th>
                                        <th>Asset Discription</th>
                                        <?php if ($user_role < 2) { ?>
                                        <th>Set Asset Status</th>
                                        <th>Remove Asset Status</th>
                                        <th>Action</th>
                                        <?php } ?>
                                    </tr>
                                </thead>

                            </table>
                            <!-- </div> -->

                        </div> <!-- end card body-->
                    </div> <!-- end card -->
                </div><!-- end col-->
            </div>
            <!-- end row-->

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

</div>

<!-- ============================================================== -->
<!-- End Page content -->
<!-- ============================================================== -->


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

<script>
    function check_asset_name(value, id){
        if(value!=''){
            $(`#asset_status${id}`).slideDown();
        }else{
            $(`#asset_status${id}`).slideUp();
        }
    }
    function check_asset_status(value, id){
        if(value=='Transfer'){
            $(`#transfer_to${id}`).slideDown();
        }else{
            $(`#transfer_to${id}`).slideUp();
        }
    }

    function set_asset_status(id){
        let asset_name = $(`#asset_name${id}`).val();
        let asset_status = $(`#asset_status${id}`).val();
        let transfer_to = $(`#transfer_to${id}`).val();
        
        if(asset_name!='' && asset_status!=''){
            $(`#set_status_button${id}`).removeAttr("onclick");
            
            if(asset_status=='Transfer' && transfer_to==''){
                failedMessage('Please, Choose Employee for Transfer Asset!','<?php $_SESSION['user_name']; ?>');
                return false;
            }
            
            // console.log(id, asset_name, asset_status, transfer_to);
            $.ajax({
                url:'fun/function.php',
                type:'POST',
                data:{
                    asset_name,
                    asset_status,
                    transfer_to,
                    asset_status_id:id
                },
                success: function(res){
                    // console.log(res);
                    if(res==1){
                        successMessage('Asset assigned successfully!','<?php echo $_SESSION['user_name']; ?>')
                    }else if(res==2){
                        failedMessage('This Asset Already Assigned!','<?php echo $_SESSION['user_name']; ?>')
                    }else{
                        failedMessage('Some Error Occurred!','<?php echo $_SESSION['user_name']; ?>')
                    }
                }
            });

        }else{
            failedMessage('Please, Choose both asset name and status!','<?php $_SESSION['user_name']; ?>');
        }

    }

    function remove_asset_status(id){
        let asset_name = $(`#r_asset_name${id}`).val();
        if(asset_name!=''){

            $.ajax({
                url:'fun/function.php',
                type:'POST',
                data:{
                    asset_name,
                    asset_status_remove_id:id
                },
                success: function(res){
                    console.log(res);
                    if(res==1){
                        successMessage('Asset Status Remove successfully!','<?php echo $_SESSION['user_name']; ?>')
                    }else{
                        failedMessage('Some Error Occurred!','<?php echo $_SESSION['user_name']; ?>')
                    }
                }
            });

        }else{
            failedMessage('Please, Choose asset name!','<?php $_SESSION['user_name']; ?>');
        }
    }

    $(document).on('click', ".show_hide_assets", function(){
        if($(this).next().css('display')=='none'){
            $(this).next().slideDown();
            $(this).html('Hide Assets <i class="uil uil-angle-down"></i>');
        }else{
            $(this).next().slideUp();
            $(this).html('Show Assets <i class="uil uil-angle-right"></i>');
        }
    });

    $(document).ready(function() {

        // ############################### columns
        let columns = [];
        columns.push({data: 'row_num'}, {data: 'type'}, {data: 'add_by'});
        <?php if ($user_role < 2) { ?>
        columns.push({data: 'assign_to'});
        <?php } ?>
        columns.push({data: 'asset_details'}, {data: 'holding_period'}, {data: 'assigned_date'}, {data: 'asset_desc'});
        <?php if ($user_role < 2) { ?>
            columns.push({data: 'asset_status'}, {data: 'remove_asset_status'}, {data: 'action_id'})
        <?php } ?>
        // ############################### columns

        function show_hierarchy_data() {

            // ############################### setArray
            <?php if ($user_role == 1) { ?>
                setArray.push(`(added_by='<?php echo $emp_id; ?>' OR assigned_to='<?php echo $emp_id; ?>')`);
            <?php }else if($user_role == 2){ ?>
                setArray.push(`assigned_to='<?php echo $emp_id; ?>'`);
            <?php } ?>
            // ############################### setArray

            $("#filter_options").html('');
            form_fields.each(function() {
                search_filter(this);
            });

            if (setArray.length > 0) {
                loadTable('#basic-datatable', 'get_from_server/all_assets_get', columns, [0, "asc"], setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/all_assets_get', columns, [0, "asc"]);
            }
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }
        show_hierarchy_data();
        $("#search_filter").click(show_hierarchy_data);
    });

</script>