@extends('template.app')

@section('meta')
@endsection

@section('title')
Exchange
@endsection

@section('styles')
<style>
    .highlight {
        background-color: #ffff99;
    }

    #data-table.dataTable tbody td {
        padding: 0px !important;
        height: 20px !important;
        line-height: 35px !important;
        font-size: 15px !important;
        text-align: center;
    }

    #data-table th {
        text-align: center;
    }
</style>
@endsection

@section('content')
<div class="page-breadcrumb">
    <div class="row">
        <div class="col-7 align-self-center">
            <h4 class="page-title text-dark font-weight-medium mb-1">Exchange</h4>
            <div class="d-flex align-items-center">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb m-0 p-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}" class="text-muted">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('exchange') }}" class="text-muted">Exchange</a></li>
                        <li class="breadcrumb-item text-muted active" aria-current="page">List</li>
                    </ol>
                </nav>
            </div>
        </div>
        <div class="col-5 align-self-center">
            <div class="customize-input float-right">
                <a class="btn btn-outline-primary btn-rounded waves-effect" href="{{ route('exchange.create') }}">Add New</a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid mt-3">
    <div class="card">
        <div class="card-body" style="min-width:100% !important;">
            <table class="table table-bordered data-table" id="data-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Customer Name</th>
                        <th>Seller Detail</th>
                        <th>Car Name</th>
                        <th>Registration Number</th>
                        <th>Chasis Number</th>
                        <th>Engine Number</th>
                        <th>Amount</th>
                        <th>Remarks</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

<!-- Cancel Reason Modal -->
<div class="modal fade" id="DescModal" tabindex="-1" role="dialog" aria-labelledby="DescModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Cancel Reason</h3>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">&times;</button>
            </div>
            <form>
                <div class="modal-body">
                    <input type="hidden" name="id" id="id" value="">
                    <label for="cancel_reason">Enter Your Reason</label>
                    <textarea class="form-control" name="cancel_reason" id="cancel_reason" placeholder="Please Enter Your Reason" rows="4"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary btn-sm pull-right" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" id="submit-reason" class="btn btn-outline-primary btn-sm pull-right">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Cancel Reason Modal -->
<div class="modal fade" id="SellModal" tabindex="-1" role="dialog" aria-labelledby="SellModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Selling Details</h3>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">&times;</button>
            </div>
            <form>
                <div class="modal-body">
                    <div class="row">
                        <input type="hidden" name="id" id="exchange_id" value="">
                        <div class="col-md-12">
                            <label for="customer_name" style="color:black;">Customer Name</label>
                            <input type="text" name="customer_name" id="customer_name" class="form-control" placeholder="Enter Customer Name">
                        </div>
                        
                        <div class="col-md-12">
                            <label for="contact_no" style="color:black;">Contact No.</label>
                            <input type="text" name="contact_no" id="contact_no" class="form-control" placeholder="Enter Contact No.">
                        </div>
                        
                        <div class="col-md-12">
                            <label for="address" style="color:black;">Address</label>
                            <textarea class="form-control" name="address" id="address" placeholder="Please Enter Address" rows="2"></textarea>
                        </div>
                        
                        <div class="col-md-12">
                            <label class="control-label" style="color: black;">Branch</label>
                            <select name="branch" id="branch" class="form-control">
                                <option value="">Select Branch</option>
                                @if(isset($branch) && $branch->isNotEmpty())
                                    @foreach($branch AS $branch)
                                        <option value="{{ $branch->id }}">{{ $branch->name }}</option>
                                    @endforeach
                                @endif
                            </select>
                        </div>
                        
                        <div class="col-md-12">
                            <label for="remark" style="color:black;">Enter Your Remark</label>
                            <textarea class="form-control" name="remark" id="remark" placeholder="Please Enter Your Remark" rows="4"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary btn-sm pull-right" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" id="submit-sell" class="btn btn-outline-primary btn-sm pull-right">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    
    window.cancel_reason_reject = function(object) {
        var id = $(object).data("id");
        $('#DescModal').modal("show");
        $('#id').val(id);
    };
        
        
    $(document).ready(function () {
        // Attach the click handler here
        $('#submit-reason').on('click', function () {
            const id = $('#id').val();
            const reason = $('#cancel_reason').val();

            if (!reason.trim()) {
                toastr.warning("Please enter a reason.");
                return;
            }

            $('#DescModal').modal("hide");
            
            $.ajax({
                url: "{{ route('exchange.cancel.reason') }}",
                type: "POST",
                dataType: "json",
                data: {
                    id: id,
                    cancel_reason: reason,
                    status: 'deleted',
                    _token: "{{ csrf_token() }}"
                },
                success: function (response) {
                    if (response.code === 200) {
                        datatable.ajax.reload();
                        toastr.success('Cancelled successfully', 'Success');
                    } else {
                        toastr.error('Failed to cancel', 'Error');
                    }
                },
                error: function () {
                    toastr.error('Something went wrong', 'Error');
                }
            });
        });
    });
