File "manage_expense.php"

Full Path: /home/leadltht/fastlinkinternet.com/administrator/data-provider/admin/expense/manage_expense.php
File size: 10.9 KB
MIME-type: text/x-php
Charset: utf-8

<?php
require_once('/home/leadltht/fastlinkinternet.com/administrator/data-provider/config.php'); // Ensure the correct path to config.php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['userdata']['type']) || !isset($_SESSION['userdata']['firstname']) || !isset($_SESSION['userdata']['lastname'])) {
    echo '<center>Unknown User Type</center>';
    exit;
}

$firstname = $_SESSION['userdata']['firstname'];
$lastname = $_SESSION['userdata']['lastname'];
$full_name = htmlspecialchars($firstname . ' ' . $lastname);

$type = $_SESSION['userdata']['type'];

if (isset($_GET['id']) && $_GET['id'] > 0) {
    $qry = $conn->query("SELECT * from `expense_list` where id = '{$_GET['id']}'");
    if ($qry->num_rows > 0) {
        foreach ($qry->fetch_assoc() as $k => $v) {
            $$k = $v;
        }
    } else {
?>
        <center>Unknown Expense ID</center>
        <style>
            #uni_modal .modal-footer {
                display: none;
            }
        </style>
        <div class="text-right">
            <button class="btn btn-default bg-gradient-dark btn-flat" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
        </div>
<?php
        exit;
    }
}
?>

<style>
    .wider-form .form-group {
        width: 100%;
    }
    .wider-form .col-md-6 {
        flex: 0 0 150%;
        max-width: 100%;
    }
</style>


<div class="container-fluid wider-form">
    <form action="" id="expense-form">
        <input type="hidden" name="id" value="<?php echo isset($id) ? $id : '' ?>">
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="expense_date" class="control-label">Expense Date *</label>
                    <input name="expense_date" id="expense_date" type="date" class="form-control form-control-sm rounded-0" value="<?php echo isset($expense_date) ? $expense_date : ''; ?>" required>
                </div>
                <div class="form-group">
                    <label for="collected_by" class="control-label">Recorded By</label>
                    <input type="text" name="collected_by" id="collected_by" class="form-control form-control-sm rounded-0" value="<?= $full_name ?>" readonly>
                </div>
                <div class="form-group">
                    <label for="item_name" class="control-label">Name of Item</label>
                    <input type="text" name="item_name" id="item_name" class="form-control form-control-sm rounded-0" value="<?= $item_name ?>">
                </div>
            </div>
            <div class="col-md-6">
                <table class="table table-stripped table-bordered">
                    <thead>
                        <tr>
                            <th class="text-center">
                                <div class="custom-control custom-checkbox">
                                    <input class="custom-control-input custom-control-input-primary custom-control-input-outline" type="checkbox" id="checkall">
                                    <label for="checkall" class="custom-control-label">All</label>
                                </div>
                            </th>
                            <th class="text-center">Category</th>
                            <th class="text-center">Description</th>
                            <th class="text-center">Fee</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $expense_item = [];
                        if (isset($id)) {
                            $expense_qry = $conn->query("SELECT * FROM `expense_items` WHERE expense_id = '{$id}' ");
                            while ($row = $expense_qry->fetch_assoc()) {
                                $expense_item[$row['category_id']] = $row;
                            }
                        }

                        $category_query = "SELECT * FROM `expenses_category_list` ORDER BY `name` ASC";
                        $category = $conn->query($category_query);

                        while ($row = $category->fetch_assoc()): 
                        ?>
                        <tr>
                            <td class="px-2 py-1 align-middle text-center">
                                <input type="hidden" class="fee" id="fee<?= $row['id'] ?>" name="fee[<?= $row['id'] ?>]" value="<?= (isset($expense_item[$row['id']])) ? ($expense_item[$row['id']]['fee']) : ($row['fee']) ?>">
                                <div class="custom-control custom-checkbox">
                                    <input name="category_id[<?= $row['id'] ?>]" class="custom-control-input custom-control-input-primary custom-control-input-outline check-item" type="checkbox" id="cat_<?= $row['id'] ?>" value="<?= $row['id'] ?>" <?= (isset($expense_item[$row['id']])) ? 'checked' : '' ?>>
                                    <label for="cat_<?= $row['id'] ?>" class="custom-control-label"></label>
                                </div>
                            </td>
                            <td class="px-2 py-1 align-middle"><?= $row['name'] ?></td>
                            <td class="px-2 py-1 align-middle"><?= $row['description'] ?></td>
                            <td class="px-2 py-1 align-middle"><input class="form-control form-control-sm rounded-0 fee-input" value="<?= $row['fee'] ?>" type="text" name="" id="<?= $row['id'] ?>"></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
                <div class="form-group">
                    <label for="total_amount" class="control-label">Total Expense</label>
                    <input name="total_amount" id="total_amount" type="text" class="form-control form-control-sm rounded-0" value="<?php echo isset($total_amount) ? $total_amount : 0; ?>" readonly tabindex="-1">
                </div>
            </div>
        </div>
    </form>
