@extends('backend.layouts.master')

@section('title')
Settings - {{ $title }}
@endsection

@section('navbar-content')
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0"> Settings </h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ route('home') }}">Dashboard</a></li>
                    @if (helper::roleAccess('settings.expense.index'))
                    <li class="breadcrumb-item"><a href="{{ route('settings.expense.index') }}">Expense List</a></li>
                    @endif
                    <li class="breadcrumb-item active"><span>Add New Expense</span></li>
                </ol>
            </div>
        </div>
    </div>
</div>
@endsection

@section('admin-content')

<div class="row">
    <div class="col-md-12">
        <div class="card card-default">
            <div class="card-header">
                <h3 class="card-title">Add New Expense</h3>
                <div class="card-tools">
                    @if (helper::roleAccess('settings.expense.index'))
                    <a class="btn btn-default" href="{{ route('settings.expense.index') }}"><i class="fa fa-list"></i> Expense List</a>
                    @endif
                    <a class="btn btn-tool btn-default" data-card-widget="collapse"><i class="fas fa-minus"></i></a>
                    <a class="btn btn-tool btn-default" data-card-widget="remove"><i class="fas fa-times"></i></a>
                </div>
            </div>

            <div class="card-body">
                <div class="form-row">
                    <div class="col-md-4 mb-3">
                        <label for="category_id">Category Name * :</label>
                        <select class="form-control select2" name="category_id" id="category_id">
                            <option selected disabled value="">--Select--</option>
                            @foreach ($category as $value)
                            <option value="{{ $value->id }}">{{ $value->name }}</option>
                            @endforeach
                        </select>
                        <span class="error text-danger font-weight-bold"></span>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label for="branch_id">Branch Name * :</label>
                        <select class="form-control select2" name="branch_id" id="branch_id">
                            <option selected disabled value="">--Select--</option>
                              @if(auth()->user()->role_id > 1)
                                    @foreach ($branch as $key => $value)
                                        <option value="{{ $value->id }}" {{auth()->user()->branch_id == $value->id ? 'selected' :''}}>{{ $value->name }}</option>
                                    @endforeach
                                    @else 

                                  @foreach ($branch as $key => $value)
                                        <option value="{{ $value->id }}">{{ $value->name }}</option>
                                    @endforeach
                                    @endif
                        </select>
                        <span class="error text-danger font-weight-bold"></span>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label for="account_id">Account Name * :</label>
                        <select class="form-control select2" name="account_id" id="account_id">
                            <option selected disabled value="">--Select--</option>
                            @foreach ($accountName as $value)
                            <option value="{{ $value->id }}">{{ $value->account_name }}</option>
                            @endforeach
                        </select>
                        <span class="error text-danger font-weight-bold"></span>
                    </div>

               <div class="col-md-4 mb-3">
    <label for="payment_method">Payment Method * :</label>
    <select id="payment_method" name="payment_method_single" class="form-control select2">
           <x-account :setAccounts="$accounts" />
</select>
                                                                                                   
    <span class="error text-danger font-weight-bold"></span>
</div>


                    <div class="col-md-4 mb-3">
                        <label for="amount">Amount * :</label>
                        <input type="text" id="amount" name="amount" class="form-control" placeholder="Amount" value="" required>
                        <span class="error text-danger font-weight-bold"></span>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label for="date">Date:</label>
                        <div class="input-group date" id="reservationdate" data-target-input="nearest">
                            <input type="text" id="date" name="date" data-toggle="datetimepicker" value="{{ date('Y-m-d') }}"
                                class="form-control datetimepicker-input" data-target="#reservationdate" autocomplete="off" />
                            <div class="input-group-append" data-target="#reservationdate" data-toggle="datetimepicker">
                                <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                            </div>
                        </div>
                        <span class="error text-danger font-weight-bold"></span>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label for="note">Note :</label>
                        <textarea id="note" name="note" rows="1" class="form-control" placeholder="Note"></textarea>
                        <span class="error text-danger font-weight-bold"></span>
                    </div>

                    <div class="col-md-8 mt-3 text-right mb-3">
                        <button class="btn btn-info" id="add_new" type="button"><i class="fa fa-plus"></i> &nbsp;Add New</button>
                    </div>
                </div>
            </div>

            <div class="card-footer">
                <form class="needs-validation" method="POST" action="{{ route('settings.expense.store') }}" novalidate>
                    @csrf
                    <table class="table table-bordered table-hover" id="show_item">
                       <thead>
