@extends('layouts.dashboard.superadminapp')

@section('title', 'Manufacturing Plans')

@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;
    }
    .table-actions .btn {
        padding: 0.2rem 0.4rem;
        font-size: 0.75rem;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Manufacturing Plans" icon="route" iconColor="warning" />

<!-- 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

<!-- Card Table -->
<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-project-diagram mr-2"></i> Manufacturing Plans
        </h6>
        <a href="{{ route('superadmin.routecard.index') }}" class="btn btn-light btn-sm" title="Create New Plan">
            <i class="fas fa-plus mr-1"></i> Create Plan
        </a>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-sm" id="routeCardTable" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr>
                        <th>Plan ID</th>
                        <th>Plan Date</th>
                        <th>Order ID</th>
                        <th>Order Date</th>
                        <th>Company Name</th>
                        <th>Product Type</th>
                        <th>Project Start</th>
                        <th>Status</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($cards as $card)
                        <tr id="row-{{ $card->id }}">
                            <td>{{ $card->route_no }}</td>
                            <td>{{ $card->route_date ? \Carbon\Carbon::parse($card->route_date)->format('d M Y') : '-' }}</td>
                            <td>{{ $card->order_no ?? '-' }}</td>
                            <td>{{ $card->order_date ? \Carbon\Carbon::parse($card->order_date)->format('d M Y') : '-' }}</td>
                            <td>{{ $card->company_name ?? '-' }}</td>
                            <td>{{ $card->product_type ?? '-' }}</td>
                            <td>{{ $card->project_start_date ? \Carbon\Carbon::parse($card->project_start_date)->format('d M Y') : '-' }}</td>
                            <td>
                                @if ($card->status == 'approved')
                                    <span class="badge badge-success">Approved</span>
                                @elseif($card->status == 'rejected')
                                    <span class="badge badge-danger">Rejected</span>
                                @elseif($card->status == 'planned')
                                    <span class="badge badge-info">Planned</span>
                                @elseif($card->status == 'ready_to_production')
                                    <span class="badge badge-primary">Ready</span>
                                @elseif($card->status == 'in_production')
                                    <span class="badge badge-warning">In Progress</span>
                                @else
                                    <span class="badge badge-secondary">{{ ucfirst($card->status ?? 'Pending') }}</span>
                                @endif
                            </td>
                            <td>
                                <div class="btn-group table-actions" role="group">
                                    <a href="{{ route('superadmin.routecard.show', $card->id) }}" class="btn btn-info btn-sm" title="View">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <a href="{{ route('superadmin.routecard.edit', $card->id) }}" class="btn btn-warning btn-sm" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    @if ($card->status == 'pending' || $card->status == null)
                                        <button class="btn btn-success btn-sm approve-btn" title="Approve" data-id="{{ $card->id }}">
                                            <i class="fa fa-check"></i>
                                        </button>
                                    @endif
                                    <button class="btn btn-danger btn-sm delete-btn" title="Delete" data-id="{{ $card->id }}">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Approval Modal -->
<div class="modal fade" id="statusModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="statusForm">
                <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                    <h5 class="modal-title text-white"><i class="fas fa-check-circle mr-2"></i>Approve Route Card</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="status-card-id">
                    <p class="text-muted">Are you sure you want to approve this route card?</p>
                </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-success btn-sm"><i class="fa fa-check mr-1"></i> Approve</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<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' }
        ],
        pageLength: 10,
        responsive: true,
        language: {
            "emptyTable": "No route cards found"
        }
    });

    // Handle delete button with SweetAlert
    $(document).on('click', '.delete-btn', function() {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Delete Route Card?',
            text: "Are you sure you want to delete this route card?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, Delete!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('{{ url("superadmin/routecard") }}/' + id, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json',
                    },
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire('Deleted!', 'Route card deleted successfully.', 'success')
                            .then(() => location.reload());
                    } else {
                        Swal.fire('Error!', data.message || 'Failed to delete route card.', 'error');
                    }
                })
                .catch(() => Swal.fire('Error!', 'Failed to delete route card.', 'error'));
            }
        });
    });

    // Handle approve button
    $(document).on('click', '.approve-btn', function() {
        var id = $(this).data('id');
        $('#status-card-id').val(id);
        $('#statusModal').modal('show');
    });

    // Submit approval
    $('#statusForm').on('submit', function(e) {
        e.preventDefault();
        var id = $('#status-card-id').val();
        fetch('{{ url("superadmin/routecard") }}/' + id + '/approve', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({})
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                $('#statusModal').modal('hide');
                Swal.fire('Approved!', 'Route card approved successfully.', 'success')
                    .then(() => location.reload());
            } else {
                Swal.fire('Error!', 'Status update failed!', 'error');
            }
        })
        .catch(() => Swal.fire('Error!', 'Error updating status!', 'error'));
    });
});
</script>
@endsection