</script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script>
    var datatable;

    $(document).ready(function () {
        datatable = $('#data-table').DataTable({
            processing: true,
            serverSide: true,
            pageLength: 25,
            responsive: true,
            scrollY: '400px',
            scrollCollapse: true,
            paging: true,
            searching: false,
            aaSorting: [],
            ajax: {
                url: "{{ route('exchange') }}",
                type: "POST",
                dataType: "json",
                data: {
                    _token: "{{ csrf_token() }}"
                }
            },
            columns: [
                { data: 'DT_RowIndex', name: 'DT_RowIndex' },
                { data: 'customer_name', name: 'customer_name' },
                { data: 'seller_detail', name: 'seller_detail' },
                { data: 'car_name', name: 'car_name' },
                { data: 'registeration_number', name: 'registeration_number' },
                { data: 'chassis_number', name: 'chassis_number' },
                { data: 'engine_number', name: 'engine_number' },
                { data: 'amount', name: 'amount' },
                { data: 'remarks', name: 'remarks' },
                { data: 'status', name: 'status' },
                { data: 'action', name: 'action', orderable: false },
            ]
        });

        // Highlight on hover
        $('#data-table tbody').on('mouseover', 'tr', function () {
            $(this).addClass('highlight');
        }).on('mouseout', 'tr', function () {
            $(this).removeClass('highlight');
        });
        
        $(document).on('click', '.change-status', function () {
            var id = $(this).data("id");
            var status = $(this).data("status");

            if (confirm('Are you sure?')) {
                $.ajax({
                    "url": "{!! route('exchange.change.status') !!}",
                    "dataType": "json",
                    "type": "POST",
                    "data": {
                        id: id,
                        status: status,
                        _token: "{{ csrf_token() }}" 
                    },
                    success: function(response) {
                        if (response.code == 200) {
                            $('#datatable').DataTable().ajax.reload();
                            toastr.success('Status changed successfully', 'Success');
                            location.reload();
                        } else {
                            toastr.error('Failed to change status', 'Error');
                        }
                    }
                });
            }
        }); 
        
        $(document).on('click', '.sell-status', function () {
            var id = $(this).data("id");
            var status = $(this).data("status");
            $('#SellModal').modal("show"); 
            var exchange_id = atob(id);
            $('#exchange_id').val(exchange_id);
        });    
        
        $('#submit-sell').on('click', function () {
            const id = $('#exchange_id').val();
            const customer_name = $('#customer_name').val();
            const contact_no = $('#contact_no').val();
            const address = $('#address').val();
            const branch = $('#branch').val();
            const remark = $('#remark').val();

            if (!customer_name.trim()) {
                toastr.warning("Please enter a customer name.");
                return;
            }
            
            if (!contact_no.trim()) {
                toastr.warning("Please enter a contact no.");
                return;
            }
            
            if (!address.trim()) {
                toastr.warning("Please enter a address");
                return;
            }
            
            if (!branch.trim()) {
                toastr.warning("Please select a branch");
                return;
            }

            $('#SellModal').modal("hide");
            
            $.ajax({
                url: "{{ route('exchange.sell') }}",
                type: "POST",
                dataType: "json",
                data: {
                    id: id,
                    customer_name: customer_name,
                    contact_no: contact_no,
                    address: address,
                    branch: branch,
                    status: 'sell',
                    remark: remark,
                    _token: "{{ csrf_token() }}"
                },
                success: function (response) {
                    if (response.code === 200) {
                        datatable.ajax.reload();
                        toastr.success('Sell successfully', 'Success');
                    } else {
                        toastr.error('Failed to sell', 'Error');
                    }
                },
                error: function () {
                    toastr.error('Something went wrong', 'Error');
                }
            });
        });
    });
</script>
@endsection
