@extends('layouts.dashboard.superadminapp')
@section('title', 'Manufacturing Plan')

@section('styles')
<style>
    #productTable input.form-control { padding: 0.25rem 0.5rem; font-size: 0.875rem; }
    #processModal .modal-content { background: white !important; }
    #processModal.show { display: block !important; background-color: rgba(0, 0, 0, 0.5); }
    #processModal .modal-body { padding: 20px !important; }
    #processModal .form-control { background-color: #fff !important; border: 1px solid #ced4da !important; }
    .form-control:read-only { background-color: #e9ecef; }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Manufacturing Plan" icon="route" iconColor="warning" />

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if ($errors->any())
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>
        <ul class="mb-0">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Route Card Form -->
<div class="card shadow mb-4" id="route_card_section">
    <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-project-diagram mr-2"></i> {{ isset($routeCard) && !empty($routeCard) ? 'Edit Manufacturing Plan - ' . $routeCard->route_no : 'Create Manufacturing Plan' }}
        </h6>
        <div>
            <a href="{{ route('superadmin.manufacturing.planning', ['tab' => empty($routeCard) ? 'r2plan' : 'planning']) }}" class="btn btn-light btn-sm mr-1">
                <i class="fa fa-arrow-left mr-1"></i> Back to Planning
            </a>
            <a href="{{ route('superadmin.routecard.details') }}" class="btn btn-light btn-sm">
                <i class="fa fa-list mr-1"></i> Plans List
            </a>
        </div>
    </div>
    <div class="card-body">
        @if (isset($routeCard) && !empty($routeCard))
            <input type="hidden" id="routeCard" value="{{ json_encode($routeCard) }}">
        @endif

        <form id="routeForm" method="POST"
            action="{{ isset($routeCard) && !empty($routeCard) ? route('superadmin.routecard.update', $routeCardId) : route('superadmin.routecard.store') }}"
            data-action-type="{{ isset($routeCard) && !empty($routeCard) ? 'update' : 'create' }}">
            @csrf
            @if (isset($routeCard) && !empty($routeCard))
                @method('PUT')
            @endif

            <!-- Row 1: Basic Info -->
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Plan ID <span class="text-danger">*</span></label>
                    @if (isset($routeCard) && !empty($routeCard))
                        <input type="hidden" name="id" value="{{ $routeCard->id }}">
                        <input type="text" id="routeNo" name="route_no" value="{{ $routeCard->route_no }}" readonly required class="form-control">
                    @else
                        <input type="text" id="routeNo" name="route_no" value="{{ $nextRouteNo }}" readonly required class="form-control">
                    @endif
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Plan Date <span class="text-danger">*</span></label>
                    <input type="date" id="routeDate" name="route_date" required class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Sales Order ID <span class="text-danger">*</span></label>
                    <select id="orderNo" name="order_no" class="form-control" required>
                        <option value="">Select Sales Order</option>
                        @foreach ($saleOrders as $sOrder)
                            <option value="{{ $sOrder->sales_order_no }}" data-order="{{ json_encode($sOrder) }}">
                                {{ $sOrder->sales_order_no }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">GRN No</label>
                    <input type="text" id="grnNo" name="grn_no" class="form-control">
                </div>
            </div>

            <!-- Row 2: Order Info -->
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Order Date</label>
                    <input type="date" id="orderDate" name="order_date" class="form-control">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Order Company Name</label>
                    <input type="text" id="companyName" name="company_name" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Order Reference No</label>
                    <input type="text" id="orderRefNo" name="order_ref_no" class="form-control">
                </div>
            </div>

            <!-- Row 3: Company Details -->
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Address</label>
                    <input type="text" id="companyAddress" name="company_address" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">GST No</label>
                    <input type="text" id="companyGSTN" name="company_gstn" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Email</label>
                    <input type="email" id="companyEmail" name="company_email" class="form-control">
                </div>
            </div>

            <!-- Row 4: Contact & Quotation -->
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Contact Number</label>
                    <input type="tel" id="companyPhone" name="company_phone" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Quotation ID</label>
                    <input type="text" id="quotationNo" name="quotation_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Quotation Date</label>
                    <input type="date" id="quotationDate" name="quotation_date" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">RFQ No</label>
                    <input type="text" id="rfqNo" name="rfq_no" class="form-control">
                </div>
            </div>

            <!-- Row 5: RFQ & Part Details -->
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">RFQ Date</label>
                    <input type="date" id="rfqDate" name="rfq_date" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Part No</label>
                    <input type="text" id="partNo" name="part_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Project Material No</label>
                    <input type="text" id="project-materialNo" name="project_material_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Drawing No</label>
                    <input type="text" id="drawingNo" name="drawing_no" class="form-control">
                </div>
            </div>

            <!-- Row 6: Product Type & Project Start -->
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Drawing Revision</label>
                    <input type="text" id="drawingRev" name="drawing_rev" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Product Type <span class="text-danger">*</span></label>
                    <select id="productType" name="product_type" class="form-control" required>
                        <option value="">Select Product Type</option>
                        @foreach ($productTypes as $pt)
                            <option value="{{ $pt->name }}">{{ $pt->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Expected Project Start <span class="text-danger">*</span></label>
                    <input type="date" id="projectStart" name="project_start_date" required class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Description</label>
                    <textarea id="description" name="description" rows="1" class="form-control"></textarea>
                </div>
            </div>

            <hr>

            <!-- Action Buttons -->
            <div class="d-flex justify-content-end">
                <button type="submit" id="save-RC" class="btn btn-success btn-sm mr-2">
                    <i class="fa fa-save mr-1"></i>
                    {{ isset($routeCard) && !empty($routeCard) ? 'Save Plan' : 'Save & Add Process' }}
                </button>
                <a href="{{ route('superadmin.routecard.details') }}" class="btn btn-outline-secondary btn-sm">
                    <i class="fa fa-times mr-1"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Process Details Section (Only shown when editing) -->
@if (isset($routeCard) && !empty($routeCard))
    @include('superadmin.routecard.list')
    @include('superadmin.routecard.processmodel')
@endif

@endsection

@section('scripts')
<script>
    const processCount = {{ !empty($routeCardProcesses) ? $routeCardProcesses->count() : 'null' }};

    function fillFormData(fromSelector, sourceData, mappedKeys, callback=(v)=>(v)) {
        [...(new FormData(fromSelector[0])).entries()].map(([key, value]) => {
            let newValue = callback(dotwalk(sourceData, mappedKeys[key] || key) || sourceData[key] || value, mappedKeys[key] || key);
            fromSelector.find(`[name="${key}"]`).val(newValue);
        });
    }

    const mappedKeys = {
        "order_date": "sales_order_date",
        "order_ref_no": "rfq_no",
        "route_date": "rfq_date",
        "company_name": "customer.company",
    };
    const mappedValues = {
        "project_start_date": (v) => v ? v.split(' ')[0] : '',
    };

    const mappedValueResolver = (v, k) => mappedValues[k] ? mappedValues[k](v) : v;

    document.addEventListener('DOMContentLoaded', function() {
        if (processCount === 0) {
            setTimeout(() => {
                $("#route_card_process_list #addProcess").trigger("click");
            }, 500);
        }

        const saleOrder = {!! json_encode($saleOrder) !!};

        let routeCard = null;
        if ($("#route_card_section #routeCard").length) {
            routeCard = JSON.parse($("#route_card_section #routeCard").val());
            fillFormData($("#routeForm"), routeCard, mappedKeys, mappedValueResolver);
            console.log("Route Card Data:", {routeCard, saleOrder});
        }

        if (saleOrder) {
            $("#orderNo").val(saleOrder.sales_order_no);
            setTimeout(() => $("#orderNo").trigger("change"), 0);
        }

        $("#orderNo").on('change', function() {
            const orderNo = $(this).val();
            if (orderNo) {
                const orderData = $(this).find('option:selected').data('order');
                console.log("Selected Order Data:", orderData, routeCard);
                if (!routeCard) {
                    fillFormData($("#routeForm"), orderData, mappedKeys, mappedValueResolver);
                }
            }
        });

        $('#routeForm').on('submit', function(e) {
            e.preventDefault();
            this.submit();
        });
    });
</script>
@endsection
