@extends('layouts.dashboard.superadminapp')

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

@push('styles')
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            --secondary-gradient: linear-gradient(135deg, #fdfbfb 0%, #ebedee 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --card-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
            --hover-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04);
            --text-dark: #2d3748;
            --text-muted: #718096;
            --bg-light: #f7fafc;
        }

        body {
            background-color: #f8f9fa; /* Light gray background */
            font-family: 'Inter', sans-serif;
        }

        /* Page Header */
        .page-header-gradient {
            background: var(--primary-gradient);
            color: white;
            padding: 2rem 2.5rem;
            border-radius: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            position: relative;
            z-index: 10;
            margin-bottom: 2rem;
            /* margin-left: 0; removed negative margins */
            /* margin-right: 0; */
        }

        .breadcrumb-item + .breadcrumb-item::before {
            color: rgba(255, 255, 255, 0.6);
        }

        .breadcrumb-item.active {
            color: rgba(255, 255, 255, 0.9);
        }
        
        /* Premium Card */
        .premium-card {
            background: white;
            border: none;
            border-radius: 16px;
            box-shadow: var(--card-shadow);
            transition: all 0.3s ease;
            height: 100%;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .premium-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--hover-shadow);
        }

        .card-header-stripe {
            height: 6px;
            background: var(--primary-gradient);
            width: 100%;
        }

        .card-body-content {
            padding: 1.5rem;
            flex-grow: 1;
        }

        .rc-number {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--text-dark);
            margin-bottom: 0.25rem;
        }

        .company-name {
            font-size: 0.95rem;
            color: var(--text-muted);
            margin-bottom: 1rem;
            font-weight: 500;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.75rem;
            font-size: 0.9rem;
        }

        .detail-label {
            color: var(--text-muted);
        }

        .detail-value {
            font-weight: 600;
            color: var(--text-dark);
        }

        /* Progress Bar */
        .progress-container {
            margin: 1rem 0;
        }
        .progress {
            height: 8px;
            border-radius: 4px;
            background-color: #edf2f7;
            overflow: hidden;
        }
        .progress-bar-custom {
            background: var(--primary-gradient);
        }

        /* Buttons */
        .btn-action-primary {
            background: var(--primary-gradient);
            border: none;
            color: white;
            padding: 0.6rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            width: 100%;
            transition: opacity 0.2s;
        }

        .btn-action-primary:hover {
            opacity: 0.95;
            color: white;
            text-decoration: none;
        }

        .btn-sm-glass {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            font-size: 0.85rem;
            border-radius: 6px;
        }
        .btn-sm-glass:hover {
            background: rgba(255,255,255,0.3);
            color: white;
        }

        /* Process List in Card */
        .process-preview {
            background: #f8fafc;
            border-radius: 8px;
            padding: 0.75rem;
            margin-top: 1rem;
            border: 1px solid #e2e8f0;
        }
        .process-item {
            display: flex;
            align-items: center;
            font-size: 0.85rem;
            margin-bottom: 0.5rem;
        }
        .process-item:last-child {
            margin-bottom: 0;
        }
        .step-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #cbd5e0;
            margin-right: 0.75rem;
        }
        .step-dot.completed {
            background: #48bb78;
        }
        
    </style>
@endpush

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

    <!-- Gradient Header -->
    <div class="page-header-gradient">
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 font-weight-bold mb-1">Ready to Production</h1>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb bg-transparent p-0 m-0">
                            <li class="breadcrumb-item"><a href="{{ url('superadmin/dashboard') }}" class="text-white-50">Dashboard</a></li>
                            <li class="breadcrumb-item"><a href="{{ url('superadmin/manufacturing/planning') }}" class="text-white-50">Planning</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Ready List</li>
                        </ol>
                    </nav>
                </div>
                <div>
                    <a href="{{ url('superadmin/manufacturing/planning') }}" class="btn btn-sm-glass shadow-sm">
                        <i class="fas fa-arrow-left mr-1"></i> Back to Planning
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container-fluid" style="position: relative; z-index: 20; padding-top: 0;">
        <div class="row" id="ReadyProductionBoxes">
            <!-- Cards will be populated here -->
            <div class="col-12 text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast for notification -->
    <div id="planToast" class="toast" style="position: fixed; top: 1rem; right: 1rem; min-width: 250px; z-index:9999;" data-delay="3000">
        <div class="toast-header">
            <strong class="mr-auto" id="planToastTitle">Notice</strong>
            <button type="button" class="ml-2 mb-1 close" data-dismiss="toast">&times;</button>
        </div>
        <div class="toast-body" id="planToastBody"></div>
    </div>
@endsection

