@extends('layouts.dashboard.adminapp')

@section('title', 'Ready to Production')

@push('styles')
    <style>
        .process-list-step {
            background: #fffbe9;
            border-radius: 16px;
            padding: 1.1rem 1.5rem 1.1rem 1.3rem;
            margin-bottom: 1.2rem;
            border: 1px solid #f5e3b1;
            box-shadow: 0 1px 6px 0 rgba(80, 102, 144, 0.05);
        }

        .process-step-number {
            width: 2.1rem;
            height: 2.1rem;
            background: #ffeabb;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 1.13rem;
            color: #e2a100;
            margin-right: 0.7rem;
        }

        .process-title {
            font-size: 1.18rem;
            color: #e2a100;
            font-weight: 700;
        }

        .process-label {
            font-size: 1.04rem;
            margin-bottom: 0.1rem;
            color: #847a58;
        }

        .badge-info {
            background: #3db3ff;
            color: #fff;
            font-weight: 500;
        }

        .badge-secondary {
            background: #666;
            color: #fff;
            font-weight: 600;
        }

        .expected-date {
            background: #fff6cb;
            color: #a88600;
            font-size: 1.05rem;
            font-weight: 700;
            padding: 0.18em 0.6em;
            border-radius: 7px;
            margin-top: 0.2em;
            display: inline-block;
        }

        .project-boxes {
            gap: 1.5rem;
            flex-wrap: wrap;
        }

        .box-progress-bar {
            background: #ffeabb;
            border-radius: 2px;
        }

        .project-box {
            border-radius: 22px;
            padding: 1.2rem 1.4rem;
            background: #fff5d4;
            box-shadow: 0 1px 6px 0 rgba(80, 102, 144, 0.06);
            min-width: 350px;
            max-width: 420px;
            transition: box-shadow 0.2s;
            margin-bottom: 0.7rem;
        }

        .project-box:hover {
            box-shadow: 0 4px 14px 0 rgba(80, 102, 144, 0.13);
        }

        .box-progress-header {
            color: #e4a01a;
            font-weight: 600;
            font-size: 1.07rem;
        }

        .box-content-header {
            color: #ce9700;
        }

        .project-box-footer .btn {
            font-size: 0.95rem;
        }

        .list-group-item,
        .table td,
        .table th {
            background: #fffbe9 !important;
        }

        .process-list-toggle {
            user-select: none;
        }

        .table thead th {
            background: #ffedbe !important;
            color: #b27d03;
            border-bottom: 1px solid #f5c97c;
        }

        .badge-info {
            background: #22b7f7 !important;
        }

        .badge-secondary {
            background: #646464 !important;
        }

        .badge-light {
            background: #fff2b2 !important;
            color: #7a6600;
        }

        @media (max-width: 576px) {
            .project-box {
                min-width: 95vw;
                max-width: 100vw;
            }

            .process-list-step {
                padding: 0.8rem 0.5rem 0.8rem 0.7rem;
            }

            .process-title {
                font-size: 1.07rem;
            }

            .expected-date {
                font-size: 0.98rem;
            }

            .table-responsive {
                font-size: 0.93rem;
            }
        }
    </style>
@endpush

@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <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"><a href="#">UEPL</a> / Ready to Production</h1>
        <a href="{{ url('admin/manufacturing/planning') }}" class="btn btn-secondary btn-sm">&larr; Back</a>
    </div>

    <div class="row">
        <div class="col-lg-12">
            <div id="ReadyProductionBoxes" class="project-boxes d-flex flex-wrap"></div>
        </div>
    </div>

    <!-- Toast for notifications -->
    <div id="planToast" class="toast" style="position: fixed; top: 1rem; right: 1rem; min-width: 200px; z-index:9999;">
        <div class="toast-header">
            <strong class="mr-auto" id="planToastTitle">Notice</strong>
            <button type="button" class="ml-2 mb-1 close" onclick="$('#planToast').toast('hide');">&times;</button>
        </div>
        <div class="toast-body" id="planToastBody"></div>
    </div>
