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

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


$currentMonth = date('n');
$currentYear = date('Y');
 if ($currentMonth >= 4) {
    $startYear = $currentYear;
    $endYear = $currentYear + 1;
} else {
    $startYear = $currentYear - 1;
    $endYear = $currentYear;
}
$financial_year_from = "$startYear-04";
$financial_year_to = "$endYear-03";


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

    if ($q) {
        echo "<script>alert('Tax Slab Deleted Successfully !');</script>";
        echo "<script>location.href='tax-slab';</script>";
    }
}

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

?>


<!-- ============================================================== -->
<!-- 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">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-1 mb-4">
                                Add Tax Slab
                            </h4>

                            <form id="form_submit">
                                <div class="row">
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="financial_year_from">Select Financial Year From</label>
                                            <input type="month" name="financial_year_from" required class="form-control" id="financial_year_from" value="<?php echo isset($edit['year_start'])?$edit['year_start']:$financial_year_from; ?>">
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="financial_year_to">Select Financial Year To</label>
                                            <input type="month" name="financial_year_to" required class="form-control" id="financial_year_to" value="<?php echo isset($edit['year_end'])?$edit['year_end']:$financial_year_to; ?>">
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="tax_slab_from">Tax Slab From</label>
                                            <input type="text" name="tax_slab_from" class="form-control indianCurrencyFormat" id="tax_slab_from" required placeholder="Tax Slab From" value="<?php echo $edit['tax_slab_from']; ?>">
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="tax_slab_to">Tax Slab To</label>
                                            <input type="text" name="tax_slab_to" class="form-control indianCurrencyFormat" id="tax_slab_to" required placeholder="Tax Slab To" value="<?php echo $edit['tax_slab_to']; ?>">
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="tax_slab_rate">Tax Slab Rate</label>
                                            <input type="text" name="tax_slab_rate" class="form-control percentageFormat" id="tax_slab_rate" required placeholder="Tax Slab Rate" value="<?php echo $edit['tax_slab_rate']; ?>">
                                        </div>
                                    </div>
                                </div>

                                <?php if (isset($edit['id'])) { ?>
                                    <input type="hidden" name="edit_taxSlab_id" value="<?php echo $edit['id']; ?>">
                                    <input class="btn btn-primary mr-1" name="updateTaxSlab_submit" id="updateTaxSlab_submit" type="hidden">
                                <?php } else { ?>
                                    <input class="btn btn-primary mr-1" name="addTaxSlab_submit" id="addTaxSlab_submit" 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="updateTaxSlab_submit" id="updateTaxSlab_submit" type="submit">Update Tax Slab</button>
                                    <?php } else { ?>
                                        <button class="btn btn-primary mr-1" name="addTaxSlab_submit" id="addTaxSlab_submit" type="submit">Save Tax Slab</button>
                                    <?php } ?>
                                </div>

                            </form>
                        </div>
                    </div> 
                </div>

            </div>

            <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 Tax Slab
                            </h4>

                            <table id="basic-datatable" class="table dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Financial Year</th>
                                        <th>Tax Slab</th>
                                        <th>Rate</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>

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

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

        </div>
    </div> 

</div>



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

<script>
  $(document).ready(function() {
        
        // ############################### columns
        let columns = [
            {data: 'id'}, 
            {data: 'year_start'}, 
            {data: 'tax_slab_from'},
            {data: 'tax_slab_rate'},
            {data: 'year_end'},
            {data: 'tax_slab_to', visible:false},
        ];

        // ############################### columns
        function show_hierarchy_data() {

            $("#filter_options").html('');
            form_fields.each(function() {
                search_filter(this);
            });
            if (setArray.length > 0) {
                loadTable('#basic-datatable', 'get_from_server/tax_slab_get', columns, [0, 'asc'], setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/tax_slab_get', columns, [0, 'asc']);
            }
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }

        show_hierarchy_data();
    });
   


    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='tax-slab';
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });
</script>