@extends('layouts.dashboard.superadminapp')

@section('title', 'Raw Materials')

@section('styles')
<style>
    /* Compact Page Header */
    .page-header {
        background: linear-gradient(135deg, #fff 0%, #f8f9fc 100%);
        border-radius: 8px;
        padding: 0.5rem 1rem;
        margin-bottom: 0.75rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    }
    .page-header h1 {
        font-size: 1rem;
        font-weight: 600;
        color: #2d3748;
        margin: 0;
    }

    /* DateTime Display */
    .datetime-display { gap: 0.5rem; }
    .date-box, .time-box {
        display: flex;
        align-items: center;
        gap: 0.35rem;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        padding: 0.35rem 0.65rem;
        border-radius: 6px;
        border: 1px solid #e2e8f0;
        font-size: 0.75rem;
        color: #475569;
        font-weight: 500;
    }
    .date-box i, .time-box i { color: #36b9cc; font-size: 0.7rem; }
    .time-box {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
        color: #fff;
        border: none;
        min-width: 85px;
        justify-content: center;
    }
    .time-box i { color: rgba(255,255,255,0.8); }
    .time-box .display-time {
        font-family: 'Courier New', monospace;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    /* Compact KPI Cards */
    .kpi-card {
        border-radius: 8px;
        color: #fff;
        position: relative;
        overflow: hidden;
        padding: 0.75rem 1rem !important;
    }
    .kpi-card .kpi-icon {
        font-size: 2rem;
        opacity: 0.25;
        position: absolute;
        right: 0.75rem;
        top: 50%;
        transform: translateY(-50%);
    }
    .kpi-card .kpi-value {
        font-size: 1.5rem;
        font-weight: 700;
        margin-bottom: 0.1rem;
        line-height: 1.2;
    }
    .kpi-card .kpi-label {
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        opacity: 0.9;
    }
    .kpi-card .kpi-info {
        font-size: 0.65rem;
        margin-top: 0.25rem;
        opacity: 0.8;
    }

    /* Gradient backgrounds */
    .bg-gradient-info { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-gradient-success { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-gradient-primary { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }

    /* Compact Cards */
    .compact-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        margin-bottom: 0.75rem;
    }
    .compact-card .card-header {
        background: transparent;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 0.6rem 1rem;
    }
    .compact-card .card-body { padding: 1rem; }

    /* Enhanced DataTable Styling */
    .datatable-card .card-header {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
        border-radius: 8px 8px 0 0;
        padding: 0.6rem 1rem;
    }
    .datatable-card .card-header h6 {
        color: #fff;
        font-size: 0.85rem;
        margin: 0;
    }

    /* DataTable Container - Top Controls */
    #rawMaterialTable_wrapper > .row:first-child {
        background: linear-gradient(135deg, #f8f9fc 0%, #eef1f8 100%);
        padding: 1rem 1.25rem;
        margin: 0 !important;
        border-bottom: 2px solid #e3e6f0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-radius: 0;
    }

    /* DataTable Container - Bottom Controls */
    #rawMaterialTable_wrapper .row.bottom-controls {
        background: linear-gradient(135deg, #f8f9fc 0%, #eef1f8 100%);
        padding: 1rem 1.25rem;
        margin: 0 !important;
        border-top: 2px solid #e3e6f0;
        display: flex !important;
        flex-direction: row !important;
        flex-wrap: nowrap !important;
        align-items: center !important;
        justify-content: space-between !important;
    }
    #rawMaterialTable_wrapper .row.bottom-controls > div {
        padding: 0 0.5rem !important;
    }

    /* Enhanced Length Menu */
    #rawMaterialTable_wrapper .dataTables_length {
        display: flex;
        align-items: center;
    }
    #rawMaterialTable_wrapper .dataTables_length label {
        display: flex;
        align-items: center;
        gap: 0.6rem;
        font-size: 0.85rem;
        color: #5a5c69;
        margin-bottom: 0;
        font-weight: 500;
    }
    #rawMaterialTable_wrapper .dataTables_length select {
        border: 2px solid #d1d9e6 !important;
        border-radius: 10px !important;
        padding: 0.6rem 2.2rem 0.6rem 1rem !important;
        font-size: 0.85rem !important;
        font-weight: 600 !important;
        color: #36b9cc !important;
        background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%2336b9cc' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E") no-repeat right 0.85rem center !important;
        background-size: 10px !important;
        appearance: none !important;
        cursor: pointer;
        transition: all 0.2s ease;
        min-width: 75px;
        box-shadow: 0 2px 6px rgba(0,0,0,0.06);
    }
    #rawMaterialTable_wrapper .dataTables_length select:hover {
        border-color: #36b9cc !important;
    }
    #rawMaterialTable_wrapper .dataTables_length select:focus {
        border-color: #36b9cc !important;
        box-shadow: 0 0 0 4px rgba(54, 185, 204, 0.15) !important;
        outline: none !important;
    }

    /* Enhanced Search Box */
    #rawMaterialTable_wrapper .dataTables_filter {
        display: flex;
        align-items: center;
        position: relative;
    }
    #rawMaterialTable_wrapper .dataTables_filter label {
        display: flex;
        align-items: center;
        gap: 0;
        font-size: 0;
        color: transparent;
        margin-bottom: 0;
        position: relative;
    }
    #rawMaterialTable_wrapper .dataTables_filter input[type="search"] {
        border: 2px solid #d1d9e6 !important;
        border-radius: 10px !important;
        padding: 0.6rem 1rem 0.6rem 2.5rem !important;
        font-size: 0.85rem !important;
        min-width: 260px;
        transition: all 0.2s ease;
        background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%236c757d' viewBox='0 0 16 16'%3E%3Cpath d='M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z'/%3E%3C/svg%3E") no-repeat left 0.85rem center !important;
        background-size: 15px !important;
        box-shadow: 0 2px 6px rgba(0,0,0,0.06);
        margin-left: 0 !important;
    }
    #rawMaterialTable_wrapper .dataTables_filter input[type="search"]:focus {
        border-color: #36b9cc !important;
        box-shadow: 0 0 0 4px rgba(54, 185, 204, 0.15) !important;
        outline: none !important;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%2336b9cc' viewBox='0 0 16 16'%3E%3Cpath d='M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z'/%3E%3C/svg%3E") !important;
    }

    /* Enhanced Info Text */
    #rawMaterialTable_wrapper .dataTables_info {
        font-size: 0.8rem !important;
        color: #5a6169 !important;
        padding: 0.5rem 1rem !important;
        background: linear-gradient(135deg, #fff 0%, #f8f9fc 100%) !important;
        border-radius: 10px !important;
        border: 2px solid #e3e8f0 !important;
        font-weight: 600 !important;
        box-shadow: 0 2px 6px rgba(0,0,0,0.04);
    }

    /* Enhanced Pagination */
    #rawMaterialTable_wrapper .dataTables_paginate {
        display: flex !important;
        align-items: center !important;
        gap: 0.35rem !important;
    }
    #rawMaterialTable_wrapper .dataTables_paginate .paginate_button {
        padding: 0.5rem 0.85rem !important;
        margin: 0 !important;
        border-radius: 10px !important;
        border: 2px solid #e3e8f0 !important;
        background: linear-gradient(135deg, #fff 0%, #f8f9fc 100%) !important;
        color: #5a5c69 !important;
        font-size: 0.8rem !important;
        font-weight: 600 !important;
        transition: all 0.2s ease !important;
        cursor: pointer !important;
        min-width: 40px !important;
        text-align: center !important;
        box-shadow: 0 2px 6px rgba(0,0,0,0.06) !important;
    }
    #rawMaterialTable_wrapper .dataTables_paginate .paginate_button:hover:not(.disabled):not(.current) {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%) !important;
        border-color: #36b9cc !important;
        color: #fff !important;
        transform: translateY(-2px) !important;
        box-shadow: 0 6px 15px rgba(54, 185, 204, 0.4) !important;
    }
    #rawMaterialTable_wrapper .dataTables_paginate .paginate_button.current {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%) !important;
        border-color: #36b9cc !important;
        color: #fff !important;
        box-shadow: 0 6px 15px rgba(54, 185, 204, 0.4) !important;
    }
    #rawMaterialTable_wrapper .dataTables_paginate .paginate_button.disabled {
        opacity: 0.5 !important;
        cursor: not-allowed !important;
        background: #f1f3f8 !important;
        color: #adb5bd !important;
        box-shadow: none !important;
    }

    /* Table Styling */
    #rawMaterialTable {
        border-collapse: separate;
        border-spacing: 0;
        width: 100% !important;
    }
    #rawMaterialTable thead th {
        background: linear-gradient(135deg, #f8f9fc 0%, #eaecf4 100%);
        border: none;
        border-bottom: 2px solid #e3e6f0;
        padding: 0.75rem 0.5rem;
        font-size: 0.7rem;
        font-weight: 700;
        color: #36b9cc;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        cursor: pointer;
        transition: all 0.2s ease;
        white-space: nowrap;
    }
    #rawMaterialTable thead th:hover {
        background: linear-gradient(135deg, #eef1f8 0%, #e3e8f4 100%);
        color: #258391;
    }

    /* Sort Indicators */
    #rawMaterialTable thead th.sorting::after,
    #rawMaterialTable thead th.sorting_asc::after,
    #rawMaterialTable thead th.sorting_desc::after {
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        font-size: 0.6rem;
        margin-left: 0.3rem;
    }
    #rawMaterialTable thead th.sorting::after { content: '\f0dc'; color: #b8c2d0; }
    #rawMaterialTable thead th.sorting_asc::after { content: '\f0de'; color: #1cc88a; }
    #rawMaterialTable thead th.sorting_desc::after { content: '\f0dd'; color: #e74a3b; }

    #rawMaterialTable tbody td {
        padding: 0.6rem 0.5rem;
        font-size: 0.78rem;
        border: none;
        border-bottom: 1px solid #e9ecef;
        vertical-align: middle;
    }
    #rawMaterialTable tbody tr {
        transition: all 0.15s ease;
    }
    #rawMaterialTable tbody tr:hover {
        background-color: #e8f8fa !important;
        transform: scale(1.002);
        box-shadow: 0 2px 8px rgba(54, 185, 204, 0.1);
    }
    #rawMaterialTable tbody tr:nth-child(even) {
        background-color: #fafbfc;
    }

    /* Action Buttons */
    .action-btn {
        width: 28px;
        height: 28px;
        padding: 0;
        border-radius: 6px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 0.7rem;
        transition: all 0.2s;
        border: none;
        margin: 0 1px;
    }
    .action-btn:hover { transform: scale(1.1); }
    .action-btn.edit-btn { background: #fff3cd; color: #856404; }
    .action-btn.edit-btn:hover { background: #f6c23e; color: #fff; }
    .action-btn.delete-btn { background: #ffebee; color: #c62828; }
    .action-btn.delete-btn:hover { background: #e74a3b; color: #fff; }
    .action-btn.view-btn { background: #e3f2fd; color: #1565c0; }
    .action-btn.view-btn:hover { background: #4e73df; color: #fff; }

    /* File Buttons */
    .file-btn {
        width: 24px;
        height: 24px;
        padding: 0;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 0.65rem;
        margin: 1px;
    }

    /* Add Button */
    .add-btn {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        border: none;
        padding: 0.4rem 1rem;
        border-radius: 6px;
        font-size: 0.8rem;
        font-weight: 600;
        color: #fff;
        transition: all 0.2s;
    }
    .add-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(28, 200, 138, 0.3);
        color: #fff;
    }

    /* Quick Actions */
    .quick-link-card {
        background: #fff;
        border-radius: 8px;
        padding: 0.75rem;
        text-align: center;
        transition: all 0.2s;
        border: 1px solid rgba(0, 0, 0, 0.05);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    }
    .quick-link-card:hover {
        border-color: #36b9cc;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(54, 185, 204, 0.15);
    }
    .quick-link-card i { font-size: 1.25rem; margin-bottom: 0.25rem; }
    .quick-link-card .link-title { font-weight: 600; color: #333; font-size: 0.7rem; }

    /* Enhanced Modal Styling */
    #rawMaterialModal .modal-content,
    #deleteRawMaterialModal .modal-content {
        border: none;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    }
    #rawMaterialModal .modal-header.primary-header {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%) !important;
        padding: 0.6rem 1rem !important;
        border-bottom: 2px solid rgba(255,255,255,0.2) !important;
    }
    #deleteRawMaterialModal .modal-header.danger-header {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%) !important;
        padding: 0.6rem 1rem !important;
        border-bottom: 2px solid rgba(255,255,255,0.2) !important;
    }
    #rawMaterialModal .modal-header .close,
    #deleteRawMaterialModal .modal-header .close {
        opacity: 1;
        text-shadow: none;
        padding: 0;
        margin: 0;
        width: 26px;
        height: 26px;
        border-radius: 50%;
        background: rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 1.2rem;
        line-height: 1;
        transition: all 0.2s;
    }
    #rawMaterialModal .modal-header .close:hover,
    #deleteRawMaterialModal .modal-header .close:hover {
        background: rgba(255,255,255,0.35);
        transform: rotate(90deg);
    }
    #rawMaterialModal .modal-title,
    #deleteRawMaterialModal .modal-title {
        font-size: 0.9rem;
        font-weight: 600;
        color: #fff !important;
    }
    #rawMaterialModal .modal-body {
        padding: 1rem !important;
        background: #fff;
        max-height: 70vh;
        overflow-y: auto;
    }
    #deleteRawMaterialModal .modal-body {
        padding: 1rem !important;
        background: #fff;
    }
    #rawMaterialModal .modal-footer,
    #deleteRawMaterialModal .modal-footer {
        background: #f8f9fc;
        border-top: 1px solid #e3e6f0;
        padding: 0.6rem 1rem;
        display: flex;
        justify-content: flex-end;
        gap: 0.5rem;
    }
    #deleteRawMaterialModal .modal-footer {
        justify-content: center;
    }
    #rawMaterialModal .modal-footer .btn,
    #deleteRawMaterialModal .modal-footer .btn {
        border-radius: 5px;
        padding: 0.45rem 1rem;
        font-weight: 600;
        font-size: 0.8rem;
        min-width: 95px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 0.3rem;
        height: 34px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: all 0.2s;
    }
    #rawMaterialModal .modal-footer .btn-secondary,
    #deleteRawMaterialModal .modal-footer .btn-secondary {
        background: linear-gradient(135deg, #6c757d 0%, #545b62 100%);
        border: none;
        color: #fff;
    }
    #rawMaterialModal .modal-footer .btn-primary {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
        border: none;
        color: #fff;
    }
    #deleteRawMaterialModal .modal-footer .btn-danger {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);
        border: none;
        color: #fff;
    }

    /* Compact Form Styling */
    #rawMaterialModal .form-label {
        font-size: 0.78rem;
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.25rem;
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }
    #rawMaterialModal .form-label i {
        font-size: 0.7rem;
    }
    #rawMaterialModal .form-control-modern {
        border: 1px solid #d1d3e2;
        border-radius: 5px;
        padding: 0.45rem 0.7rem;
        font-size: 0.82rem;
        height: 36px;
        transition: all 0.2s;
        background: #fff;
    }
    #rawMaterialModal .form-control-modern:hover {
        border-color: #b8bcc5;
    }
    #rawMaterialModal .form-control-modern:focus {
        border-color: #36b9cc;
        box-shadow: 0 0 0 2px rgba(54, 185, 204, 0.15);
        background: #fff;
    }

    /* Form Error Alert */
    #formErrors {
        border-radius: 5px;
        border: none;
        background: #fff5f5;
        border-left: 3px solid #e74a3b;
        padding: 0.5rem 0.75rem;
        margin-bottom: 0.75rem;
    }
    #formErrors ul { margin-bottom: 0; font-size: 0.8rem; }

    /* Delete Modal Enhancement */
    .delete-modal-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: linear-gradient(135deg, #fff5f5 0%, #fee8e7 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 0.6rem;
        border: 2px solid #f8d7da;
    }
    .delete-modal-icon i {
        font-size: 1.3rem;
        color: #e74a3b;
    }
    .delete-item-name {
        background: #f8f9fc;
        padding: 0.4rem 0.8rem;
        border-radius: 5px;
        border: 1px dashed #d1d3e2;
        display: inline-block;
        font-size: 0.85rem;
    }

    /* File Preview Styles */
    #filePreview, #existingFile {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }
    #filePreview .file-box, #existingFile .file-box {
        position: relative;
        width: 80px;
        border: 1px solid #e3e6f0;
        border-radius: 6px;
        padding: 5px;
        text-align: center;
        overflow: hidden;
        background: #f8f9fc;
    }
    #filePreview .file-box img, #existingFile .file-box img {
        max-width: 100%;
        height: 50px;
        object-fit: cover;
        border-radius: 4px;
    }
    .remove-file-btn, .remove-existing-file-btn {
        position: absolute;
        top: 2px;
        right: 2px;
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);
        color: white;
        border: none;
        border-radius: 50%;
        font-size: 10px;
        width: 18px;
        height: 18px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
        line-height: 1;
    }
    .remove-file-btn:hover, .remove-existing-file-btn:hover {
        transform: scale(1.1);
    }

    /* File Count Display */
    #fileCountDisplay {
        font-size: 0.75rem;
        color: #36b9cc;
        font-weight: 600;
        margin-top: 0.25rem;
        display: block;
    }

    /* Enhanced Toast */
    .custom-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 280px;
        max-width: 350px;
        border-radius: 8px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.2);
        border: none;
        animation: slideInRight 0.3s ease;
    }
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    .custom-toast .toast-body {
        padding: 0.65rem 1rem;
        font-size: 0.85rem;
        font-weight: 500;
        display: flex;
        align-items: center;
    }
    .custom-toast.bg-success {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%) !important;
    }
    .custom-toast.bg-danger {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%) !important;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .kpi-card .kpi-value { font-size: 1.25rem; }
        .page-header { flex-direction: column; gap: 0.5rem; }
        #rawMaterialTable_wrapper .dataTables_filter input[type="search"] {
            min-width: 180px !important;
        }
    }
    @media (max-width: 576px) {
        #rawMaterialTable_wrapper .row.bottom-controls {
            flex-direction: column !important;
            gap: 0.75rem;
        }
        #rawMaterialTable_wrapper .row.bottom-controls > div {
            width: 100% !important;
            justify-content: center !important;
        }
    }