@endsection

@push('scripts')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

    <script>
        function showToast(msg, title = 'Notice') {
            $('#planToastTitle').text(title);
            $('#planToastBody').text(msg);
            $('#planToast').toast({
                delay: 2000
            });
            $('#planToast').toast('show');
        }

        function fetchReadyToProduction() {
            fetch('{{ url('admin/routecard/ready-to-production-list') }}')
                .then(res => res.json())
                .then(data => renderReadyProductionRC(data));
        }

        function renderReadyProductionRC(cards) {
            let rcBox = $('#ReadyProductionBoxes');
            rcBox.html('');
            let color = '#fff5d4';
            if (!cards.length) {
                rcBox.html(
                    '<div class="text-secondary py-4" style="font-size:1.1rem;">No projects in Ready to Production.</div>'
                );
            }
            cards.forEach(card => {
                // Progress calculation
                let total = card.processes ? card.processes.length : 0;
                let completed = card.processes ? card.processes.filter(p => p.status && p.status.toLowerCase() ===
                    'completed').length : 0;
                let percent = total ? Math.round((completed / total) * 100) : 0;

                let progressBar = `
                <div class="progress mb-2" style="height: 8px;">
                    <div class="progress-bar bg-success" role="progressbar"
                         style="width: ${percent}%;" aria-valuenow="${percent}"
                         aria-valuemin="0" aria-valuemax="100"></div>
                </div>
                <div style="font-size: 0.97rem;">${percent}% Complete</div>
            `;

                let processes = '';
                if (card.processes && card.processes.length) {
                    processes = `
    <div class="p-2">
        <ul class="process-list-steps pl-0 mb-0">
            ${card.processes.map((proc, idx) => `
                    <li class="process-list-step mb-3 shadow-sm">
                        <div class="d-flex align-items-center mb-2">
                            <div class="process-step-number mr-3">${idx + 1}</div>
                            <div>
                                <div class="process-title font-weight-bold mb-1">${proc.process || '-'}</div>
                            </div>
                        </div>
                        <div class="process-label mb-1">
                            <span class="text-muted">Description:</span>
                            <span>${proc.description || '-'}</span>
                        </div>
                        <div class="row mb-2">
                            <div class="col-12 col-md-7 mb-1">
                                <span class="text-muted"><i class="fas fa-cogs"></i> Machine:</span>
                                <span class="badge badge-info ml-1">${proc.machine || '-'}</span>
                            </div>
                            <div class="col-12 col-md-5 mb-1">
                                <span class="text-muted"><i class="fas fa-user"></i> Operator:</span>
                                <span class="badge badge-secondary ml-1">${proc.operator_name || '-'}</span>
                            </div>
                        </div>
                        <div class="row mb-1">
                            <div class="col-12 col-md-6 mb-2">
                                <span class="text-muted"><i class="far fa-play-circle"></i> Expected Start:</span><br>
                                <span class="expected-date">${proc.start_date ? formatDateTime(proc.start_date) : '-'}</span>
                            </div>
                            <div class="col-12 col-md-6 mb-2">
                                <span class="text-muted"><i class="far fa-stop-circle"></i> Expected End:</span><br>
                                <span class="expected-date">${proc.end_date ? formatDateTime(proc.end_date) : '-'}</span>
                            </div>
                        </div>
                        <div>
                            <span class="badge badge-${getStatusClass(proc.status)}">${proc.status ? proc.status.replace('_', ' ').toUpperCase() : 'PLANNED'}</span>
                        </div>
                    </li>
                `).join('')}
        </ul>
    </div>
`;
                } else {
                    processes = `<div class="px-2 py-2 text-muted">No processes found.</div>`;
                }

                let html = `
    <div class="project-box-wrapper mb-4" style="min-width:350px;max-width:420px;">
        <div class="project-box shadow-sm" style="background:${color};border-radius:22px;">
            <div class="project-box-header d-flex justify-content-between align-items-center">
                <span class="project-date" style="font-size:1rem;">
                    <i class="far fa-calendar-alt"></i> RC Date: ${formatDate(card.route_date) || ''}
                </span>
                <a class="btn btn-sm btn-link text-primary" title="View Plan" href="{{ url('admin/manufacturing/plan') }}/${card.id}">
                    <i class="fas fa-eye"></i>
                </a>
            </div>
            <div class="project-box-content-header pb-0">
                <p class="box-content-header mb-0 font-weight-bold" style="font-size:1.15rem;color:#ce9700;">
                    <i class="fas fa-barcode"></i> ${card.route_no}
                </p>
                <p class="box-content-subheader mb-2" style="color:#ffb43e;font-size:.95rem;">
                    <i class="fas fa-industry"></i> ${card.company_name}
                </p>
            </div>
            <div class="box-progress-wrapper">
                <p class="box-progress-header" style="font-weight:600;">Ready to Production</p>
                <div class="box-progress-bar mb-2"><span class="box-progress" style="width:100%;background:#ffae00;height:4px;display:block;border-radius:2px;"></span></div>
            </div>
            ${progressBar}
            <div class="mt-2" style="font-size: .97rem;">
                <span style="color:#0a7d4b;font-weight:500;">Planned By:</span> 
                <span style="color:#222;">${card.approved_by || 'Admin'}</span> <br>
                <span style="color:#0a7d4b;font-weight:500;">On:</span>
                <span style="color:#222;">${formatDate(card.approved_at) || ''}</span>
            </div>
            <div>
                <button class="btn btn-success btn-block btn-sm mt-3 mb-1" style="font-weight:600;" onclick="markInProduction(${card.id})">
                    <i class="fas fa-cogs"></i> Mark as In Production
                </button>
            </div>
            <div class="mt-3 mb-2 process-list-toggle text-center" style="cursor:pointer;" data-toggle="collapse" data-target="#proc-list-${card.id}">
                <span style="font-size:0.97rem;color:#c08401;">
                    <i class="fas fa-tasks"></i> Show/Hide Process List
                </span>
            </div>
            <div class="collapse" id="proc-list-${card.id}">
                ${processes}
            </div>
        </div>
    </div>
    `;
                rcBox.append(html);
            });
        }

        function getStatusClass(status) {
            switch ((status || '').toLowerCase()) {
                case 'completed':
                    return 'success';
                case 'qc':
                    return 'primary';
                case 'in_progress':
                    return 'warning';
                case 'not_started':
                    return 'secondary';
                default:
                    return 'secondary';
            }
        }

        function markInProduction(rcId) {
            if (!confirm('Are you sure to mark this Route Card as In Production?')) return;
            fetch(`{{ url('admin/routecard/in-production') }}/${rcId}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                })
                .then(res => res.json())
                .then(resp => {
                    if (resp.success) {
                        showToast('Project marked as In Production!');
                        setTimeout(function() {
                            window.location.href = `{{ url('admin/manufacturing/production') }}/${rcId}`;
                        }, 700);
                    } else {
                        showToast('Failed to update!', 'Error');
                    }
                });
        }


        function formatDate(dateStr) {
            if (!dateStr) return '';
            const d = new Date(dateStr);
            if (isNaN(d.getTime())) return '';
            return d.toLocaleDateString('en-GB');
        }

        function formatDateTime(dateStr) {
            if (!dateStr) return '';
            const d = new Date(dateStr);
            if (isNaN(d.getTime())) return '';
            return d.toLocaleString('en-GB', {
                day: '2-digit',
                month: '2-digit',
                year: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        $(document).ready(function() {
            fetchReadyToProduction();
        });
    </script>
@endpush
