@extends('layouts.dashboard.superadminapp')

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

@section('styles')
    <!-- DataTables Bootstrap 5 styling for buttons -->
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
    <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 | Purchase Order 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

    <!-- 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-shopping-cart mr-2"></i> Purchase Order List
            </h6>
            <a href="{{ route('superadmin.purchase.purchaseorder') }}" class="btn btn-light btn-sm" title="Add Purchase Order">
                <i class="fas fa-plus mr-1"></i> Add PO
            </a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-sm" id="purchaseOrderTable" width="100%" cellspacing="0">
                    <thead class="thead-light">
                        <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') }}" style="color:white">
                                        {{ ucfirst($po->status ?? 'pending') }}
                                    </span>
                                </td>
                                <td class="text-center" style="white-space: nowrap;">
                                    @if ($po->status === 'pending')
                                        <button class="btn btn-outline-success btn-sm approve-btn" data-id="{{ $po->id }}" title="Approve">
                                            <i class="fa fa-check"></i>
                                        </button>
                                        <button class="btn btn-outline-danger btn-sm 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 btn-sm">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <a href="{{ route('superadmin.purchase.order.print', $po->id) }}" title="Print" target="_blank" class="btn btn-success btn-sm">
                                        <i class="fa fa-print"></i>
                                    </a>
                                    <a href="{{ route('superadmin.purchase.order.edit', $po->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" data-id="{{ $po->id }}" title="Delete">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function() {
            var table = $('#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"
                }
            });

            // Delete with SweetAlert confirmation
            $(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?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    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');
                            }
                        });
                    }
                });
            });
        });
      $(document).ready(function() {
    // Approve PO
    $(document).on('click', '.approve-btn', function () {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Approve this Purchase Order?',
            text: "Are you sure you want to APPROVE this order?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, Approve'
        }).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()); // ✅ Reload after alert
                    },
                    error: function () {
                        Swal.fire('Error!', 'Failed to approve the purchase order.', 'error')
                            .then(() => location.reload()); // ✅ Reload after alert
                    }
                });
            }
        });
    });
    
    // Reject PO
    $(document).on('click', '.reject-btn', function () {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Reject this Purchase Order?',
            text: "Are you sure you want to REJECT this order?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Reject'
        }).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()); // ✅ Reload after alert
                    },
                    error: function () {
                        Swal.fire('Error!', 'Failed to reject the purchase order.', 'error')
                            .then(() => location.reload()); // ✅ Reload after alert
                    }
                });
            }
        });
    });

});

    </script>
@endsection
