@extends('layouts.dashboard.superadminapp')

@section('title', 'Edit Sales RFQ')

@section('styles')
<style>
    /* Modern Purple Theme Variables */
    :root {
        --purple-primary: #8b5cf6;
        --purple-dark: #7c3aed;
        --purple-light: #a78bfa;
        --teal-primary: #06b6d4;
        --teal-dark: #0891b2;
        --success: #10b981;
        --success-dark: #059669;
        --danger: #ef4444;
        --danger-dark: #dc2626;
        --warning: #f59e0b;
        --info: #06b6d4;
        --gray-50: #f8fafc;
        --gray-100: #f1f5f9;
        --gray-200: #e2e8f0;
        --gray-300: #cbd5e1;
        --gray-600: #475569;
        --gray-700: #334155;
        --gray-800: #1e293b;
        --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
        --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
        --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
        --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
        --radius: 0.5rem;
        --radius-md: 0.75rem;
        --radius-lg: 1rem;
    }

    /* Modern Page Header */
    .modern-page-header {
        background: linear-gradient(135deg, #fff 0%, var(--gray-50) 100%);
        border-radius: var(--radius-lg);
        padding: 1.25rem 1.5rem;
        margin-bottom: 1.5rem;
        box-shadow: var(--shadow-md);
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 1rem;
    }

    .header-left {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .icon-wrapper {
        width: 3rem;
        height: 3rem;
        background: linear-gradient(135deg, var(--purple-primary) 0%, var(--purple-dark) 100%);
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
    }

    .icon-wrapper i {
        font-size: 1.5rem;
        color: #fff;
    }

    .header-title {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }

    .header-title h1 {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--gray-800);
        margin: 0;
        line-height: 1.2;
    }

    .header-subtitle {
        font-size: 0.875rem;
        color: var(--gray-600);
        font-weight: 500;
    }

    /* DateTime Display */
    .datetime-display {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .date-box, .time-box {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        background: var(--gray-50);
        padding: 0.5rem 1rem;
        border-radius: var(--radius);
        border: 1px solid var(--gray-200);
        font-size: 0.875rem;
        color: var(--gray-700);
        font-weight: 500;
    }

    .date-box i {
        color: var(--purple-primary);
        font-size: 0.9rem;
    }

    .time-box {
        background: linear-gradient(135deg, var(--purple-primary) 0%, var(--purple-dark) 100%);
        color: #fff;
        border: none;
        min-width: 95px;
        justify-content: center;
        box-shadow: 0 2px 8px rgba(139, 92, 246, 0.25);
    }

    .time-box i {
        color: rgba(255, 255, 255, 0.9);
    }

    .time-box .display-time {
        font-family: 'SF Mono', 'Courier New', monospace;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    /* Section Cards */
    .section-card {
        border: none;
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-md);
        margin-bottom: 1.5rem;
        overflow: hidden;
        transition: all 0.2s;
    }

    .section-card:hover {
        box-shadow: var(--shadow-lg);
    }

    .section-header {
        background: linear-gradient(135deg, var(--purple-primary) 0%, var(--purple-dark) 100%);
        color: #fff;
        padding: 1rem 1.5rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .section-header h2 {
        font-size: 1rem;
        font-weight: 600;
        margin: 0;
        letter-spacing: 0.3px;
    }

    .section-header i {
        font-size: 1.1rem;
        opacity: 0.9;
    }

    .section-header.info {
        background: linear-gradient(135deg, var(--teal-primary) 0%, var(--teal-dark) 100%);
    }

    .section-header.success {
        background: linear-gradient(135deg, var(--success) 0%, var(--success-dark) 100%);
    }

    .section-header.warning {
        background: linear-gradient(135deg, var(--warning) 0%, #d97706 100%);
    }

    .section-body {
        padding: 1.5rem;
        background: #fff;
    }

    /* Form Controls */
    .form-label {
        font-weight: 600;
        color: var(--gray-700);
        font-size: 0.8125rem;
        margin-bottom: 0.5rem;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }

    .required-star {
        color: var(--danger);
        margin-left: 2px;
    }

    .form-control {
        font-size: 0.9375rem;
        padding: 0.625rem 1rem;
        border: 2px solid var(--gray-200);
        border-radius: var(--radius);
        transition: all 0.2s;
        background: var(--gray-50);
    }

    .form-control:hover {
        border-color: var(--gray-300);
    }

    .form-control:focus {
        border-color: var(--purple-primary);
        box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1);
        background: #fff;
        outline: none;
    }

    .form-control[readonly] {
        background: var(--gray-100);
        color: var(--gray-600);
        cursor: not-allowed;
    }

    select.form-control {
        appearance: none;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%238b5cf6' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
        background-position: right 0.75rem center;
        background-repeat: no-repeat;
        background-size: 1.5em 1.5em;
        padding-right: 2.5rem;
    }

    input[type="file"].form-control {
        padding: 0.5rem;
        font-size: 0.875rem;
    }

    input[type="file"].form-control::file-selector-button {
        padding: 0.5rem 1rem;
        margin-right: 1rem;
        border: none;
        background: linear-gradient(135deg, var(--purple-primary) 0%, var(--purple-dark) 100%);
        color: #fff;
        border-radius: 0.375rem;
        cursor: pointer;
        transition: all 0.2s;
        font-weight: 500;
        font-size: 0.875rem;
    }

    input[type="file"].form-control::file-selector-button:hover {
        background: linear-gradient(135deg, var(--purple-dark) 0%, #6d28d9 100%);
    }

    textarea.form-control {
        min-height: 80px;
        resize: vertical;
    }

    /* Row Spacing */
    .form-row {
        margin-bottom: 0.75rem;
    }

    .form-row > [class*="col-"] {
        margin-bottom: 0.75rem;
    }

    /* Existing Files */
    .existing-file {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.75rem 1rem;
        background: linear-gradient(135deg, var(--gray-50) 0%, #fff 100%);
        border: 2px solid var(--gray-200);
        border-radius: var(--radius);
        margin-bottom: 0.75rem;
        font-size: 0.875rem;
        transition: all 0.2s;
    }

    .existing-file:hover {
        border-color: var(--purple-primary);
        box-shadow: 0 2px 8px rgba(139, 92, 246, 0.15);
    }

    .existing-file i.fa-file {
        color: var(--purple-primary);
        font-size: 1.1rem;
    }

    .existing-file a {
        color: var(--gray-800);
        text-decoration: none;
        font-weight: 500;
        flex: 1;
    }

    .existing-file a:hover {
        color: var(--purple-primary);
        text-decoration: underline;
    }

    .existing-file .delete-file-btn {
        color: var(--danger);
        cursor: pointer;
        font-size: 1.1rem;
        transition: all 0.2s;
        padding: 0.25rem;
    }

    .existing-file .delete-file-btn:hover {
        color: var(--danger-dark);
        transform: scale(1.2);
    }

    /* File Preview */
    .file-preview {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        margin-top: 0.75rem;
    }

    .file-preview img {
        max-width: 100px;
        max-height: 80px;
        border-radius: var(--radius);
        border: 2px solid var(--gray-200);
        object-fit: cover;
        transition: all 0.2s;
    }

    .file-preview img:hover {
        border-color: var(--purple-primary);
        transform: scale(1.05);
    }

    .file-preview a {
        font-size: 0.875rem;
        color: var(--purple-primary);
        text-decoration: none;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 0.75rem;
        background: var(--gray-50);
        border-radius: var(--radius);
        border: 1px solid var(--gray-200);
        transition: all 0.2s;
    }

    .file-preview a:hover {
        background: var(--purple-primary);
        color: #fff;
        border-color: var(--purple-primary);
    }

    /* Material Row */
    .material-row {
        background: linear-gradient(135deg, var(--gray-50) 0%, #fff 100%);
        border: 2px solid var(--gray-200);
        border-radius: var(--radius);
        padding: 0.75rem;
        margin-bottom: 0.75rem;
        transition: all 0.2s;
    }

    .material-row:hover {
        border-color: var(--purple-primary);
        box-shadow: 0 2px 8px rgba(139, 92, 246, 0.15);
    }

    .material-row .input-group {
        align-items: stretch;
    }

    .material-row .form-control {
        border-radius: var(--radius) 0 0 var(--radius) !important;
        border-right: none;
    }

    .material-row .input-group-append {
        margin-left: 0;
    }

    .material-row .input-group-append .btn {
        border-radius: 0 var(--radius) var(--radius) 0 !important;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 1rem;
    }

    /* Buttons */
    .btn {
        font-size: 0.9375rem;
        font-weight: 600;
        padding: 0.625rem 1.25rem;
        border-radius: var(--radius);
        transition: all 0.2s;
        border: none;
        box-shadow: var(--shadow-sm);
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

    .btn:hover {
        transform: translateY(-1px);
        box-shadow: var(--shadow);
    }

    .btn:active {
        transform: translateY(0);
    }

    .btn-primary {
        background: linear-gradient(135deg, var(--purple-primary) 0%, var(--purple-dark) 100%);
        color: #fff;
    }

    .btn-primary:hover {
        background: linear-gradient(135deg, var(--purple-dark) 0%, #6d28d9 100%);
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4);
        color: #fff;
    }

    .btn-success {
        background: linear-gradient(135deg, var(--success) 0%, var(--success-dark) 100%);
        color: #fff;
    }

    .btn-success:hover {
        background: linear-gradient(135deg, var(--success-dark) 0%, #047857 100%);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
        color: #fff;
    }

    .btn-danger {
        background: linear-gradient(135deg, var(--danger) 0%, var(--danger-dark) 100%);
        color: #fff;
    }

    .btn-danger:hover {
        background: linear-gradient(135deg, var(--danger-dark) 0%, #b91c1c 100%);
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
        color: #fff;
    }

    .btn-secondary {
        background: linear-gradient(135deg, #6c757d 0%, #545b62 100%);
        color: #fff;
    }

    .btn-secondary:hover {
        background: linear-gradient(135deg, #545b62 0%, #3d4349 100%);
        box-shadow: 0 4px 12px rgba(108, 117, 125, 0.4);
        color: #fff;
    }

    .btn-outline-success {
        border: 2px solid var(--success);
        color: var(--success);
        background: transparent;
        box-shadow: none;
    }

    .btn-outline-success:hover {
        background: var(--success);
        color: #fff;
        border-color: var(--success);
    }

    .btn-sm {
        padding: 0.5rem 1rem;
        font-size: 0.875rem;
    }

    .btn i {
        font-size: 0.875rem;
    }

    /* Footer Actions */
    .footer-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.5rem 0;
        margin-top: 1rem;
        gap: 1rem;
    }

    /* Modern Modal */
    .modal-content {
        border: none;
        border-radius: var(--radius-lg);
        overflow: hidden;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }

    .modal-header {
        background: linear-gradient(135deg, var(--success) 0%, var(--success-dark) 100%);
        color: #fff;
        padding: 1rem 1.5rem;
        border-bottom: none;
    }

    .modal-header .modal-title {
        font-size: 1.125rem;
        font-weight: 600;
        color: #fff;
        margin: 0;
    }

    .modal-header .close {
        opacity: 1;
        text-shadow: none;
        padding: 0;
        margin: 0;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 1.5rem;
        line-height: 1;
        transition: all 0.2s;
    }

    .modal-header .close:hover {
        background: rgba(255, 255, 255, 0.35);
        transform: rotate(90deg);
    }

    .modal-body {
        padding: 1.5rem;
    }

    .modal-footer {
        background: var(--gray-50);
        border-top: 1px solid var(--gray-200);
        padding: 1rem 1.5rem;
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
    }

    /* Toast Notification */
    .custom-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 320px;
        max-width: 400px;
        border-radius: var(--radius-lg);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
        border: none;
        animation: slideIn 0.3s ease;
    }

    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    .custom-toast .toast-body {
        padding: 1rem 1.25rem;
        font-size: 0.9375rem;
        font-weight: 500;
        display: flex;
        align-items: center;
        color: #fff;
    }

    .custom-toast.bg-success {
        background: linear-gradient(135deg, var(--success) 0%, var(--success-dark) 100%);
    }

    .custom-toast.bg-danger {
        background: linear-gradient(135deg, var(--danger) 0%, var(--danger-dark) 100%);
    }

    .custom-toast .close {
        color: #fff;
        opacity: 0.9;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .modern-page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .datetime-display {
            width: 100%;
            justify-content: flex-start;
        }

        .footer-actions {
            flex-direction: column;
            align-items: stretch;
        }

        .footer-actions .btn {
            width: 100%;
            justify-content: center;
        }
    }

    /* Loading Spinner */
    .spinner-border-sm {
        width: 1rem;
        height: 1rem;
        border-width: 0.15em;
    }

    /* Additional spacing utilities */
    .mt-custom {
        margin-top: 1rem;
    }
</style>
@endsection

@section('content')
<div class="container-fluid">

    <!-- Modern Page Header -->
    <div class="modern-page-header">
        <div class="header-left">
            <div class="icon-wrapper">
                <i class="fas fa-edit"></i>
            </div>
            <div class="header-title">
                <h1>Edit Sales RFQ</h1>
                <div class="header-subtitle">Update Request for Quotation Details</div>
            </div>
        </div>
        <div class="datetime-display">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

    <form id="rfqForm" action="{{ route('superadmin.salesbom.rfq.update', $rfq->id) }}" method="POST" enctype="multipart/form-data">
        @csrf
        @method('PUT')

        <!-- RFQ Basic Information -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-info-circle"></i>
                <h2>RFQ Basic Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-4">
                        <label class="form-label">RFQ No <span class="required-star">*</span></label>
                        <input type="text" name="rfqNo" class="form-control" value="{{ $rfq->rfq_no }}" readonly>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">RFQ Date <span class="required-star">*</span></label>
                        <input type="date" name="rfqDate" class="form-control" value="{{ $rfq->rfq_date }}" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Customer Reference No</label>
                        <input type="text" name="cusRefNo" class="form-control" value="{{ $rfq->cus_ref_no }}" placeholder="Reference number">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-4">
                        <label class="form-label">Customer <span class="required-star">*</span></label>
                        <select name="customer" class="form-control" required>
                            <option value="">Select Customer</option>
                            @foreach ($customers as $customer)
                                <option value="{{ $customer->id }}" {{ $rfq->customer == $customer->id ? 'selected' : '' }}>
                                    {{ $customer->company }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">RFQ Type <span class="required-star">*</span></label>
                        <select id="rfqType" name="rfqType" class="form-control" required>
                            <option value="">Select RFQ Type</option>
                            @foreach($rfqTypes as $type)
                                <option value="{{ $type->rfqtype }}" {{ $rfq->rfq_type == $type->rfqtype ? 'selected' : '' }}>
                                    {{ $type->rfqtype }}
                                </option>
                            @endforeach
                            <option value="other" {{ !$rfqTypes->contains('rfqtype', $rfq->rfq_type) && $rfq->rfq_type ? 'selected' : '' }}>Other</option>
                        </select>
                        <input type="text" name="other_rfq_type" id="other-rfq-type" class="form-control mt-2"
                            placeholder="Enter RFQ Type" value="{{ !$rfqTypes->contains('rfqtype', $rfq->rfq_type) ? $rfq->rfq_type : '' }}" style="display: none;">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Product Type <span class="required-star">*</span></label>
                        <select id="productType" name="productType" class="form-control" required>
                            <option value="">Select Product Type</option>
                            @foreach($productTypes as $type)
                                <option value="{{ $type->name }}" {{ $rfq->product_type == $type->name ? 'selected' : '' }}>
                                    {{ $type->name }}
                                </option>
                            @endforeach
                            <option value="other" {{ !$productTypes->contains('name', $rfq->product_type) && $rfq->product_type ? 'selected' : '' }}>Other</option>
                        </select>
                        <input type="text" name="other_product_type" id="other-product-type" class="form-control mt-2"
                            placeholder="Enter Product Type" value="{{ !$productTypes->contains('name', $rfq->product_type) ? $rfq->product_type : '' }}" style="display: none;">
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Details -->
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-cube"></i>
                <h2>Product Details</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-4">
                        <label class="form-label">Part No</label>
                        <input type="text" name="partNo" class="form-control" value="{{ $rfq->part_no }}" placeholder="Part number">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Project/Material No</label>
                        <input type="text" name="project_materialNo" class="form-control" value="{{ $rfq->project_material_no }}" placeholder="Project/Material number">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Description</label>
                        <input type="text" name="description" class="form-control" value="{{ $rfq->description }}" placeholder="Item description">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">Drawing No</label>
                        <input type="text" name="drawingNo" class="form-control" value="{{ $rfq->drawing_no }}" placeholder="Drawing number">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Drawing Revision</label>
                        <input type="text" name="drawingRev" class="form-control" value="{{ $rfq->drawing_rev }}" placeholder="Revision">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Quantity <span class="required-star">*</span></label>
                        <input type="number" name="quantity" class="form-control" value="{{ $rfq->quantity }}" required min="1" placeholder="Enter quantity">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">UOM <span class="required-star">*</span></label>
                        <input type="text" name="uom" class="form-control" value="{{ $rfq->uom }}" required placeholder="Unit of measure">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-12">
                        <label class="form-label">Notes</label>
                        <textarea name="note" class="form-control" rows="3" placeholder="Any additional notes or comments...">{{ $rfq->note }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Raw Materials -->
        <div class="section-card">
            <div class="section-header success">
                <i class="fas fa-cubes"></i>
                <h2>Raw Materials <span class="required-star">*</span></h2>
            </div>
            <div class="section-body">
                <div id="materials-wrapper">
                    <!-- Materials will be loaded by JS -->
                </div>
                <div class="mt-custom">
                    <button type="button" id="add-material" class="btn btn-outline-success btn-sm">
                        <i class="fas fa-plus"></i> Add Material
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-toggle="modal" data-target="#addRawMaterialModal">
                        <i class="fas fa-plus-circle"></i> New Raw Material
                    </button>
                </div>
            </div>
        </div>

        <!-- File Attachments -->
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-paperclip"></i>
                <h2>File Attachments</h2>
            </div>
            <div class="section-body">
                @php
                    $fileLabels = [
                        'drawing' => ['label' => 'Drawing Files', 'input' => 'drawingFiles'],
                        'material_spec' => ['label' => 'Material Specification Files', 'input' => 'materialSpecificationFiles'],
                        'rfq_form' => ['label' => 'RFQ Form Files', 'input' => 'rfqFormFiles'],
                        'annexure' => ['label' => 'Annexure Files', 'input' => 'annexureFiles']
                    ];
                @endphp

                <div class="row">
                    @foreach ($fileLabels as $type => $info)
                        @php
                            $files = $rfq->rfqFiles->where('file_type', $type);
                        @endphp
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{{ $info['label'] }}</label>

                            <!-- Existing Files -->
                            @if ($files->count())
                                <div class="mb-2">
                                    @foreach ($files as $file)
                                        <div class="existing-file" id="fileRow_{{ $file->id }}">
                                            <i class="fas fa-file"></i>
                                            <a href="{{ asset('storage/' . $file->file_path) }}" target="_blank">
                                                {{ Str::limit($file->file_name, 40) }}
                                            </a>
                                            <i class="fas fa-times delete-file-btn" onclick="deleteRfqFile({{ $file->id }})" title="Delete File"></i>
                                        </div>
                                    @endforeach
                                </div>
                            @endif

                            <!-- New File Upload -->
                            <input type="file" name="{{ $info['input'] }}[]" class="form-control" multiple accept=".pdf,image/*">
                            <div id="{{ $info['input'] }}_preview" class="file-preview"></div>
                            <small class="text-muted d-block mt-1">Accepts: PDF, JPG, PNG (Max: 5MB each)</small>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>

        <!-- Form Actions -->
        <div class="footer-actions">
            <a href="{{ route('superadmin.salesbom.rfq.rfqdetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <button type="submit" class="btn btn-success" id="submitBtn">
                <span class="spinner-border spinner-border-sm d-none" role="status" id="submitSpinner"></span>
                <i class="fas fa-save" id="submitIcon"></i>
                <span id="submitText">Update RFQ</span>
            </button>
        </div>
    </form>

    <!-- Modal for Adding Raw Material -->
    <div class="modal fade" id="addRawMaterialModal" tabindex="-1" aria-labelledby="addRawMaterialLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <form id="addRawMaterialForm">
                <div class="modal-content">
                    <div class="modal-header">
                        <h6 class="modal-title mb-0">
                            <i class="fas fa-plus-circle"></i> Add New Raw Material
                        </h6>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group mb-3">
                            <label class="form-label">Raw Material Name <span class="required-star">*</span></label>
                            <input type="text" name="name" class="form-control" required placeholder="Enter material name">
                        </div>
                        <div class="form-group mb-3">
                            <label class="form-label">ISO Specification <span class="required-star">*</span></label>
                            <input type="text" name="iso_specification" class="form-control" required placeholder="ISO specification">
                        </div>
                        <div class="form-group mb-3">
                            <label class="form-label">Material Density</label>
                            <input type="text" name="density" class="form-control" placeholder="Density (optional)">
                        </div>
                        <div class="form-group mb-0">
                            <label class="form-label">Mechanical Properties</label>
                            <input type="text" name="mechanical_properties" class="form-control" placeholder="Mechanical properties (optional)">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                        <button type="submit" class="btn btn-success btn-sm" id="addMaterialBtn">
                            <span class="spinner-border spinner-border-sm d-none" id="addMaterialSpinner"></span>
                            <i class="fas fa-plus" id="addMaterialIcon"></i>
                            <span id="addMaterialText">Add Material</span>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

</div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    // Dynamic Date/Time Update
    function updateDateTime() {
        const now = new Date();
        const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        document.getElementById('day').textContent = days[now.getDay()];
        document.getElementById('daynum').textContent = now.getDate();
        document.getElementById('month').textContent = months[now.getMonth()];
        document.getElementById('year').textContent = now.getFullYear();

        const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        document.querySelector('.display-time').textContent = timeStr;
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);

    // Load Raw Materials
    let allMaterials = [];
    let initialMaterials = {!! json_encode(is_array(json_decode($rfq->raw_material, true)) ? json_decode($rfq->raw_material, true) : []) !!};

    function loadRawMaterialsSelects(callback) {
        $.get('{{ route('superadmin.salesbom.rawmaterials.list') }}', function(data) {
            allMaterials = data;
            renderMaterialRows();
            if (callback) callback();
        });
    }

    function renderMaterialRows() {
        let html = '';
        if (!Array.isArray(initialMaterials)) initialMaterials = [];
        initialMaterials = initialMaterials.filter(x => !!x);

        for (let i = 0; i < Math.max(initialMaterials.length, 1); i++) {
            html += buildMaterialRow(initialMaterials[i] || '');
        }
        $('#materials-wrapper').html(html);
        setTimeout(disableDuplicateOptions, 100);
    }

    function buildMaterialRow(selectedVal) {
        let select = `<select name="rawmaterials[]" class="form-control raw-material-select" required>`;
        select += '<option value="">Select Raw Material</option>';
        allMaterials.forEach(mat => {
            let sel = (mat.id == selectedVal) ? 'selected' : '';
            select += `<option value="${mat.id}" ${sel}>${mat.rm_grade} (${mat.iso_specification})</option>`;
        });
        select += '</select>';
        return `
            <div class="material-row">
                <div class="input-group">
                    ${select}
                    <div class="input-group-append">
                        <button type="button" class="btn btn-danger remove-material" title="Remove Material">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    function disableDuplicateOptions() {
        let selectedVals = [];
        $('.raw-material-select').each(function() {
            let val = $(this).val();
            if (val) selectedVals.push(val);
        });
        $('.raw-material-select').each(function() {
            let currentVal = $(this).val();
            $(this).find('option').each(function() {
                let optVal = $(this).val();
                if (optVal && optVal !== currentVal && selectedVals.includes(optVal)) {
                    $(this).prop('disabled', true);
                } else {
                    $(this).prop('disabled', false);
                }
            });
        });
    }

    // Show/Hide Other Fields
    function toggleOtherFields() {
        $('#other-rfq-type').toggle($('#rfqType').val() === 'other');
        $('#other-product-type').toggle($('#productType').val() === 'other');
    }

    $('#rfqType').on('change', toggleOtherFields);
    $('#productType').on('change', toggleOtherFields);
    toggleOtherFields();

    // Add/Remove Material Rows
    $(document).on('click', '#add-material', function() {
        $('#materials-wrapper').append(buildMaterialRow(''));
        setTimeout(disableDuplicateOptions, 100);
    });

    $(document).on('click', '.remove-material', function() {
        if ($('.material-row').length > 1) {
            $(this).closest('.material-row').remove();
            disableDuplicateOptions();
        } else {
            showToast('error', 'At least one raw material is required.');
        }
    });

    $(document).on('change', '.raw-material-select', function() {
        disableDuplicateOptions();
    });

    // Add Raw Material Modal
    $('#addRawMaterialForm').submit(function(e) {
        e.preventDefault();
        var $btn = $('#addMaterialBtn');
        var $spinner = $('#addMaterialSpinner');
        var $text = $('#addMaterialText');
        var $icon = $('#addMaterialIcon');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $icon.addClass('d-none');
        $text.text('Adding...');

        $.ajax({
            url: '{{ route('superadmin.salesbom.rawmaterials.store') }}',
            method: 'POST',
            data: $(this).serialize(),
            headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            success: function(response) {
                if (response.success) {
                    $('#addRawMaterialModal').modal('hide');
                    $('#addRawMaterialForm')[0].reset();
                    loadRawMaterialsSelects(function() {
                        $('.raw-material-select').last().val(response.material.id);
                        disableDuplicateOptions();
                    });
                    showToast('success', 'Raw material added successfully!');
                }
            },
            error: function(xhr) {
                var errorMsg = 'Error adding raw material.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMsg = xhr.responseJSON.message;
                }
                showToast('error', errorMsg);
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $text.text('Add Material');
            }
        });
    });

    // Form Submit
    $('#rfqForm').on('submit', function() {
        $('#submitBtn').prop('disabled', true);
        $('#submitSpinner').removeClass('d-none');
        $('#submitIcon').addClass('d-none');
        $('#submitText').text('Updating...');
    });

    // File Preview
    const previewFileInputs = ['drawingFiles', 'materialSpecificationFiles', 'rfqFormFiles', 'annexureFiles'];
    previewFileInputs.forEach(function(inputId) {
        $(document).on('change', `input[name="${inputId}[]"]`, function(event) {
            const previewContainer = $(`#${inputId}_preview`);
            previewContainer.html('');

            const files = event.target.files;
            if (files.length > 0) {
                Array.from(files).forEach(file => {
                    const fileType = file.type;
                    if (fileType.startsWith('image/')) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            img.title = file.name;
                            previewContainer.append(img);
                        };
                        reader.readAsDataURL(file);
                    } else {
                        const link = document.createElement('a');
                        link.href = '#';
                        link.innerHTML = '<i class="fas fa-file-pdf"></i>' + file.name;
                        previewContainer.append(link);
                    }
                });
            }
        });
    });

    // Toast Notification Helper
    function showToast(type, message) {
        $('.custom-toast').remove();

        var bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
        var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

        var toastHtml = `
            <div class="toast custom-toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-delay="4000">
                <div class="toast-body">
                    <i class="fas ${icon}"></i>
                    <span class="flex-grow-1">${message}</span>
                    <button type="button" class="close ml-2 text-white" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        `;

        var $toast = $(toastHtml);
        $('body').append($toast);
        $toast.toast('show');

        $toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }

    // Make showToast globally available
    window.showToast = showToast;

    // Load materials on page load
    loadRawMaterialsSelects();
});

// Delete RFQ File Function
function deleteRfqFile(fileId) {
    if (!confirm("Are you sure you want to delete this file?")) return;

    let route = "{{ route('superadmin.salesbom.rfq.deletefile', ':id') }}".replace(':id', fileId);

    fetch(route, {
        method: "DELETE",
        headers: {
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
            "Content-Type": "application/json"
        }
    })
    .then(res => res.json())
    .then(res => {
        if (res.success) {
            document.getElementById('fileRow_' + fileId)?.remove();
            showToast('success', 'File deleted successfully!');
        } else {
            showToast('error', res.message || 'Error deleting file.');
        }
    })
    .catch(err => {
        console.error(err);
        showToast('error', 'An error occurred while deleting the file.');
    });
}
</script>
@endsection