</div>


<!-- Include Select2 CSS and JS files -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
    function _checkAll(){
        var total = $('.check-item').length;
        var checked = $('.check-item:checked').length;
        if(total == checked){
            $('#checkall').prop('checked',true);
        }else{
            $('#checkall').prop('checked',false);
        }
    }

    function calc_total(){
        var total = 0;
        $('.check-item:checked').each(function(){
            var tr = $(this).closest('tr');
            var fee = tr.find('input.fee').val();
            total += parseFloat(fee) || 0;
        });
        console.log("Total calculated: ", total); // Debugging line
        $('#total_amount').val(total.toFixed(2)); // Ensure the total is formatted correctly
    }

    function delete_expense(id) {
        start_loader();
        $.ajax({
            url: "https://fastlinkinternet.com/administrator/data-provider/classes/Master.php?f=delete_expense",
            method: "POST",
            data: { id: id },
            dataType: "json",
            error: err => {
                console.log(err);
                alert_toast("An error occurred.", 'error');
                end_loader();
            },
            success: function(resp) {
                if (typeof resp === 'object' && resp.status === 'success') {
                    location.reload();
                } else {
                    alert_toast("An error occurred.", 'error');
                    end_loader();
                }
            }
        });
    }

    $(document).ready(function(){
        _checkAll();
        calc_total();

        $('.check-item').change(function(){
            _checkAll();
            calc_total();
        });

        $('#checkall').change(function(){
            if($(this).is(':checked') == true){
                $('.check-item').prop('checked', true).trigger('change');
            }else{
                $('.check-item').prop('checked', false).trigger('change');
            }
            _checkAll();
            calc_total();
        });

        $('input.fee-input').on('input', function() {
            var id = $(this).attr('id');
            var value = $(this).val();
            $('#fee' + id).val(value);
            calc_total();
        });

        $('#expense-form').submit(function(e){
            e.preventDefault();
            var _this = $(this);
            $('.err-msg').remove();
            var el = $('<div>');
            el.addClass("alert err-msg");
            el.hide();

            if(_this[0].checkValidity() == false){
                _this[0].reportValidity();
                return false;
            }

            if($('.check-item:checked').length <= 0){
                alert_toast("Please Select at least 1 category first.", 'error');
                return false;
            }

            start_loader();

            // Log form data before submission
            console.log("Form data before submission:", new FormData($(this)[0]));

            $.ajax({
                url: "https://fastlinkinternet.com/administrator/data-provider/classes/Master.php?f=save_expense",
                data: new FormData($(this)[0]),
                cache: false,
                contentType: false,
                processData: false,
                method: 'POST',
                type: 'POST',
                dataType: 'json',
                error: err => {
                    console.error("Full Error Response:", err);
                    el.addClass('alert-danger').text("An error occurred");
                    _this.prepend(el);
                    el.show('.modal');
                    end_loader();
                },
                success: function(resp){
                    // Log the server response for debugging
                    console.log("Server response:", resp);

                    if (typeof resp == 'object' && resp.status == 'success') {
                        location.reload();
                    } else if (resp.status == 'failed' && !!resp.msg) {
                        el.addClass('alert-danger').text(resp.msg);
                        _this.prepend(el);
                        el.show('.modal');
                    } else {
                        el.text("An error occurred");
                        console.error("Response:", resp);
                    }
                    $("html, body").scrollTop(0);
                    end_loader();
                }
            });
        });

        // Initialize Select2 with type search
        $('.select2').select2({
            placeholder: 'Select an option',
            allowClear: true
        });
    });
</script>