@extends('layouts.dashboard.managerapp')
@section('title', 'Production Execution')
@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <style>
        .production-card {
            border-radius: 18px;
            border: none;
            box-shadow: 0 4px 32px 0 rgba(0, 0, 0, .07);
            transition: box-shadow 0.25s;
            background: #fff;
        }

        .production-card:hover {
            box-shadow: 0 8px 36px 0 rgba(60, 60, 100, .11);
        }

        .status-badge {
            font-size: 0.9rem;
            padding: 0.35em 0.9em;
            border-radius: 18px;
            letter-spacing: .5px;
            text-transform: uppercase;
        }

        .status-pending {
            background: #ffe082;
            color: #865700;
        }

        .status-in-progress {
            background: #81d4fa;
            color: #02587e;
        }

        .status-qc {
            background: #fff59d;
            color: #856c00;
        }

        .status-completed {
            background: #c8e6c9;
            color: #226622;
        }

        .operator-badge {
            background: #f5f7fa;
            padding: 0.2em 0.7em;
            border-radius: 15px;
            font-size: 0.93em;
            margin-left: 0.25em;
        }

        .production-btn {
            min-width: 160px;
            font-weight: 600;
            border-radius: 12px;
            box-shadow: 0 2px 12px 0 rgba(80, 200, 140, .07);
            font-size: 1.07em;
            letter-spacing: .1em;
            margin-top: 0.4em;
        }

        .production-btn:active,
        .production-btn:focus {
            box-shadow: none;
        }

        .step-badge {
            background: #2196f3;
            color: #fff;
            font-size: 1.1em;
            border-radius: 50%;
            width: 34px;
            height: 34px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        .progress {
            height: 30px;
            border-radius: 16px;
            background: #e3f2fd;
        }

        .progress-bar {
            font-size: 1.13em;
            font-weight: 500;
            border-radius: 14px;
        }
    </style>

    <div class="container py-4">
        <style>
            .production-header {
                background: white;
                border-radius: 15px;
                padding: 1.5rem;
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
                margin-bottom: 2rem;
                border-left: 5px solid #3b82f6;
            }
            .process-card {
                background: white;
                border-radius: 16px;
                border: 1px solid #f3f4f6;
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
                transition: all 0.3s ease;
                margin-bottom: 1.5rem;
                position: relative;
                overflow: hidden;
            }
            .process-card:hover {
                transform: translateY(-3px);
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            }
            .stage-stepper {
                display: flex;
                justify-content: space-between;
                align-items: center;
                position: relative;
                margin: 1.5rem 0;
            }
            .stage-stepper::before {
                content: '';
                position: absolute;
                top: 50%;
                left: 0;
                right: 0;
                height: 2px;
                background: #e5e7eb;
                z-index: 0;
                transform: translateY(-50%);
            }
            .step-item {
                position: relative;
                z-index: 1;
                background: white;
                padding: 0 10px;
                text-align: center;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            .step-circle {
                width: 32px;
                height: 32px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 0.8rem;
                background: #f3f4f6;
                color: #9ca3af;
                border: 2px solid #e5e7eb;
                margin-bottom: 0.5rem;
                transition: all 0.3s;
            }
            .step-item.active .step-circle {
                background: #eff6ff;
                border-color: #3b82f6;
                color: #3b82f6;
            }
            .step-item.completed .step-circle {
                background: #ecfdf5;
                border-color: #10b981;
                color: #10b981;
            }
            .step-item.rejected .step-circle {
                background: #fef2f2;
                border-color: #ef4444;
                color: #ef4444;
            }
            .step-label {
                font-size: 0.75rem;
                font-weight: 600;
                color: #6b7280;
                text-transform: uppercase;
                letter-spacing: 0.05em;
            }
            .modal-content {
                border-radius: 16px;
                border: none;
                box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
            }
            .btn-action-custom {
                border-radius: 10px;
                padding: 0.6rem 1.5rem;
                font-weight: 500;
                transition: all 0.2s;
            }
            .btn-action-custom:hover {
                transform: scale(1.02);
            }
        </style>

        <div class="production-header d-flex justify-content-between align-items-center">
            <div>
                <h2 class="h4 fw-bold mb-1 text-gray-800">Route Card: <span class="text-primary">#{{ $routeCard->route_no }}</span></h2>
                <p class="text-muted mb-0">Production Execution Board</p>
            </div>
            <div style="width: 200px;">
                 @php
                    $total = $routeCard->processes->count();
                    $done = $routeCard->processes->where('status', 'approved')->count();
                    $percent = $total ? round(($done / $total) * 100) : 0;
                @endphp
                <div class="text-end small fw-bold text-muted mb-1">{{ $percent }}% Completed</div>
                <div class="progress" style="height: 8px; border-radius: 4px;">
                    <div class="progress-bar bg-primary" role="progressbar" style="width: {{ $percent }}%;"></div>
                </div>
            </div>
        </div>

        @foreach ($routeCard->processes as $index => $proc)
            <div class="process-card p-4">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="d-flex">
                        <div class="me-3">
                             <span class="d-flex align-items-center justify-content-center bg-gray-100 text-gray-600 fw-bold rounded-circle" style="width: 40px; height: 40px; font-size:1.1rem;">
                                {{ $index + 1 }}
                             </span>
                        </div>
                        <div>
                            <h5 class="fw-bold text-dark mb-1">{{ $proc->process }}</h5>
                            <p class="text-muted small mb-0">{{ $proc->description ?: 'No description provided' }}</p>
                        </div>
                    </div>
                    <div>
                         @php
                            $statusColors = [
                                'pending' => 'bg-warning text-dark',
                                'in_production' => 'bg-primary text-white',
                                'qc_check' => 'bg-info text-white',
                                'completed' => 'bg-success text-white',
                                'approved' => 'bg-success text-white',
                            ];
                            $badgeClass = $statusColors[$proc->status] ?? 'bg-secondary text-white';
                         @endphp
                        <span class="badge {{ $badgeClass }} px-3 py-2 rounded-pill fw-normal" style="font-size:0.85rem;">
                            {{ ucfirst(str_replace('_', ' ', $proc->status)) }}
                        </span>
                    </div>
                </div>

                <!-- Three Stage QC Stepper -->
                 @php
                    $qcBefore = $proc->qcApprovals->where('stage', 'before')->first();
                    $qcDuring = $proc->qcApprovals->where('stage', 'during')->first();
                    $qcAfter = $proc->qcApprovals->where('stage', 'after')->first();

                    function getStepClass($qc) {
                        if (!$qc) return ''; // pending/waiting
                        if ($qc->status == 'approved') return 'completed';
                        if ($qc->status == 'rejected') return 'rejected';
                        return 'active'; // pending approval
                    }
                    function getStepIcon($qc) {
                         if (!$qc) return 'fa-circle';
                         if ($qc->status == 'approved') return 'fa-check';
                         if ($qc->status == 'rejected') return 'fa-times';
                         return 'fa-clock';
                    }
                @endphp
                <div class="stage-stepper px-5">
                    <div class="step-item {{ getStepClass($qcBefore) }}">
                        <div class="step-circle" title="Pre-Flight QC">
                            <i class="fas {{ getStepIcon($qcBefore) }}"></i>
                        </div>
                        <span class="step-label">Pre-Check</span>
                    </div>
                    <div class="step-item {{ getStepClass($qcDuring) }}">
                        <div class="step-circle" title="In-Process QC">
                            <i class="fas {{ getStepIcon($qcDuring) }}"></i>
                        </div>
                        <span class="step-label">In-Process</span>
                    </div>
                    <div class="step-item {{ getStepClass($qcAfter) }}">
                        <div class="step-circle" title="Final QC">
                            <i class="fas {{ getStepIcon($qcAfter) }}"></i>
                        </div>
                        <span class="step-label">Final QC</span>
                    </div>
                </div>

                <!-- Resource & Actions Row -->
                <div class="row mt-4 align-items-center">
                    <div class="col-md-6">
                        <div class="d-flex align-items-center bg-light rounded p-2 border">
                            <i class="fas fa-microchip text-secondary ms-2 me-2"></i>
                            <span class="me-3 small"><strong class="text-dark">Machine:</strong> {{ $proc->machine }}</span>
                            
                            <i class="fas fa-user-circle text-secondary me-2 ms-2"></i>
                            <span class="me-3 small"><strong class="text-dark">Op:</strong> {{ isset($employees[$proc->operator]) ? $employees[$proc->operator] : ($proc->operator ?: '-') }}</span>
                            
                            <a href="javascript:void(0)" class="ms-auto text-primary" onclick="openResourceModal({{ $proc->id }}, '{{ $proc->machine }}', '{{ $proc->operator }}')">
                                <i class="fas fa-edit"></i>
                            </a>
                        </div>
                    </div>
                    <div class="col-md-6 text-end">
                        @if ($proc->status == 'pending')
                            <button class="btn btn-action-custom btn-success shadow-sm" onclick="startProcess({{ $proc->id }})"
                                @if ($index > 0 && $routeCard->processes[$index - 1]->status != 'approved' && $routeCard->processes[$index - 1]->status != 'completed') disabled @endif>
                                <i class="fas fa-play me-2"></i> Start
                            </button>
                        @elseif ($proc->status == 'in_production')
                             <button class="btn btn-action-custom btn-danger shadow-sm me-2" onclick="endProcess({{ $proc->id }})">
                                <i class="fas fa-stop me-2"></i> Stop
                            </button>
                            <button class="btn btn-action-custom btn-warning shadow-sm" onclick="openBreakdownModal('{{ $proc->machine }}')">
                                <i class="fas fa-exclamation-triangle"></i>
                            </button>
                        @elseif($proc->status == 'qc_check')
                             <span class="text-info fw-bold"><i class="fas fa-spinner fa-spin me-2"></i> Awaiting Final QC</span>
                        @elseif($proc->status == 'completed' || $proc->status == 'approved')
                            <span class="text-success fw-bold"><i class="fas fa-check-circle me-2"></i> Done</span>
                        @endif

                        @if($qcBefore && $qcBefore->status === 'rejected')
                             <div class="text-danger small fw-bold mt-1">Pre-QC Rejected!</div>
                        @endif
                    </div>
                </div>
            </div>
        @endforeach
    </div>
        <!-- Resource Modal -->
        <div class="modal fade" id="resourceModal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header border-0 pb-0">
                        <h5 class="modal-title fw-bold">Update Resource</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-light border small text-muted mb-3">
                            Changing resources mid-production is allowed but tracked.
                        </div>
                        <input type="hidden" id="edit_proc_id">
                        <div class="mb-3">
                            <label class="form-label fw-bold small">Assigned Machine</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0"><i class="fas fa-hdd text-secondary"></i></span>
                                <input type="text" class="form-control border-start-0 ps-0" id="edit_machine" placeholder="Machine Name">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold small">Operator</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0"><i class="fas fa-user text-secondary"></i></span>
                                <select class="form-control border-start-0 ps-0" id="edit_operator">
                                    @foreach($employees as $id => $name)
                                        <option value="{{ $id }}">{{ $name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pt-0">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary px-4" onclick="saveResource()">Update</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Breakdown Modal -->
        <div class="modal fade" id="breakdownModal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-danger">
                    <div class="modal-header bg-danger text-white">
                        <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Report Breakdown</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="bd_machine_id">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Issue Description</label>
                            <textarea class="form-control" id="bd_reason" rows="4" placeholder="Describe the failure or maintenance reason..."></textarea>
                        </div>
                        <div class="text-end text-muted small">
                            This will log downtime for the machine.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-danger px-4" onclick="submitBreakdown()">Report Alert</button>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <script>
        window.routes = {
            startProcess: "{{ url('manager/manufacturing/production/start-process') }}",
            endProcess: "{{ url('manager/manufacturing/production/end-process') }}",
            approveQC: "{{ url('manager/manufacturing/production/approve-qc') }}",
            updateResource: "{{ url('manager/manufacturing/production/update-resource') }}", // Need to add route
            reportBreakdown: "{{ url('manager/manufacturing/production/report-breakdown') }}" // Need to add route
        };

        function startProcess(id) {
            fetch(`${window.routes.startProcess}/${id}`, {
                method: "POST",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            }).then(r => r.json()).then(resp => {
                if(resp.error) alert(resp.error);
                else location.reload();
            });
        }

        function endProcess(id) {
            fetch(`${window.routes.endProcess}/${id}`, {
                method: "POST",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            }).then(r => r.json()).then(resp => {
                if(resp.error) alert(resp.error);
                else location.reload();
            });
        }

        // Modal Functions
        function openResourceModal(id, machine, operator) {
            $('#edit_proc_id').val(id);
            $('#edit_machine').val(machine);
            $('#edit_operator').val(operator);
            $('#resourceModal').modal('show');
        }

        function saveResource() {
            let id = $('#edit_proc_id').val();
            fetch(`${window.routes.updateResource}/${id}`, {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                body: JSON.stringify({
                    machine: $('#edit_machine').val(),
                    operator: $('#edit_operator').val()
                })
            }).then(r => r.json()).then(resp => {
                 location.reload();
            });
        }

        function openBreakdownModal(machineId) {
            $('#bd_machine_id').val(machineId); // Assuming machine name/id is needed. Best to use ID if available. 
            // In blade loop, machine is text. If logic needs ID, might need adjustment.
            // For now passing machine name is what we have.
            $('#breakdownModal').modal('show');
        }

        function submitBreakdown() {
            fetch(window.routes.reportBreakdown, {
                 method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                body: JSON.stringify({
                    machine_id: $('#bd_machine_id').val(), // Treating as string name for now due to DB structure?
                    // Actually migration machine_logs uses machine_id integer. 
                    // Need to ensure we have machine ID. $proc->machine is likely name. 
                    // Let's assume for now we pass name or null. Fix later if strict.
                    reason: $('#bd_reason').val()
                })
            }).then(r => r.json()).then(resp => {
                alert('Breakdown Reported');
                $('#breakdownModal').modal('hide');
            });
        }
    </script>
@endsection