<tr>
    <th colspan="7">Expense</th>
</tr>
<tr>
    <td class="text-center"><strong>Category</strong></td>
    <td class="text-center"><strong>Branch</strong></td>
    <td class="text-center"><strong>Account</strong></td>
    <td class="text-center"><strong>Payment Method</strong></td>
    <td class="text-center"><strong>Amount</strong></td>
    <td class="text-center"><strong>Date</strong></td>
    <td class="text-center"><strong>Action</strong></td>
</tr>
</thead>

                        <tbody id="main-table"></tbody>
                        <tfoot>
                            <tr>
                                <td class="text-right" colspan="4"><strong>Sub-Total (BDT)</strong></td>
                                <td class="text-right"><strong class="subtotal">0.00</strong></td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                    <button class="btn btn-info" type="submit"><i class="fa fa-save"></i> &nbsp;Save</button>
                </form>
            </div>

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

@endsection

@section('scripts')
<script>
$(document).ready(function () {

    // Initialize select2
    $('.select2').select2({
        width: '100%'
    });

    // Initialize datetimepicker
    $('#reservationdate').datetimepicker({
        format: 'YYYY-MM-DD',
        useCurrent: true,
        sideBySide: true
    });

    function resetFields() {
        $('#category_id').val(null).trigger('change');
        $('#branch_id').val(null).trigger('change');
        $('#account_id').val(null).trigger('change');
        $('#payment_method').val(null).trigger('change');
        $('#amount').val('');
        $('#date').val(new Date().toISOString().split('T')[0]);
        $('#note').val('');
        $('.error').text('');
    }

    function updateSubtotal() {
        let subtotal = 0;
        $('input[name="amount[]"]').each(function () {
            let amt = parseFloat($(this).val());
            if (!isNaN(amt)) subtotal += amt;
        });
        $('.subtotal').text(subtotal.toFixed(2));
    }

    $('#add_new').on('click', function () {
        let category_id = $('#category_id').val();
        let categoryText = $('#category_id option:selected').text();

        let branch_id = $('#branch_id').val();
        let branchText = branch_id ? $('#branch_id option:selected').text() : '';

        let account_id = $('#account_id').val();
        let accountText = $('#account_id option:selected').text();

        let payment_id = $('#payment_method').val();
        let paymentText = payment_id ? $('#payment_method option:selected').text() : '';

        let amount = $('#amount').val().trim();
        let date = $('#date').val();
        let note = $('#note').val();

        $('.error').text('');
        let isValid = true;

        if (!category_id) {
            $('#category_id').siblings('.error').text('Category can\'t be empty');
            isValid = false;
        }
        if (!account_id) {
            $('#account_id').siblings('.error').text('Account can\'t be empty');
            isValid = false;
        }
        if (!payment_id) {
            $('#payment_method').siblings('.error').text('Payment Method can\'t be empty');
            isValid = false;
        }
        if (!amount || isNaN(amount) || Number(amount) <= 0) {
            $('#amount').siblings('.error').text('Enter valid amount');
            isValid = false;
        }
        if (!date) {
            $('#date').closest('div').find('.error').text('Date can\'t be empty');
            isValid = false;
        }
        if (!isValid) return;

        let html = `
        <tr>
            <td>
                <span>${categoryText}</span>
                <input type="hidden" name="category_id[]" value="${category_id}">
            </td>
            <td>
                <span>${branchText}</span>
                <input type="hidden" name="branch_id[]" value="${branch_id ?? ''}">
            </td>
            <td>
                <span>${accountText}</span>
                <input type="hidden" name="account_id[]" value="${account_id}">
            </td>
            <td>
                <span>${paymentText}</span>
                <input type="hidden" name="payment_method[]" value="${payment_id}">
            </td>
            <td class="text-right">
                <span>${parseFloat(amount).toFixed(2)}</span>
                <input type="hidden" name="amount[]" value="${parseFloat(amount).toFixed(2)}">
            </td>
            <td>
                <span>${date}</span>
                <input type="hidden" name="date[]" value="${date}">
                <input type="hidden" name="note[]" value="${note}">
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-danger btn-sm delete-row">
                    <i class="fa fa-trash"></i>
                </button>
            </td>
        </tr>
        `;

        $('#main-table').append(html);
        resetFields();
        updateSubtotal();
    });

    $('body').on('click', '.delete-row', function () {
        $(this).closest('tr').remove();
        updateSubtotal();
    });

});
</script>
@endsection
