@extends('layouts.dashboard.superadminapp')

@section('title', 'Create 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-header.secondary {
        background: linear-gradient(135deg, #64748b 0%, #475569 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;
    }

    /* 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-secondary {
        border: 2px solid var(--gray-300);
        color: var(--gray-700);
        background: transparent;
        box-shadow: none;
    }

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

    .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;
    }

    .footer-actions > div {
        display: flex;
        gap: 0.75rem;
    }

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

    /* Alert Styling */
    .alert {
        border: none;
        border-radius: var(--radius-md);
        padding: 1rem 1.25rem;
        font-size: 0.9375rem;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: flex-start;
        box-shadow: var(--shadow-sm);
    }

    .alert-success {
        background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
        color: var(--success-dark);
        border-left: 4px solid var(--success);
    }

    .alert-danger {
        background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
        color: var(--danger-dark);
        border-left: 4px solid var(--danger);
    }

    .alert i {
        margin-right: 0.5rem;
        margin-top: 2px;
    }

    .alert ul {
        padding-left: 1.25rem;
        margin: 0;
    }

    .alert .close {
        padding: 0;
        margin-left: auto;
        color: inherit;
        opacity: 0.6;
    }

    .alert .close:hover {
        opacity: 1;
    }

    /* 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 > div {
            width: 100%;
            flex-direction: column;
        }

        .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-file-alt"></i>
            </div>
            <div class="header-title">
                <h1>Create Sales RFQ</h1>
                <div class="header-subtitle">Request for Quotation Registration</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>

    <!-- Alerts -->
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i>
            <div class="flex-grow-1">{{ session('success') }}</div>
            <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"></i>
            <div class="flex-grow-1">{{ session('error') }}</div>
            <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-triangle"></i>
            <div class="flex-grow-1">
                <strong>Please fix the following errors:</strong>
                <ul class="mt-2 mb-0">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form id="rfqform" action="{{ route('superadmin.salesbom.rfq.store') }}" method="POST" enctype="multipart/form-data">
        @csrf

        <!-- Basic Information Card -->
        <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-3">
                        <label class="form-label">RFQ ID <span class="required-star">*</span></label>
                        <input type="text" id="rfqNo" name="rfqNo" class="form-control" required readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">RFQ Date <span class="required-star">*</span></label>
                        <input type="date" id="rfqDate" name="rfqDate" class="form-control" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Customer <span class="required-star">*</span></label>
                        <select id="customer" name="customer" class="form-control" required>
                            <option value="">Select Customer</option>
                            @foreach ($customers as $customer)
                                <option value="{{ $customer->id }}">{{ $customer->company }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Customer Ref. No</label>
                        <input type="text" id="cusRefNo" name="cusRefNo" class="form-control" placeholder="Reference number">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-3">
                        <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 }}">{{ $type->rfqtype }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <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</option>
                            @foreach($productTypes as $type)
                                <option value="{{ $type->name }}">{{ $type->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Part No</label>
                        <input type="text" id="partNo" name="partNo" class="form-control" placeholder="Part number">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Project/Material No</label>
                        <input type="text" id="project-materialNo" name="project_materialNo" class="form-control" placeholder="Project/Material number">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Description</label>
                        <input type="text" id="description" name="description" class="form-control" placeholder="Item description">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Quantity <span class="required-star">*</span></label>
                        <input type="number" id="quantity" name="quantity" class="form-control" 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" id="uom" name="uom" class="form-control" required placeholder="Unit of measure">
                    </div>
                </div>
            </div>
        </div>

        <!-- Drawing Details Card -->
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-drafting-compass"></i>
                <h2>Drawing Details</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-4">
                        <label class="form-label">Drawing No</label>
                        <input type="text" id="drawingNo" name="drawingNo" class="form-control" placeholder="Drawing number">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Drawing Revision</label>
                        <input type="text" id="drawingRev" name="drawingRev" class="form-control" placeholder="Revision">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Drawing Files</label>
                        <input type="file" id="drawingFiles" name="drawingFiles[]" class="form-control" multiple accept=".pdf,image/*">
                        <div id="drawingFiles_preview" class="file-preview"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Attachments Card -->
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-paperclip"></i>
                <h2>Attachments</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-4">
                        <label class="form-label">Material Specification Files</label>
                        <input type="file" id="materialSpecificationFiles" name="materialSpecificationFiles[]" class="form-control" multiple accept=".pdf,image/*">
                        <div id="materialSpecificationFiles_preview" class="file-preview"></div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">RFQ Form Files</label>
                        <input type="file" id="rfqFormFiles" name="rfqFormFiles[]" class="form-control" multiple accept=".pdf,image/*">
                        <div id="rfqFormFiles_preview" class="file-preview"></div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Annexure Files</label>
                        <input type="file" id="annexureFiles" name="annexureFiles[]" class="form-control" multiple accept=".pdf,image/*">
                        <div id="annexureFiles_preview" class="file-preview"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Raw Materials Card -->
        <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">
                    <div class="material-row">
                        <div class="input-group">
                            <select name="rawmaterials[]" class="form-control raw-material-select" required>
                                <option value="">Select Raw Material</option>
                            </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>
                </div>
                <div class="mt-custom">
                    <button type="button" id="add-material" class="btn btn-primary 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>

        <!-- Notes Card -->
        <div class="section-card">
            <div class="section-header secondary">
                <i class="fas fa-sticky-note"></i>
                <h2>Additional Notes</h2>
            </div>
            <div class="section-body">
                <textarea id="note" name="note" class="form-control" rows="3" placeholder="Any additional notes or comments..."></textarea>
            </div>
        </div>

        <!-- Action Buttons -->
        <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>
            <div>
                <button class="btn btn-danger" type="reset" id="clearBtn">
                    <i class="fas fa-undo"></i> Clear Form
                </button>
                <button class="btn btn-success" type="submit" 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">Save RFQ</span>
                </button>
            </div>
        </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);

    // Set today's date
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];
    $('#rfqDate').val(formattedDate);

    // Generate RFQ ID via AJAX
    $.ajax({
        url: "{{ route('superadmin.salesbom.rfq.generateId') }}",
        method: 'GET',
        success: function(response) {
            $('#rfqNo').val(response.rfqId);
        },
        error: function() {
            showToast('error', 'Failed to generate RFQ ID.');
        }
    });

    // Load raw materials function
    function loadRawMaterials(select = null, callback = null) {
        $.get('{{ route('superadmin.salesbom.rawmaterials.list') }}', function(data) {
            $('.raw-material-select').each(function() {
                var selectedVal = $(this).val();
                $(this).empty().append('<option value="">Select Raw Material</option>');
                $.each(data, function(_, mat) {
                    $(this).append(
                        `<option value="${mat.id}" ${selectedVal == mat.id ? 'selected' : ''}>${mat.rm_grade} (${mat.iso_specification})</option>`
                    );
                }.bind(this));
                if (selectedVal) $(this).val(selectedVal);
            });
            if (select) {
                $(select).empty().append('<option value="">Select Raw Material</option>');
                $.each(data, function(_, mat) {
                    $(select).append(
                        `<option value="${mat.id}">${mat.rm_grade} (${mat.iso_specification})</option>`
                    );
                });
            }
            setTimeout(disableDuplicateOptions, 100);
            if (callback) callback();
        });
    }

    // Disable duplicate material selections
    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);
                }
            });
        });
    }

    // Initial load of raw materials
    loadRawMaterials();

    // On change, re-enforce uniqueness
    $(document).on('change', '.raw-material-select', function() {
        disableDuplicateOptions();
    });

    // Add material row
    $('#add-material').click(function() {
        var $newRow = $(`
            <div class="material-row">
                <div class="input-group">
                    <select name="rawmaterials[]" class="form-control raw-material-select" required>
                        <option value="">Select Raw Material</option>
                    </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>
        `);
        $('#materials-wrapper').append($newRow);
        loadRawMaterials($newRow.find('select'), disableDuplicateOptions);
    });

    // Remove material row
    $(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.');
        }
    });

    // Add new raw material via 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) {
                    var newMaterialId = response.material.id;
                    $('#addRawMaterialModal').modal('hide');
                    $('#addRawMaterialForm')[0].reset();
                    loadRawMaterials(null, function() {
                        $('.raw-material-select').last().val(newMaterialId);
                        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 validation
    $('#rfqform').on('submit', function(e) {
        let values = [];
        let duplicate = false;
        $('.raw-material-select').each(function() {
            let val = $(this).val();
            if (val) {
                if (values.includes(val)) {
                    duplicate = true;
                    return false;
                }
                values.push(val);
            }
        });
        if (duplicate) {
            showToast('error', 'Each Raw Material must be unique. Please select different materials.');
            e.preventDefault();
            return false;
        }

        // Show loading state
        $('#submitBtn').prop('disabled', true);
        $('#submitSpinner').removeClass('d-none');
        $('#submitIcon').addClass('d-none');
        $('#submitText').text('Saving...');
    });

    // Clear button
    $('#clearBtn').on('click', function() {
        $('.file-preview').empty();
        // Reload RFQ ID
        $.ajax({
            url: "{{ route('superadmin.salesbom.rfq.generateId') }}",
            method: 'GET',
            success: function(response) {
                $('#rfqNo').val(response.rfqId);
            }
        });
    });

    // File preview functionality
    const previewFileInputs = ['drawingFiles', 'materialSpecificationFiles', 'rfqFormFiles', 'annexureFiles'];
    previewFileInputs.forEach(function(inputId) {
        const input = document.getElementById(inputId);
        if (input) {
            input.addEventListener('change', function(event) {
                const previewContainer = document.getElementById(inputId + '_preview');
                previewContainer.innerHTML = '';
                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.appendChild(img);
                            };
                            reader.readAsDataURL(file);
                        } else {
                            const link = document.createElement('a');
                            link.href = URL.createObjectURL(file);
                            link.target = '_blank';
                            link.innerHTML = '<i class="fas fa-file-pdf"></i>' + file.name;
                            previewContainer.appendChild(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();
        });
    }
});
</script>
@endsection
