@extends('layouts.dashboard.superadminapp')

@section('title', 'Purchase Order List')

@section('styles')
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
<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;
}

.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-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;
}

.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.bg-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    color: #fff !important;
}

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

.badge.bg-secondary {
    background: linear-gradient(135deg, #64748b 0%, #475569 100%) !important;
    color: #fff !important;
}

/* ==================== 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-shopping-bag"></i>
        Purchase Order 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-shopping-cart"></i>
        </div>
        <div class="stat-label">Total Purchase Orders</div>
        <div class="stat-value">{{ $purchaseOrders->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">{{ $purchaseOrders->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">{{ $purchaseOrders->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">{{ $purchaseOrders->where('status', 'pending')->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>
            Purchase Order Details
        </div>
        <a href="{{ route('superadmin.purchase.purchaseorder') }}" class="btn-add-new">
            <i class="fas fa-plus"></i> Add Purchase Order
        </a>
    </div>
    <div class="table-card-body">
        <div class="table-responsive">
            <table class="table table-hover w-100" id="purchaseOrderTable">
                <thead>
                    <tr>
                        <th>Purchase Order No.</th>
                        <th>Date</th>
                        <th>Vendor Name</th>
                        <th>Quotation No.</th>
                        <th class="text-right">Grand Total</th>
                        <th class="text-center">Status</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($purchaseOrders as $po)
                        <tr id="row-{{ $po->id }}">
                            <td>{{ $po->purchase_order_no }}</td>
                            <td>{{ \Carbon\Carbon::parse($po->purchase_order_date)->format('d M Y') }}</td>
                            <td>{{ $po->vendor ? $po->vendor->company : $po->company_name }}</td>
                            <td>{{ $po->quotation_no ?? '-' }}</td>
                            <td class="text-right">₹{{ number_format($po->grand_total, 2) }}</td>
                            <td class="text-center">
                                <span class="badge {{ $po->status === 'approved' ? 'bg-success' : ($po->status === 'rejected' ? 'bg-danger' : 'bg-secondary') }}">
                                    {{ ucfirst($po->status ?? 'pending') }}
                                </span>
                            </td>
                            <td>
                                <div class="btn-group table-actions" role="group">
                                    @if ($po->status === 'pending')
                                        <button class="btn btn-success approve-btn" data-id="{{ $po->id }}" title="Approve">
                                            <i class="fa fa-check"></i>
                                        </button>
                                        <button class="btn btn-secondary reject-btn" data-id="{{ $po->id }}" title="Reject">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    @endif
                                    <a href="{{ route('superadmin.purchase.order.show', $po->id) }}" title="View" class="btn btn-info">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <a href="{{ route('superadmin.purchase.order.print', $po->id) }}" title="Print" target="_blank" class="btn btn-secondary">
                                        <i class="fa fa-print"></i>
                                    </a>
                                    <a href="{{ route('superadmin.purchase.order.edit', $po->id) }}" class="btn btn-warning" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    <button class="btn btn-danger delete-btn" data-id="{{ $po->id }}" title="Delete">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

@endsection

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

@section('scripts')
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<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

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

    // ==================== APPROVE PURCHASE ORDER ====================
    $(document).on('click', '.approve-btn', function () {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Approve Purchase Order?',
            text: "Are you sure you want to approve this purchase order?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10b981',
            cancelButtonColor: '#06b6d4',
            confirmButtonText: 'Yes, Approve',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("superadmin/purchase/order") }}/' + id + '/approve',
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function (response) {
                        Swal.fire('Approved!', response.message || 'Purchase Order approved.', 'success')
                            .then(() => location.reload());
                    },
                    error: function () {
                        Swal.fire('Error!', 'Failed to approve the purchase order.', 'error')
                            .then(() => location.reload());
                    }
                });
            }
        });
    });

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

    // ==================== DELETE PURCHASE ORDER ====================
    $(document).on('click', '.delete-btn', function() {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Delete Purchase Order?',
            text: "Are you sure you want to delete this purchase order? 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/purchase/order") }}/' + id,
                    type: 'DELETE',
                    data: {
                        _token: "{{ csrf_token() }}"
                    },
                    success: function(response) {
                        Swal.fire('Deleted!', response.message || 'Purchase Order deleted successfully.', 'success')
                            .then(() => location.reload());
                    },
                    error: function(xhr) {
                        Swal.fire('Error!', 'Failed to delete purchase order.', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endsection