</style>
@endsection

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

    <!-- Page Header -->
    <div class="page-header d-flex align-items-center justify-content-between flex-wrap">
        <h1><i class="fas fa-cubes mr-2 text-info"></i>UEPL | Raw Materials</h1>
        <div class="datetime-display d-flex align-items-center">
            <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>

    <!-- KPI Cards Row -->
    <div class="row mb-3">
        <div class="col-xl-3 col-md-6 mb-2">
            <div class="kpi-card bg-gradient-info shadow">
                <i class="fas fa-cubes kpi-icon"></i>
                <div class="kpi-value" id="totalCount">0</div>
                <div class="kpi-label">Total Materials</div>
                <div class="kpi-info"><i class="fas fa-database mr-1"></i> Inventory items</div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-2">
            <div class="kpi-card bg-gradient-success shadow">
                <i class="fas fa-check-circle kpi-icon"></i>
                <div class="kpi-value" id="activeCount">0</div>
                <div class="kpi-label">Active Records</div>
                <div class="kpi-info"><i class="fas fa-list mr-1"></i> In use</div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="compact-card card shadow mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-info" style="font-size: 0.85rem;">
                <i class="fas fa-bolt mr-2"></i>Quick Actions
            </h6>
        </div>
        <div class="card-body py-2">
            <div class="row">
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="javascript:void(0)" class="text-decoration-none" id="quickAddBtn">
                        <div class="quick-link-card">
                            <i class="fas fa-plus-circle text-success"></i>
                            <div class="link-title">Add New</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.producttype.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-boxes text-warning"></i>
                            <div class="link-title">Product Types</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.companytype.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-building text-primary"></i>
                            <div class="link-title">Company Types</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.dashboard.dashboard') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-tachometer-alt text-secondary"></i>
                            <div class="link-title">Dashboard</div>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- DataTable Card -->
    <div class="compact-card card datatable-card shadow">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold">
                <i class="fas fa-table mr-2"></i> Raw Materials Directory
            </h6>
            <button class="add-btn" id="addMaterialBtn" title="Add Raw Material">
                <i class="fas fa-plus mr-1"></i> Add Material
            </button>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="rawMaterialTable">
                    <thead>
                        <tr class="text-center">
                            <th width="5%">Sl.No</th>
                            <th width="20%">Material Grade</th>
                            <th width="18%">ISO Spec</th>
                            <th width="12%">Density</th>
                            <th width="18%">Type</th>
                            <th width="12%">Files</th>
                            <th width="15%">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Loaded by AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="rawMaterialModal" tabindex="-1" aria-labelledby="rawMaterialModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header primary-header">
                <h6 class="modal-title mb-0" id="rawMaterialModalLabel">
                    <i class="fas fa-plus-circle mr-2" id="modalIcon"></i>Add Raw Material
                </h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>

            <form id="rawMaterialForm">
                @csrf
                <input type="hidden" name="material_id" id="material_id">
                <div class="modal-body">
                    <!-- Error Alert -->
                    <div id="formErrors" class="alert alert-danger d-none" role="alert">
                        <small><i class="fas fa-exclamation-triangle mr-1"></i><strong>Error:</strong></small>
                        <ul class="mb-0 pl-3 small" id="errorList"></ul>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="form-label"><i class="fas fa-tag text-info"></i> Material Grade <span class="text-danger">*</span></label>
                            <input name="rm_grade" id="rm_grade" class="form-control form-control-modern" placeholder="e.g. EN8, SS304" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label"><i class="fas fa-certificate text-primary"></i> ISO Specification</label>
                            <input name="iso_specification" id="iso_specification" class="form-control form-control-modern" placeholder="e.g. ISO 9001">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="form-label"><i class="fas fa-weight text-warning"></i> Density (KG/m³) <span class="text-danger">*</span></label>
                            <input type="number" name="density" id="density" class="form-control form-control-modern" step="any" placeholder="e.g. 7850" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label"><i class="fas fa-layer-group text-success"></i> Material Type</label>
                            <input list="raw_material_options" name="raw_material_type" id="raw_material_type" class="form-control form-control-modern" placeholder="Select or enter type">
                            <datalist id="raw_material_options">
                                <option value="Forged Road Bar">
                                <option value="Steel">
                                <option value="Step Forging">
                                <option value="Channel">
                                <option value="Round Bars">
                                <option value="Flat Bars">
                                <option value="Angle Bars">
                                <option value="I-Beams and H-Beams">
                                <option value="Steel Metal">
                                <option value="Wire Rods">
                                <option value="Billets and Blooms">
                                <option value="Copper Rods/Bars">
                                <option value="Aluminum Extrusions">
                                <option value="Brass Rods/Sheets">
                                <option value="Titanium Bars/Sheets">
                            </datalist>
                        </div>
                    </div>

                    <div class="mb-2">
                        <label class="form-label"><i class="fas fa-file-upload text-secondary"></i> Upload Files</label>
                        <input type="file" name="material_file[]" id="material_file" class="form-control form-control-modern" multiple accept=".jpeg,.png,.jpg,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx" style="height: auto; padding: 0.35rem 0.7rem;">
                        <span id="fileCountDisplay"></span>

                        <!-- Existing Files (Edit Mode) -->
                        <div id="existingFile" class="mt-2" style="display: none;"></div>

                        <!-- New File Preview -->
                        <div id="filePreview" class="mt-2"></div>

                        <input type="hidden" name="remove_existing_file" id="remove_existing_file" value="0">
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i>
                        <span>Cancel</span>
                    </button>
                    <button type="submit" class="btn btn-primary" id="saveBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <i class="fas fa-check btn-icon"></i>
                        <span class="btn-text">Save</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteRawMaterialModal" tabindex="-1" aria-labelledby="deleteRawMaterialLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-header danger-header">
                <h6 class="modal-title mb-0" id="deleteRawMaterialLabel">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Confirm Delete
                </h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body text-center">
                <div class="delete-modal-icon">
                    <i class="fas fa-cubes"></i>
                </div>
                <p class="text-dark mb-2">Are you sure you want to delete?</p>
                <div class="delete-item-name">
                    <i class="fas fa-cubes mr-1 text-muted"></i>
                    <span class="font-weight-bold" id="deleteItemName"></span>
                </div>
                <p class="text-muted mt-2 mb-0"><small><i class="fas fa-exclamation-circle mr-1"></i>This action cannot be undone.</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times"></i>
                    <span>Cancel</span>
                </button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                    <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                    <i class="fas fa-trash-alt btn-icon"></i>
                    <span class="btn-text">Delete</span>
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    var rawMaterialsData = [];
    var selectedFiles = [];

    // Dynamic Date/Time
    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'];

        $('#day').text(days[now.getDay()]);
        $('#daynum').text(now.getDate());
        $('#month').text(months[now.getMonth()]);
        $('#year').text(now.getFullYear());

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

    // Load Raw Materials
    function loadRawMaterials() {
        if ($.fn.DataTable.isDataTable('#rawMaterialTable')) {
            $('#rawMaterialTable').DataTable().clear().destroy();
        }
        $('#rawMaterialTable tbody').empty();

        $.get('{{ route('superadmin.rawmaterial.list') }}', function(res) {
            rawMaterialsData = res.data;
            let rows = '';

            $.each(res.data, function(i, item) {
                let filePreview = '<span class="text-muted">-</span>';

                if (item.files && item.files.length > 0) {
                    filePreview = '<div class="d-flex flex-wrap justify-content-center gap-1">';
                    item.files.forEach(function(file) {
                        const fileUrl = '{{ asset("storage") }}/' + file.file_path;
                        filePreview += `
                            <a href="${fileUrl}" target="_blank" class="btn btn-sm btn-outline-info file-btn" title="View">
                                <i class="fas fa-eye"></i>
                            </a>
                            <button class="btn btn-sm btn-outline-danger file-btn" onclick="deleteFileFromList('${file.id}')" title="Delete">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        `;
                    });
                    filePreview += '</div>';
                }

                rows += `<tr class="text-center">
                    <td class="font-weight-bold text-muted">${i + 1}</td>
                    <td class="text-left">
                        <i class="fas fa-cubes text-info mr-1"></i>
                        <span class="font-weight-500">${item.rm_grade || '-'}</span>
                    </td>
                    <td>${item.iso_specification || '-'}</td>
                    <td>${item.density || '-'}</td>
                    <td><span class="badge badge-light">${item.raw_material_type || '-'}</span></td>
                    <td>${filePreview}</td>
                    <td>
                        <button class="action-btn edit-btn editBtn" title="Edit"
                            data-id="${item.id}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="action-btn delete-btn deleteBtn" title="Delete"
                            data-id="${item.id}"
                            data-name="${item.rm_grade}">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </td>
                </tr>`;
            });

            $('#rawMaterialTable tbody').html(rows);
            updateSummaryCards();

            // Initialize DataTable
            $('#rawMaterialTable').DataTable({
                pageLength: 10,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                order: [[0, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [5, 6] },
                    { className: 'align-middle', targets: '_all' }
                ],
                language: {
                    search: '',
                    searchPlaceholder: 'Search materials...',
                    lengthMenu: 'Show _MENU_',
                    info: 'Showing _START_ to _END_ of _TOTAL_',
                    infoEmpty: 'No entries found',
                    infoFiltered: '(filtered from _MAX_)',
                    paginate: {
                        first: '<i class="fas fa-angle-double-left"></i>',
                        last: '<i class="fas fa-angle-double-right"></i>',
                        next: '<i class="fas fa-chevron-right"></i>',
                        previous: '<i class="fas fa-chevron-left"></i>'
                    },
                    emptyTable: '<div class="text-center py-4"><i class="fas fa-cubes fa-3x text-muted mb-3"></i><p class="text-muted">No raw materials found</p></div>'
                },
                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rt<"row bottom-controls"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7 d-flex justify-content-end"p>>'
            });
        }).fail(function(err) {
            console.error('Failed to load raw materials:', err);
            showToast('error', 'Failed to load data. Please refresh the page.');
        });
    }

    loadRawMaterials();

    function updateSummaryCards() {
        $('#totalCount').text(rawMaterialsData.length);
        $('#activeCount').text(rawMaterialsData.length);
    }

    // Reset Form
    function resetForm() {
        $('#rawMaterialForm')[0].reset();
        $('#material_id').val('');
        $('#formErrors').addClass('d-none');
        $('#remove_existing_file').val('0');
        selectedFiles = [];
        $('#filePreview').empty();
        $('#existingFile').empty().hide();
        $('#fileCountDisplay').text('');
        $('#material_file').val('');
    }

    // Open Add Modal
    function openAddModal() {
        resetForm();
        $('#modalIcon').removeClass('fa-edit').addClass('fa-plus-circle');
        $('#rawMaterialModalLabel').html('<i class="fas fa-plus-circle mr-2" id="modalIcon"></i>Add Raw Material');
        $('#rawMaterialModal').modal('show');
    }

    $('#addMaterialBtn').on('click', openAddModal);
    $('#quickAddBtn').on('click', openAddModal);

    // Edit button click
    $('#rawMaterialTable').on('click', '.editBtn', function() {
        resetForm();
        var id = $(this).data('id');

        $.get("{{ url('superadmin/rawmaterials') }}/" + id, function(data) {
            $('#material_id').val(data.id);
            $('#rm_grade').val(data.rm_grade || '');
            $('#iso_specification').val(data.iso_specification || '');
            $('#density').val(data.density || '');
            $('#raw_material_type').val(data.raw_material_type || '');

            // Render existing files
            if (data.files && data.files.length > 0) {
                var existingHtml = '';
                data.files.forEach(function(file) {
                    var isImage = file.file_path.toLowerCase().match(/\.(jpeg|jpg|png|gif|bmp|webp)$/);
                    existingHtml += '<div class="file-box">';
                    existingHtml += '<button type="button" class="remove-existing-file-btn" onclick="deleteFileInModal(\'' + file.id + '\', this)">&times;</button>';

                    if (isImage) {
                        existingHtml += '<img src="{{ asset("storage") }}/' + file.file_path + '" alt="File">';
                    } else {
                        existingHtml += '<a href="{{ asset("storage") }}/' + file.file_path + '" target="_blank" class="btn btn-sm btn-outline-primary" style="font-size: 0.65rem;">' + (file.file_name || 'File') + '</a>';
                    }
                    existingHtml += '</div>';
                });
                $('#existingFile').html(existingHtml).show();
            }

            $('#modalIcon').removeClass('fa-plus-circle').addClass('fa-edit');
            $('#rawMaterialModalLabel').html('<i class="fas fa-edit mr-2" id="modalIcon"></i>Edit Raw Material');
            $('#rawMaterialModal').modal('show');
        }).fail(function() {
            showToast('error', 'Failed to load material data.');
        });
    });

    // File input change
    $('#material_file').on('change', function(e) {
        selectedFiles = selectedFiles.concat(Array.from(e.target.files));
        $(this).val('');
        renderFilePreview();
        updateFileCount();
    });

    function renderFilePreview() {
        var container = $('#filePreview');
        container.empty();

        selectedFiles.forEach(function(file, index) {
            var box = $('<div class="file-box"></div>');
            var removeBtn = $('<button type="button" class="remove-file-btn">&times;</button>');
            removeBtn.on('click', function() {
                selectedFiles.splice(index, 1);
                renderFilePreview();
                updateFileCount();
            });
            box.append(removeBtn);

            if (file.type.startsWith('image/')) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    box.append('<img src="' + e.target.result + '" alt="Preview">');
                };
                reader.readAsDataURL(file);
            } else {
                box.append('<a href="' + URL.createObjectURL(file) + '" target="_blank" class="btn btn-sm btn-outline-primary" style="font-size: 0.65rem;">' + file.name + '</a>');
            }

            container.append(box);
        });
    }

    function updateFileCount() {
        if (selectedFiles.length > 0) {
            $('#fileCountDisplay').text(selectedFiles.length + ' file' + (selectedFiles.length > 1 ? 's' : '') + ' selected');
        } else {
            $('#fileCountDisplay').text('');
        }
    }

    // Form submission
    $('#rawMaterialForm').submit(function(e) {
        e.preventDefault();

        var $btn = $('#saveBtn');
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');
        var $icon = $btn.find('.btn-icon');

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

        var id = $('#material_id').val();
        var url = id
            ? "{{ url('superadmin/rawmaterials/update') }}/" + id
            : "{{ route('superadmin.rawmaterial.store') }}";

        var formData = new FormData(this);
        selectedFiles.forEach(function(file) {
            formData.append('material_file[]', file);
        });
        if (id) formData.append('_method', 'PUT');

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                if (res.success) {
                    $('#rawMaterialModal').modal('hide');
                    loadRawMaterials();
                    showToast('success', res.message || 'Raw Material saved successfully!');
                } else {
                    showToast('error', res.message || 'Something went wrong.');
                }
            },
            error: function(err) {
                var errors = err.responseJSON?.errors || {};
                var message = err.responseJSON?.message || 'An error occurred';

                if (Object.keys(errors).length > 0) {
                    var errorHtml = '';
                    $.each(errors, function(field, messages) {
                        $.each(messages, function(i, msg) {
                            errorHtml += '<li>' + msg + '</li>';
                        });
                    });
                    $('#errorList').html(errorHtml);
                    $('#formErrors').removeClass('d-none');
                } else {
                    showToast('error', message);
                }
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $text.text('Save');
            }
        });
    });

    // Delete button click
    var deleteId = null;
    $('#rawMaterialTable').on('click', '.deleteBtn', function() {
        deleteId = $(this).data('id');
        $('#deleteItemName').text($(this).data('name'));
        $('#deleteRawMaterialModal').modal('show');
    });

    // Confirm delete
    $('#confirmDeleteBtn').on('click', function() {
        if (!deleteId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');
        var $icon = $btn.find('.btn-icon');

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

        $.ajax({
            url: "{{ url('superadmin/rawmaterials/delete') }}/" + deleteId,
            type: 'DELETE',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(res) {
                $('#deleteRawMaterialModal').modal('hide');
                loadRawMaterials();
                showToast('success', res.message || 'Raw Material deleted successfully!');
            },
            error: function(err) {
                showToast('error', err.responseJSON?.message || 'Failed to delete');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $text.text('Delete');
                deleteId = null;
            }
        });
    });

    // Toast notification
    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" data-delay="3500">
                <div class="toast-body">
                    <i class="fas ${icon} mr-2"></i>
                    <span class="flex-grow-1">${message}</span>
                    <button type="button" class="close ml-2" data-dismiss="toast">
                        <span>&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 accessible
    window.showToast = showToast;
});

// Delete file in edit modal
function deleteFileInModal(fileId, btn) {
    if (!confirm("Are you sure you want to delete this file?")) return;

    $.ajax({
        url: "{{ url('superadmin/raw-material') }}/" + fileId + "/delete-file",
        type: 'DELETE',
        data: { '_token': '{{ csrf_token() }}' },
        success: function(res) {
            if (res.success) {
                $(btn).closest('.file-box').remove();
                showToast('success', 'File deleted successfully');
            } else {
                showToast('error', res.message || 'Could not delete file.');
            }
        },
        error: function() {
            showToast('error', 'Server error. Please try again.');
        }
    });
}

// Delete file from list view
function deleteFileFromList(fileId) {
    if (!confirm("Are you sure you want to delete this file?")) return;

    $.ajax({
        url: "{{ url('superadmin/raw-material') }}/" + fileId + "/delete-file",
        type: 'DELETE',
        data: { '_token': '{{ csrf_token() }}' },
        success: function(res) {
            if (res.success) {
                location.reload();
            } else {
                showToast('error', res.message || 'Could not delete file.');
            }
        },
        error: function() {
            showToast('error', 'Server error. Please try again.');
        }
    });
}
</script>
@endsection
