@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<style>
/* ==================== MODERN PAGE HEADER ==================== */
.page-header-compact {
    background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
    border-radius: 1rem;
    padding: 1.25rem 1.5rem;
    box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
    margin-bottom: 1.5rem;
}

.page-header-compact h1 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.page-header-compact h1 i {
    color: #06b6d4;
    font-size: 1.125rem;
}

.datetime-display {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex-wrap: wrap;
}

.datetime-display .time {
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 500;
    font-family: 'SF Mono', 'Monaco', monospace;
    background: #f1f5f9;
    padding: 0.375rem 0.75rem;
    border-radius: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.375rem;
}

.datetime-display .time i {
    color: #06b6d4;
}

/* ==================== STAT CARDS ==================== */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.stat-card {
    background: #fff;
    border-radius: 0.75rem;
    padding: 1.25rem;
    box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
    transition: all 0.2s ease;
    border-left: 4px solid;
    position: relative;
    overflow: hidden;
}

.stat-card:hover {
    box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
    transform: translateY(-2px);
}

.stat-card.teal { border-color: #06b6d4; }
.stat-card.green { border-color: #10b981; }
.stat-card.red { border-color: #ef4444; }
.stat-card.amber { border-color: #f59e0b; }

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    opacity: 0.1;
    transform: translate(30%, -30%);
}

.stat-card.teal::before { background: #06b6d4; }
.stat-card.green::before { background: #10b981; }
.stat-card.red::before { background: #ef4444; }
.stat-card.amber::before { background: #f59e0b; }

.stat-icon {
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    margin-bottom: 0.75rem;
    color: #fff;
}

.stat-card.teal .stat-icon { background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); }
.stat-card.green .stat-icon { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.stat-card.red .stat-icon { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
.stat-card.amber .stat-icon { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }

.stat-label {
    font-size: 0.75rem;
    font-weight: 600;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 0.375rem;
}

.stat-value {
    font-size: 1.75rem;
    font-weight: 700;
    color: #1e293b;
}

/* ==================== TABLE CARD ==================== */
.table-card {
    background: #fff;
    border-radius: 1rem;
    overflow: hidden;
    box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
}

.table-card-header {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    padding: 1rem 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.table-card-title {
    font-size: 1rem;
    font-weight: 600;
    color: #fff;
    display: flex;
    align-items: center;
    gap: 0.625rem;
}

.header-actions {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.btn-import, .btn-add-new {
    background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
    color: #06b6d4;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 0.5rem;
    font-weight: 500;
    font-size: 0.9375rem;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-import:hover, .btn-add-new:hover {
    box-shadow: 0 4px 12px rgba(255, 255, 255, 0.3);
    transform: translateY(-1px);
    color: #0891b2;
}

.table-card-body {
    padding: 1.5rem;
}

/* ==================== DATATABLE ENHANCEMENTS ==================== */
div.dt-buttons {
    float: left;
    display: flex !important;
    margin-bottom: 1rem;
    gap: 0.5rem;
}

.dt-buttons .btn {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%) !important;
    color: #475569 !important;
    border: 1px solid #e2e8f0 !important;
    padding: 0.5rem 1rem !important;
    border-radius: 0.5rem !important;
    font-size: 0.875rem !important;
    font-weight: 500 !important;
    transition: all 0.2s ease !important;
}

.dt-buttons .btn:hover {
    background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%) !important;
    border-color: #cbd5e1 !important;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
}

.table {
    border-collapse: separate;
    border-spacing: 0;
}

.table thead th {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-bottom: 2px solid #e2e8f0;
    color: #475569;
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.75rem;
    letter-spacing: 0.5px;
    padding: 0.875rem 0.75rem;
    white-space: nowrap;
}

.table tbody tr {
    transition: all 0.15s ease;
}

.table tbody tr:hover {
    background: #f8fafc;
}

.table tbody td {
    padding: 0.875rem 0.75rem;
    vertical-align: middle;
    border-bottom: 1px solid #f1f5f9;
    color: #1e293b;
    font-size: 0.875rem;
}

.table tbody tr:last-child td {
    border-bottom: none;
}

/* ==================== ACTION BUTTONS ==================== */
.btn-group.table-actions {
    display: flex;
    gap: 0.25rem;
}

.table-actions .btn {
    padding: 0.375rem 0.625rem !important;
    font-size: 0.875rem !important;
    border-radius: 0.375rem !important;
    border: none;
    transition: all 0.2s ease;
}

.table-actions .btn-warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: #fff;
}

.table-actions .btn-warning:hover {
    box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
    transform: translateY(-1px);
}

.table-actions .btn-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
}

.table-actions .btn-success:hover {
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
    transform: translateY(-1px);
}

.table-actions .btn-secondary {
    background: linear-gradient(135deg, #64748b 0%, #475569 100%);
    color: #fff;
}

.table-actions .btn-secondary:hover {
    box-shadow: 0 4px 12px rgba(100, 116, 139, 0.4);
    transform: translateY(-1px);
}

.table-actions .btn-danger {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: #fff;
}

.table-actions .btn-danger:hover {
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
    transform: translateY(-1px);
}

.table-actions .btn-info {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    color: #fff;
}

.table-actions .btn-info:hover {
    box-shadow: 0 4px 12px rgba(6, 182, 212, 0.4);
    transform: translateY(-1px);
}

/* ==================== STATUS BADGES ==================== */
.badge {
    padding: 0.375rem 0.75rem;
    border-radius: 9999px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
}

.badge-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    color: #fff !important;
}

.badge-danger {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
    color: #fff !important;
}

.badge-warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
    color: #fff !important;
}

/* ==================== MODAL ENHANCEMENTS ==================== */
.modal-content {
    border: none;
    border-radius: 1rem;
    box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1);
}

.modal-header {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    border-radius: 1rem 1rem 0 0;
    border: none;
    padding: 1.25rem 1.5rem;
}

.modal-header .modal-title {
    font-weight: 600;
    font-size: 1.125rem;
}

.modal-header .close {
    color: #fff;
    opacity: 0.8;
    text-shadow: none;
    font-size: 1.5rem;
}

.modal-header .close:hover {
    opacity: 1;
}

.modal-body {
    padding: 1.5rem;
}

.modal-footer {
    border-top: 1px solid #e2e8f0;
    padding: 1rem 1.5rem;
    background: #f8fafc;
    border-radius: 0 0 1rem 1rem;
}

/* ==================== TOAST NOTIFICATIONS ==================== */
.toast-notification {
    position: fixed;
    top: 2rem;
    right: 2rem;
    background: #fff;
    padding: 1rem 1.25rem;
    border-radius: 0.75rem;
    box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
    display: flex;
    align-items: center;
    gap: 0.75rem;
    min-width: 300px;
    z-index: 9999;
    animation: slideInRight 0.3s ease-out;
}

@keyframes slideInRight {
    from { transform: translateX(400px); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
}

.toast-notification.success {
    border-left: 4px solid #10b981;
}

.toast-notification.success i {
    color: #10b981;
    font-size: 1.25rem;
}

.toast-notification.error {
    border-left: 4px solid #ef4444;
}

.toast-notification.error i {
    color: #ef4444;
    font-size: 1.25rem;
}

.toast-notification span {
    flex: 1;
    color: #1e293b;
    font-weight: 500;
    font-size: 0.9375rem;
}

.toast-notification .close {
    background: none;
    border: none;
    font-size: 1.25rem;
    color: #94a3b8;
    cursor: pointer;
    padding: 0;
    line-height: 1;
}

.toast-notification .close:hover {
    color: #64748b;
}

/* ==================== RESPONSIVE ==================== */
@media (max-width: 768px) {
    .page-header-compact {
        padding: 1rem;
    }

    .page-header-compact h1 {
        font-size: 1.125rem;
    }

    .stats-grid {
        grid-template-columns: 1fr;
    }

    .table-card-body {
        padding: 1rem;
    }

    .toast-notification {
        right: 1rem;
        left: 1rem;
        min-width: auto;
    }
}
</style>
@endsection

@section('content')

<!-- Modern Compact Page Header -->
<div class="page-header-compact d-flex justify-content-between align-items-center flex-wrap">
    <h1>
        <i class="fas fa-truck-loading"></i>
        GRN List
    </h1>
    <div class="datetime-display">
        <span class="time">
            <i class="far fa-clock"></i>
            <span id="currentTime"></span>
        </span>
    </div>
</div>

<!-- Stat Cards -->
<div class="stats-grid">
    <div class="stat-card teal">
        <div class="stat-icon">
            <i class="fas fa-clipboard-check"></i>
        </div>
        <div class="stat-label">Total GRNs</div>
        <div class="stat-value">{{ $grns->count() }}</div>
    </div>

    <div class="stat-card green">
        <div class="stat-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-label">Approved</div>
        <div class="stat-value">{{ $grns->where('status', 'approved')->count() }}</div>
    </div>

    <div class="stat-card red">
        <div class="stat-icon">
            <i class="fas fa-times-circle"></i>
        </div>
        <div class="stat-label">Rejected</div>
        <div class="stat-value">{{ $grns->where('status', 'rejected')->count() }}</div>
    </div>

    <div class="stat-card amber">
        <div class="stat-icon">
            <i class="fas fa-clock"></i>
        </div>
        <div class="stat-label">Pending</div>
        <div class="stat-value">{{ $grns->where('status', '!=', 'approved')->where('status', '!=', 'rejected')->count() }}</div>
    </div>
</div>

<!-- Table Card -->
<div class="table-card">
    <div class="table-card-header">
        <div class="table-card-title">
            <i class="fas fa-table"></i>
            GRN Details
        </div>
        <div class="header-actions">
            <button type="button" class="btn-import" data-toggle="modal" data-target="#importModal">
                <i class="fas fa-file-import"></i> Import Excel
            </button>
            <a href="{{ route('superadmin.grn.grnorder') }}" class="btn-add-new">
                <i class="fas fa-plus"></i> Add GRN
            </a>
        </div>
    </div>
    <div class="table-card-body">
        <div class="table-responsive">
            <table class="table table-hover w-100" id="grnTable">
                <thead>
                    <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>
                                @elseif($grn->status == 'rejected')
                                    <span class="badge badge-danger">Rejected</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>
                                <div class="btn-group table-actions" role="group">
                                    @if($grn->status != 'approved' && $grn->status != 'rejected')
                                        <button class="btn btn-success approve-btn" title="Approve" data-id="{{ $grn->id }}">
                                            <i class="fa fa-check"></i>
                                        </button>
                                        <button class="btn btn-secondary reject-btn" title="Reject" data-id="{{ $grn->id }}">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    @endif
                                    <a href="{{ route('superadmin.grn.view', $grn->id) }}" class="btn btn-info" title="View">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <a href="{{ route('superadmin.grn.edit', $grn->id) }}" class="btn btn-warning" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    <button class="btn btn-danger delete-btn" title="Delete" data-id="{{ $grn->id }}">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 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">
                    <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 class="mb-3">
                        <a href="{{ route('superadmin.grn.download-template') }}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-download mr-1"></i> Download Import Template
                        </a>
                        <small class="d-block text-muted mt-1">Download the Excel template and fill it with your GRN data before importing.</small>
                    </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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

@section('scripts')
<script>
// ==================== LIVE DATE & TIME ====================
function updateDateTime() {
    const now = new Date();
    const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
    document.getElementById('currentTime').textContent = now.toLocaleTimeString('en-US', timeOptions);
}
setInterval(updateDateTime, 1000);
updateDateTime();

// ==================== TOAST NOTIFICATIONS ====================
function showToast(type, message) {
    const toast = document.createElement('div');
    toast.className = `toast-notification ${type}`;
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
        <span>${message}</span>
        <button class="close" onclick="this.parentElement.remove()">&times;</button>
    `;
    document.body.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.remove();
        }
    }, 3500);
}

// Show session messages as toasts
@if (session('success'))
    showToast('success', "{{ session('success') }}");
@endif
@if (session('error'))
    showToast('error', "{{ session('error') }}");
@endif
@if ($errors->any())
    showToast('error', "{{ $errors->first() }}");
@endif

// ==================== DATATABLE INITIALIZATION ====================
$(document).ready(function() {
    $('#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"
        }
    });

    // ==================== APPROVE GRN ====================
    $(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: '#10b981',
            cancelButtonColor: '#06b6d4',
            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');
                    }
                });
            }
        });
    });

    // ==================== REJECT GRN ====================
    $(document).on('click', '.reject-btn', function() {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Reject GRN?',
            text: "Are you sure you want to reject this GRN?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#06b6d4',
            confirmButtonText: 'Yes, Reject!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("superadmin/grn/reject") }}/' + id,
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Rejected!', response.message, 'success')
                                .then(() => location.reload());
                        } else {
                            Swal.fire('Error!', response.message || 'Failed to reject.', 'error');
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error!', 'Failed to reject GRN.', 'error');
                    }
                });
            }
        });
    });

    // ==================== DELETE GRN ====================
    $(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? This action cannot be undone.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#06b6d4',
            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
