@extends('layouts.dashboard.superadminapp')
@section('title', 'Production Board')

@push('styles')
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        --text-dark: #2d3748;
        --text-muted: #718096;
        --card-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
    }

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

    /* Gradient 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;
    }

    .breadcrumb-item + .breadcrumb-item::before {
        color: rgba(255, 255, 255, 0.6);
    }
    .breadcrumb-item.active {
        color: rgba(255, 255, 255, 0.9);
    }
    
    /* Project Info Card */
    .project-info-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        box-shadow: var(--card-shadow);
        margin-bottom: 2rem;
        border-left: 5px solid #4e73df;
    }

    /* Timeline Styles */
    .timeline-wrapper {
        position: relative;
        padding-left: 20px;
    }
    .timeline-wrapper::before {
        content: '';
        position: absolute;
        top: 0;
        bottom: 0;
        left: 20px;
        width: 3px;
        background: #e2e8f0;
        border-radius: 2px;
    }

    .process-card-container {
        position: relative;
        margin-bottom: 2rem;
        padding-left: 30px;
    }
    
    .timeline-marker {
        position: absolute;
        left: -11px; /* Adjust based on parent padding */
        top: 24px;
        width: 22px;
        height: 22px;
        border-radius: 50%;
        background: white;
        border: 4px solid #cbd5e0;
        z-index: 2;
    }
    .timeline-marker.active {
        border-color: #4e73df;
        background: #4e73df;
    }
    .timeline-marker.completed {
        border-color: #48bb78;
        background: #48bb78;
    }

    .process-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
        overflow: hidden;
        transition: transform 0.2s;
        border: 1px solid #f1f1f1;
    }
    .process-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
    }

    .process-header {
        padding: 1rem 1.5rem;
        background: #f8fafc;
        border-bottom: 1px solid #edf2f7;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .process-title {
        font-weight: 700;
        font-size: 1.1rem;
        color: var(--text-dark);
    }

    .process-body {
        padding: 1.5rem;
    }

    .info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .info-item label {
        display: block;
        font-size: 0.8rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: var(--text-muted);
        margin-bottom: 0.3rem;
        font-weight: 600;
    }
    .info-item span {
        font-weight: 600;
        color: var(--text-dark);
        font-size: 0.95rem;
    }

    .action-panel {
        background: #f1f5f9;
        border-radius: 12px;
        padding: 1rem;
        margin-top: 1rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .btn-action {
        padding: 0.6rem 1.2rem;
        border-radius: 8px;
        font-weight: 600;
        border: none;
        transition: all 0.2s;
    }
    .btn-start {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        color: white;
        box-shadow: 0 4px 6px rgba(28, 200, 138, 0.3);
    }
    .btn-start:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 8px rgba(28, 200, 138, 0.4);
        color: white;
    }
    
    .btn-end {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);
        color: white;
        box-shadow: 0 4px 6px rgba(231, 74, 59, 0.3);
    }
    .btn-end:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 8px rgba(231, 74, 59, 0.4);
        color: white;
    }

    .status-pill {
        padding: 0.35em 0.8em;
        border-radius: 50rem;
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
    }
    .status-pill.pending { background: #fee2e2; color: #991b1b; }
    .status-pill.completed { background: #dcfce7; color: #166534; }
    .status-pill.in-progress { background: #dbeafe; color: #1e40af; }
    .status-pill.qc { background: #fef3c7; color: #92400e; }

</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">Production Board</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/production/in-progress') }}" class="text-white-50">In Progress</a></li>
                        <li class="breadcrumb-item active" aria-current="page">{{ $routeCard->route_no }}</li>
                    </ol>
                </nav>
            </div>
            <div>
                <button class="btn btn-warning shadow-sm mr-2" data-toggle="modal" data-target="#breakdownModal">
                    <i class="fas fa-exclamation-triangle mr-1"></i> Log Breakdown
                </button>
                <button class="btn btn-info shadow-sm mr-2" data-toggle="modal" data-target="#consumeModal">
                    <i class="fas fa-box-open mr-1"></i> Consume Material
                </button>
                <a href="{{ url('superadmin/manufacturing/production/in-progress') }}" class="btn btn-sm-glass shadow-sm" style="background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3); color: white;">
                    <i class="fas fa-arrow-left mr-1"></i> Back to List
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid" style="margin-top:-1rem;">
    <!-- ... existing content ... -->
    <!-- Overall Progress -->
    @php
        $total = $routeCard->processes->count();
        $done = $routeCard->processes->where('status', 'approved')->count();
        $percent = $total ? round(($done / $total) * 100) : 0;
    @endphp

    <!-- Consume Modal -->
    <div class="modal fade" id="consumeModal" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title"><i class="fas fa-box-open mr-2"></i> Consume Material</h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="consumeForm">
                        <div class="form-group">
                            <label>For Process</label>
                            <select class="form-control" name="process_id" required>
                                @foreach($routeCard->processes as $p)
                                    <option value="{{ $p->id }}" {{ $p->status == 'in_progress' ? 'selected' : '' }}>
                                        {{ $p->process }} ({{ ucwords(str_replace('_', ' ', $p->status)) }})
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Select Item (SKU)</label>
                            <select class="form-control select2" name="sku_id" id="skuSelect" required style="width:100%">
                                <option value="">Select Item...</option>
                                @foreach($skus as $sku)
                                    <option value="{{ $sku->id }}" data-stock="{{ $sku->current_stock }}">
                                        {{ $sku->item_name }} (Stock: {{ $sku->current_stock }})
                                    </option>
                                @endforeach
                            </select>
                            <small class="text-muted" id="stockDisplay">Available: -</small>
                        </div>
                        <div class="form-group">
                            <label>Quantity to Consume</label>
                            <input type="number" class="form-control" name="quantity" min="0.01" step="0.01" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-info" onclick="submitConsumption()">Consume</button>
                </div>
            </div>
        </div>
    </div>
    <!-- ... -->
    <!-- (I will rely on existing lines being preserved, targeting end of file for Modal) -->

<!-- Breakdown Modal -->
<div class="modal fade" id="breakdownModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle mr-2"></i> Report Machine Breakdown</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="breakdownForm">
                    <div class="form-group">
                        <label>Select Machine</label>
                        <select class="form-control" name="machine_id" required>
                            @foreach($routeCard->processes->unique('machine') as $p)
                                <option value="{{ $p->machine }}">{{ $p->machine }}</option>
                            @endforeach
                            {{-- Ideally machines are IDs, but here stored as string names? Check model.
                                 Assuming string names based on view '$p->machine'
                                 Controller logMachineBreakdown expects 'machine_id'.
                                 If machines are just strings in process table, we log string?
                                 Or need to map to Machine model?
                                 Let's assume we log the string name for now if ID not available.
                                 Or better, use route card machine ID if available.
                                 View shows `$p->machine` text. I'll send that as ID if it's unique name.
                            --}}
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Breakdown Start Time</label>
                        <input type="datetime-local" class="form-control" name="start_time" required value="{{ date('Y-m-d\TH:i') }}">
                    </div>
                    <div class="form-group">
                        <label>Reason / Details</label>
                        <textarea class="form-control" name="reason" rows="3" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" onclick="submitBreakdown()">Report Breakdown</button>
            </div>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
    window.routes = {
        startProcess: "{{ url('superadmin/manufacturing/production/start-process') }}",
        endProcess: "{{ url('superadmin/manufacturing/production/end-process') }}",
        logBreakdown: "{{ url('superadmin/manufacturing/production/log-breakdown') }}",
        consumeMaterial: "{{ url('superadmin/manufacturing/production/consume-material') }}"
    };

    $(document).ready(function() {
        // Initialize Select2 for modal
        $('.select2').select2({
            theme: 'bootstrap4',
            dropdownParent: $('#consumeModal')
        });

        // Show stock on change
        $('#skuSelect').on('change', function() {
             let stock = $(this).find(':selected').data('stock');
             $('#stockDisplay').text('Available: ' + (stock !== undefined ? stock : '-'));
        });
    });

    function startProcess(id) {
        // ... (existing)
        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();
        });
    }
    // ... (existing endProcess)
    
    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) {
        if(!confirm("Are you sure to end this process? This will trigger Final QC.")) return;
        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();
        });
    }

    function submitBreakdown() {
        let form = document.getElementById('breakdownForm');
        if(!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        let data = new FormData(form);
        
        fetch(window.routes.logBreakdown, {
            method: "POST",
            headers: { 
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(data))
        }).then(r => r.json()).then(resp => {
            if(resp.success) {
                $('#breakdownModal').modal('hide');
                alert("Breakdown Reported");
            } else {
                alert("Error reporting breakdown");
            }
        });
    }

    function submitConsumption() {
        let form = document.getElementById('consumeForm');
        if(!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        let data = new FormData(form);
        
        fetch(window.routes.consumeMaterial, {
            method: "POST",
            headers: { 
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(data))
        }).then(r => r.json()).then(resp => {
            if(resp.success) {
                $('#consumeModal').modal('hide');
                alert("Material Consumed! New Stock: " + resp.new_stock);
                // Update local data-stock?
                let skuId = data.get('sku_id');
                $(`#skuSelect option[value="${skuId}"]`).data('stock', resp.new_stock);
                $('#stockDisplay').text('Available: ' + resp.new_stock);
            } else {
                alert(resp.message || "Error consuming material");
            }
        });
    }

</script>
@endpush
