@extends('layouts.dashboard.superadminapp')

@section('title', 'GRN List')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .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;
    }
</style>
@endsection

@section('content')
    <!-- 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 | GRN List</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>

    <!-- Alerts -->
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>
            <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <!-- Table Section -->
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
            <h6 class="m-0 font-weight-bold text-white">
                <i class="fas fa-clipboard-check mr-2"></i> GRN List
            </h6>
            <div>
                <button type="button" class="btn btn-light btn-sm mr-2" data-toggle="modal" data-target="#importModal" title="Import Excel">
                    <i class="fas fa-file-import mr-1"></i> Import
                </button>
                <a href="{{ route('superadmin.grn.grnorder') }}" class="btn btn-light btn-sm" title="Add GRN">
                    <i class="fas fa-plus mr-1"></i> Add GRN
                </a>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-sm" id="grnTable" width="100%" cellspacing="0">
                    <thead class="thead-light">
                        <tr>
                            <th>GRN ID</th>
                            <th>GRN Date</th>
                            <th>Order ID</th>
                            <th>Order Date</th>
                            <th>Company Name</th>
                            <th>Quotation ID</th>
                            <th>RFQ ID</th>
                            <th>Part No</th>
                            <th>Status</th>
                            <th>Challan</th>
                            <th>Product Type</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($grns as $grn)
                            <tr id="row-{{ $grn->id }}">
                                <td>{{ $grn->grn_no }}</td>
                                <td>{{ $grn->grn_date ? \Carbon\Carbon::parse($grn->grn_date)->format('d M Y') : '-' }}</td>
                                <td>{{ $grn->order_no ?? '-' }}</td>
                                <td>{{ $grn->order_date ? \Carbon\Carbon::parse($grn->order_date)->format('d M Y') : '-' }}</td>
                                <td>{{ $grn->company_name ?? '-' }}</td>
                                <td>{{ $grn->quotation_no ?? '-' }}</td>
                                <td>{{ $grn->rfq_no ?? '-' }}</td>
                                <td>{{ $grn->part_no ?? '-' }}</td>
                                <td>
                                    @if($grn->status == 'approved')
                                        <span class="badge badge-success">Approved</span>
                                    @else
                                        <span class="badge badge-warning">Pending</span>
                                    @endif
                                </td>
                                <td class="text-center">
                                    @if ($grn->challan_file)
                                        <a href="{{ asset('storage/' . $grn->challan_file) }}" target="_blank" class="btn btn-info btn-sm" title="View Challan">
                                            <i class="fa fa-file-pdf"></i>
                                        </a>
                                    @else
                                        -
                                    @endif
                                </td>
                                <td>{{ $grn->product_type ?? '-' }}</td>
                                <td class="text-center" style="white-space: nowrap;">
                                    @if($grn->status != 'approved')
                                        <button class="btn btn-success btn-sm approve-btn" title="Approve" data-id="{{ $grn->id }}">
                                            <i class="fa fa-check"></i>
                                        </button>
                                    @endif
                                    <a href="{{ route('superadmin.grn.view', $grn->id) }}" class="btn btn-info btn-sm" title="View">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <a href="{{ route('superadmin.grn.edit', $grn->id) }}" class="btn btn-warning btn-sm" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    <button class="btn btn-danger btn-sm delete-btn" title="Delete" data-id="{{ $grn->id }}">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Bulk Import Modal -->
    <div class="modal fade" id="importModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form method="POST" action="{{ route('superadmin.grn.import') }}" enctype="multipart/form-data">
                    @csrf
                    <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                        <h5 class="modal-title text-white"><i class="fas fa-file-import mr-2"></i>Import GRN Excel</h5>
                        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="small font-weight-bold">Select Excel File <span class="text-danger">*</span></label>
                            <input type="file" name="file" class="form-control" required accept=".xls,.xlsx">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-upload mr-1"></i> Import</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        // DataTable with export buttons
        $('#grnTable').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' }
            ],
            pageLength: 10,
            responsive: true,
            language: {
                "emptyTable": "No GRN records found"
            }
        });

        // Handle approve button
        $(document).on('click', '.approve-btn', function() {
            var id = $(this).data('id');
            Swal.fire({
                title: 'Approve GRN?',
                text: "This will update stock levels. Continue?",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, Approve!',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '{{ url("superadmin/grn/approve") }}/' + id,
                        type: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}'
                        },
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Approved!', response.message, 'success')
                                    .then(() => location.reload());
                            } else {
                                Swal.fire('Error!', response.message || 'Failed to approve.', 'error');
                            }
                        },
                        error: function(xhr) {
                            Swal.fire('Error!', 'Failed to approve GRN.', 'error');
                        }
                    });
                }
            });
        });

        // Handle delete button with SweetAlert
        $(document).on('click', '.delete-btn', function() {
            var id = $(this).data('id');
            Swal.fire({
                title: 'Delete GRN?',
                text: "Are you sure you want to delete this GRN record?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, Delete!',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '{{ url("superadmin/grn/delete") }}/' + id,
                        type: 'DELETE',
                        data: {
                            _token: '{{ csrf_token() }}'
                        },
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Deleted!', 'GRN record deleted successfully.', 'success')
                                    .then(() => location.reload());
                            } else {
                                Swal.fire('Error!', 'Failed to delete GRN record.', 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error!', 'Failed to delete GRN record.', 'error');
                        }
                    });
                }
            });
        });
    });
</script>
@endsection
