@extends('layouts.dashboard.adminapp')

@section('title', 'Route Card Details')

<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
        margin-bottom: 1rem;
    }

    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }

    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }

    .btn-delete {
        min-width: 80px;
    }

    .page-header-icon {
        font-size: 2rem;
        color: #506690;
        vertical-align: middle;
    }
</style>

@section('content')
    @if (session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger">{{ session('error') }}</div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <!-- Page Heading -->
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL / Route Card Datatable</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>

    <!-- Card Table -->
    <div class="card shadow mb-4">
        <div class="card-header d-flex justify-content-between align-items-center gap-3">
            <span class="fw-bold"></span>
            <a href="{{ route('admin.routecard.routecardorder') }}" class="btn btn-primary" title="New Route Card">
                <i class="fas fa-plus-square"></i>
            </a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover text-dark w-100" id="routeCardTable">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th>RC ID</th>
                            <th>RC Date</th>
                            <th>GRN ID</th>
                            <th>GRN Date</th>
                            <th>Order ID</th>
                            <th>Order Date</th>
                            <th>Order Reference No</th>
                            <th>Quotation ID</th>
                            <th>RFQ ID</th>
                            <th>Company Name</th>
                            <th>Company Email</th>
                            <th>Phone Number</th>
                            <th>Company Address</th>
                            <th>GST</th>
                            <th>Part No</th>
                            <th>Project Material No</th>
                            <th>Drawing ID</th>
                            <th>Drawing Revision</th>
                            <th>Description</th>
                            <th>Product Type</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($cards as $card)
                            <tr class="text-center align-middle" id="row-{{ $card->id }}">
                                <td>{{ $card->route_no }}</td>
                                <td>{{ $card->route_date }}</td>
                                <td>{{ $card->grn_no }}</td>
                                <td>{{ $card->grn_date }}</td>
                                <td>{{ $card->order_no }}</td>
                                <td>{{ $card->order_date }}</td>
                                <td>{{ $card->order_ref_no }}</td>
                                <td>{{ $card->quotation_no }}</td>
                                <td>{{ $card->rfq_no }}</td>
                                <td>{{ $card->company_name }}</td>
                                <td>{{ $card->company_email }}</td>
                                <td>{{ $card->company_phone }}</td>
                                <td>{{ $card->company_address }}</td>
                                <td>{{ $card->company_gstn }}</td>
                                <td>{{ $card->part_no }}</td>
                                <td>{{ $card->project_material_no }}</td>
                                <td>{{ $card->drawing_no }}</td>
                                <td>{{ $card->drawing_rev }}</td>
                                <td>{{ $card->description }}</td>
                                <td>{{ $card->product_type }}</td>
                                <td>
                                    @if ($card->status == 'Approved')
                                        <span class="badge badge-success">{{ $card->status }}</span>
                                    @elseif($card->status == 'Rejected')
                                        <span class="badge badge-danger">{{ $card->status }}</span>
                                    @else
                                        <span class="badge badge-warning">{{ $card->status }}</span>
                                    @endif
                                    @if ($card->approved_by)
                                        <br><small>By: {{ $card->approved_by }}</small>
                                        <br><small>At:
                                            {{ $card->approved_at ? \Carbon\Carbon::parse($card->approved_at)->format('d-m-Y H:i') : '' }}</small>
                                    @endif
                                </td>
                                <td>
                                    <a href="{{ route('admin.routecard.show', $card->id) }}"
                                        class="btn btn-primary btn-sm mb-1" title="View"><i class="fa fa-eye"></i></a>
                                    <a href="{{ route('admin.routecard.edit', $card->id) }}"
                                        class="btn btn-warning btn-sm mb-1" title="Edit"> <i class="fa fa-edit"></i> </a>
                                    <button class="btn btn-danger btn-sm mb-1 delete-btn" title="Delete"
                                        data-id="{{ $card->id }}"><i class="fa fa-trash"></i></button>
                                    @if ($card->status == 'Pending')
                                        <button class="btn btn-success btn-sm mb-1 status-btn" title="Approve/Reject"
                                            data-id="{{ $card->id }}"><i class="fa fa-check-circle"></i>/<i class="fa fa-times-circle"></i></button>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Approval Popup Modal -->
    <div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="statusModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form id="statusForm" class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="statusModalLabel">Change Status</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                        onclick="$('#statusModal').modal('hide')">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="status-card-id">
                    <div class="form-group">
                        <label>Status</label>
                        <select class="form-control" id="status-select" required>
                            <option value="Approved">Approve</option>
                            <option value="Rejected">Reject</option>
                            <option value="Pending">Pending</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Approved By</label>
                        <input type="text" class="form-control" id="approved-by" placeholder="Enter name" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"
                        onclick="$('#statusModal').modal('hide')">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        $(document).ready(function() {
            $('#routeCardTable').DataTable({
                dom: 'Bfrtip',
                buttons: [{
                        extend: 'copy',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'csv',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'excel',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'pdf',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'print',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'colvis',
                        className: 'btn btn-secondary btn-sm'
                    }
                ],
                responsive: true,
                destroy: true,
            });

            // Handle delete button (you should implement the backend route for deleting)
            // $(document).on('click', '.delete-btn', function() {
            //     var id = $(this).data('id');
            //     if (confirm('Are you sure you want to delete this route card?')) {
            //         fetch(`{{ url('admin/routecard/delete') }}/${id}`, {
            //                 method: 'DELETE',
            //                 headers: {
            //                     'X-CSRF-TOKEN': '{{ csrf_token() }}',
            //                     'Accept': 'application/json',
            //                 },
            //             })
            //             .then(res => res.json())
            //             .then(data => {
            //                 if (data.success) {
            //                     $(`#row-${id}`).remove();
            //                 } else {
            //                     alert('Delete failed');
            //                 }
            //             })
            //             .catch(() => alert('Error deleting record'));
            //     }
            // });
        });
    </script>
    <script>
        $(document).on('click', '.delete-btn', function() {
            var id = $(this).data('id');
            if (confirm('Are you sure you want to delete this route card?')) {
                fetch(`{{ url('admin/routecard') }}/${id}`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json',
                        },
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            $('#row-' + id).remove();
                            alert('Deleted successfully!');
                        } else {
                            alert('Delete failed!');
                        }
                    })
                    .catch(() => alert('Error deleting record'));
            }
        });
    </script>
    <script>
        $(document).ready(function() {
            // Open modal
            $(document).on('click', '.status-btn', function() {
                var id = $(this).data('id');
                $('#status-card-id').val(id);
                $('#status-select').val('Approved');
                $('#approved-by').val('');
                $('#statusModal').modal('show');
            });

            // Submit approval
            $('#statusForm').on('submit', function(e) {
                e.preventDefault();
                var id = $('#status-card-id').val();
                var status = $('#status-select').val();
                var approvedBy = $('#approved-by').val();
                fetch(`{{ url('admin/routecard/approve') }}/${id}`, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            status: status,
                            approved_by: approvedBy
                        })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            // Optionally update UI without reload:
                            $('#statusModal').modal('hide');
                            location.reload();
                        } else {
                            alert('Status update failed!');
                        }
                    }).catch(() => alert('Error updating status!'));
            });
        });
    </script>

@endsection
