@extends('layouts.dashboard.managerapp')

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

@push('styles')
    <style>
        .process-list-step {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1rem;
            margin-bottom: 1rem;
            border-left: 4px solid #3b82f6;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .process-step-number {
            width: 2rem;
            height: 2rem;
            background: #eff6ff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 1rem;
            color: #3b82f6;
            margin-right: 0.7rem;
        }
        .project-box {
            border-radius: 16px;
            padding: 1.5rem;
            background: #fff;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
            min-width: 350px;
            max-width: 420px;
            transition: all 0.2s ease-in-out;
            border: 1px solid #e5e7eb;
            margin-bottom: 1.5rem;
        }
        .project-box:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 15px rgba(0,0,0,0.1);
        }
        .box-title { color: #1f2937; font-weight: 700; font-size: 1.25rem; }
        .box-subtitle { color: #6b7280; font-weight: 500; font-size: 0.9rem; }
        
        @media (max-width: 576px) {
            .project-box { min-width: 95vw; max-width: 100vw; }
        }
    </style>
@endpush

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

    <div class="d-sm-flex align-items-center justify-content-between mb-4 px-2">
        <div>
             <h1 class="h3 mb-2 text-gray-800 fw-bold">Ready to Production</h1>
             <p class="text-muted mb-0">Approve plans to begin manufacturing.</p>
        </div>
        <a href="{{ url('manager/manufacturing/planning') }}" class="btn btn-outline-secondary rounded-pill px-4 shadow-sm">&larr; Back to Dashboard</a>
    </div>

    <div class="row px-2">
        <div class="col-lg-12">
            <div id="ReadyProductionBoxes" class="project-boxes d-flex flex-wrap gap-4"></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('manager/routecard/ready-to-production-list') }}')
                .then(res => res.json())
                .then(data => renderReadyProductionRC(data));
        }

        function renderReadyProductionRC(cards) {
            let rcBox = $('#ReadyProductionBoxes');
            rcBox.html('');
            
            if (!cards.length) { // Fix: check length property properly
                 rcBox.html('<div class="col-12 text-center py-5"><div class="text-muted h5"><i class="fas fa-clipboard-check mb-3 fa-2x"></i><br>No plans ready for production.</div></div>');
                 return;
            }

            cards.forEach(card => {
                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="d-flex justify-content-between small fw-bold text-muted mb-1">
                    <span>Progress</span>
                    <span>${percent}%</span>
                </div>
                <div class="progress mb-3" style="height: 6px; border-radius:3px;">
                    <div class="progress-bar bg-success" role="progressbar" style="width: ${percent}%;"></div>
                </div>`;

                let processes = '';
                if (card.processes && card.processes.length) {
                    processes = `
                    <div class="mt-3">
                        <ul class="list-unstyled mb-0">
                            ${card.processes.map((proc, idx) => `
                                <li class="process-list-step">
                                    <div class="d-flex align-items-center mb-2">
                                        <span class="process-step-number">${idx + 1}</span>
                                        <div class="fw-bold text-dark">${proc.process || '-'}</div>
                                    </div>
                                    <div class="small text-muted ps-5">
                                        <div><i class="fas fa-hdd me-1"></i> ${proc.machine || 'Unassigned'}</div>
                                        <div><i class="fas fa-user me-1"></i> ${proc.operator_name || 'Unassigned'}</div>
                                    </div>
                                </li>
                            `).join('')}
                        </ul>
                    </div>`;
                }

                let html = `
                <div class="project-box">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div>
                            <div class="box-title mb-0"><i class="fas fa-file-alt text-primary me-2"></i>${card.route_no}</div>
                            <div class="box-subtitle mt-1">${card.company_name}</div>
                        </div>
                        <span class="badge badge-light text-secondary border">${formatDate(card.route_date)}</span>
                    </div>

                    ${progressBar}

                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <a class="btn btn-outline-primary btn-sm rounded-pill px-3" href="{{ url('manager/manufacturing/plan') }}/${card.id}">
                            <i class="fas fa-eye me-1"></i> View Plan
                        </a>
                         <button class="btn btn-primary btn-sm rounded-pill px-3 shadow-sm" onclick="markInProduction(${card.id})">
                            <i class="fas fa-play me-1"></i> Start Production
                        </button>
                    </div>
                   
                    <div class="mt-3 text-center">
                        <a href="javascript:void(0)" class="small text-muted text-decoration-none" data-toggle="collapse" data-target="#proc-list-${card.id}">
                            Show Process Details <i class="fas fa-chevron-down ms-1"></i>
                        </a>
                    </div>
                    <div class="collapse" id="proc-list-${card.id}">
                        ${processes}
                    </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('manager/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('manager/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