@push('scripts')
    <!-- Only custom scripts, libraries loaded in layout -->
    <script>
        function showToast(msg, title = 'Notice', type='success') {
            $('#planToastTitle').text(title);
            $('#planToastBody').text(msg);
            // reset classes
            $('#planToast .toast-header').removeClass('bg-success bg-danger text-white');
            
            if(type === 'success') {
                $('#planToast .toast-header').addClass('bg-success text-white');
            } else if (type === 'error') {
                 $('#planToast .toast-header').addClass('bg-danger text-white');
            }
            
            $('#planToast').toast('show');
        }

        function fetchReadyToProduction() {
            fetch('{{ url('superadmin/routecard/ready-to-production-list') }}')
                .then(res => res.json())
                .then(data => renderReadyProductionRC(data))
                .catch(err => {
                    console.error(err);
                    $('#ReadyProductionBoxes').html('<div class="col-12 text-center text-danger">Failed to load data.</div>');
                });
        }

        function renderReadyProductionRC(cards) {
            let rcBox = $('#ReadyProductionBoxes');
            rcBox.html('');
            
            if (!cards || !cards.length) {
                rcBox.html(`
                    <div class="col-12 text-center py-5">
                       <div class="card shadow-sm border-0 p-5">
                            <i class="fas fa-clipboard-check fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No projects ready for production.</h5>
                            <p class="text-black-50">Approve Route Cards in Planning to see them here.</p>
                       </div>
                    </div>
                `);
                return;
            }

            cards.forEach(card => {
                // Progress
                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;

                // Process Preview (first 3)
                let processPreview = '';
                if(card.processes && card.processes.length > 0) {
                     let firstThree = card.processes.slice(0, 3);
                     processPreview = `
                        <div class="process-preview mt-3">
                            <h6 style="font-size:0.8rem; font-weight:700; color:#718096; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:0.5rem;">Process Preview</h6>
                            ${firstThree.map(p => `
                                <div class="process-item">
                                    <div class="step-dot ${p.status === 'Completed' ? 'completed' : ''}"></div>
                                    <span class="text-truncate" style="max-width:200px;">${p.process}</span>
                                </div>
                            `).join('')}
                            ${card.processes.length > 3 ? `<div class="text-center mt-1" style="font-size:0.75rem; color:#a0aec0;">+ ${card.processes.length - 3} more</div>` : ''}
                        </div>
                     `;
                }

                let html = `
                <div class="col-12 col-md-6 col-lg-4 mb-4">
                    <div class="premium-card">
                        <div class="card-header-stripe"></div>
                        <div class="card-body-content d-flex flex-column">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div>
                                    <div class="rc-number">${card.route_no}</div>
                                    <div class="company-name"><i class="far fa-building mr-1"></i> ${card.company_name}</div>
                                </div>
                                <span class="badge badge-pill badge-light border" style="font-weight:500;">
                                    ${formatDate(card.route_date)}
                                </span>
                            </div>

                            <div class="detail-row">
                                <span class="detail-label">Order No:</span>
                                <span class="detail-value text-break text-right" style="max-width:150px;">${card.order_no || '-'}</span>
                            </div>
                            <!--
                            <div class="detail-row">
                                <span class="detail-label">Product Type:</span>
                                <span class="detail-value">${card.product_type || '-'}</span>
                            </div>
                            -->

                            <div class="progress-container">
                                <div class="d-flex justify-content-between small mb-1">
                                    <span class="text-muted">Planning Progress</span>
                                    <span class="font-weight-bold ${percent === 100 ? 'text-success' : 'text-primary'}">${percent}%</span>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar progress-bar-custom" role="progressbar" style="width: ${percent}%"></div>
                                </div>
                            </div>
                            
                            <div class="mt-auto">
                                <div class="detail-row align-items-center">
                                     <span class="detail-label"><i class="fas fa-user-check mr-1"></i> Approved By:</span>
                                     <span class="detail-value badge badge-success badge-pill px-2" style="font-size:0.8rem; background-color:#c6f6d5; color:#22543d;">
                                        ${card.approved_by || 'Admin'}
                                     </span>
                                </div>
                                
                                <div class="row no-gutters mt-3">
                                   <div class="col-8 pr-2">
                                       <button class="btn-action-primary shadow-sm" onclick="markInProduction(${card.id})">
                                           <i class="fas fa-industry mr-1"></i> Start Production
                                       </button>
                                   </div>
                                   <div class="col-4 pl-1">
                                        <a href="{{ url('superadmin/manufacturing/plan') }}/${card.id}" class="btn btn-outline-secondary btn-block" style="border-radius:8px; padding:0.6rem; font-weight:600;">
                                            <i class="far fa-eye"></i> View
                                        </a>
                                   </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                `;
                rcBox.append(html);
            });
        }

        function markInProduction(rcId) {
            Swal.fire({
                title: 'Start Production?',
                text: "This will move the Route Card to the active production board.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, Start it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch(`{{ url('superadmin/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) {
                            Swal.fire(
                                'Started!',
                                'Project has been moved to In Production.',
                                'success'
                            ).then(() => {
                                window.location.href = `{{ url('superadmin/manufacturing/production') }}/${rcId}`;
                            });
                        } else {
                            showToast('Failed to update status', 'Error', 'error');
                        }
                    })
                    .catch(e => showToast('Server Error', 'Error', 'error'));
                }
            })
        }

        function formatDate(dateStr) {
            if (!dateStr) return '';
            const d = new Date(dateStr);
            if (isNaN(d.getTime())) return '';
            return d.toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'});
        }

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