@extends('layouts.dashboard.superadminapp')

@section('title', 'Production Processes')

@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: #6610f2; font-size: 0.7rem; }
    .time-box {
        background: linear-gradient(135deg, #6610f2 0%, #520dc2 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-indigo { background: linear-gradient(135deg, #6610f2 0%, #520dc2 100%); }
    .bg-gradient-success { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-gradient-info { background: linear-gradient(135deg, #36b9cc 0%, #258391 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, #6610f2 0%, #520dc2 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 */
    #processTable_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 */
    #processTable_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;
    }
    #processTable_wrapper .row.bottom-controls > div {
        padding: 0 0.5rem !important;
    }

    /* Enhanced Length Menu */
    #processTable_wrapper .dataTables_length {
        display: flex;
        align-items: center;
    }
    #processTable_wrapper .dataTables_length label {
        display: flex;
        align-items: center;
        gap: 0.6rem;
        font-size: 0.85rem;
        color: #5a5c69;
        margin-bottom: 0;
        font-weight: 500;
    }
    #processTable_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: #6610f2 !important;
        background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%236610f2' 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);
    }
    #processTable_wrapper .dataTables_length select:hover,
    #processTable_wrapper .dataTables_length select:focus {
        border-color: #6610f2 !important;
        box-shadow: 0 0 0 4px rgba(102, 16, 242, 0.15) !important;
        outline: none !important;
    }

    /* Enhanced Search Box */
    #processTable_wrapper .dataTables_filter {
        display: flex;
        align-items: center;
        position: relative;
    }
    #processTable_wrapper .dataTables_filter label {
        display: flex;
        align-items: center;
        gap: 0;
        font-size: 0;
        color: transparent;
        margin-bottom: 0;
        position: relative;
    }
    #processTable_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;
    }
    #processTable_wrapper .dataTables_filter input[type="search"]:focus {
        border-color: #6610f2 !important;
        box-shadow: 0 0 0 4px rgba(102, 16, 242, 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='%236610f2' 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 */
    #processTable_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 */
    #processTable_wrapper .dataTables_paginate {
        display: flex !important;
        align-items: center !important;
        gap: 0.35rem !important;
    }
    #processTable_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;
    }
    #processTable_wrapper .dataTables_paginate .paginate_button:hover:not(.disabled):not(.current) {
        background: linear-gradient(135deg, #6610f2 0%, #520dc2 100%) !important;
        border-color: #6610f2 !important;
        color: #fff !important;
        transform: translateY(-2px) !important;
        box-shadow: 0 6px 15px rgba(102, 16, 242, 0.4) !important;
    }
    #processTable_wrapper .dataTables_paginate .paginate_button.current {
        background: linear-gradient(135deg, #6610f2 0%, #520dc2 100%) !important;
        border-color: #6610f2 !important;
        color: #fff !important;
        box-shadow: 0 6px 15px rgba(102, 16, 242, 0.4) !important;
    }
    #processTable_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 */
    #processTable {
        border-collapse: separate;
        border-spacing: 0;
        width: 100% !important;
    }
    #processTable 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: #6610f2;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        cursor: pointer;
        transition: all 0.2s ease;
        white-space: nowrap;
    }
    #processTable thead th:hover {
        background: linear-gradient(135deg, #eef1f8 0%, #e3e8f4 100%);
        color: #520dc2;
    }

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

    #processTable tbody td {
        padding: 0.6rem 0.5rem;
        font-size: 0.78rem;
        border: none;
        border-bottom: 1px solid #e9ecef;
        vertical-align: middle;
    }
    #processTable tbody tr {
        transition: all 0.15s ease;
    }
    #processTable tbody tr:hover {
        background-color: rgba(102, 16, 242, 0.05) !important;
        transform: scale(1.002);
        box-shadow: 0 2px 8px rgba(102, 16, 242, 0.1);
    }
    #processTable 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; }

    /* 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);
        cursor: pointer;
    }
    .quick-link-card:hover {
        border-color: #6610f2;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 16, 242, 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 */
    .modal .modal-content {
        border: none;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    }
    .modal .modal-header.primary-header {
        background: linear-gradient(135deg, #6610f2 0%, #520dc2 100%) !important;
        padding: 0.6rem 1rem !important;
        border-bottom: 2px solid rgba(255,255,255,0.2) !important;
    }
    .modal .modal-header.success-header {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%) !important;
        padding: 0.6rem 1rem !important;
        border-bottom: 2px solid rgba(255,255,255,0.2) !important;
    }
    .modal .modal-header.info-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;
    }
    .modal .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;
    }
    .modal .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;
    }
    .modal .modal-header .close:hover {
        background: rgba(255,255,255,0.35);
        transform: rotate(90deg);
    }
    .modal .modal-title {
        font-size: 0.9rem;
        font-weight: 600;
        color: #fff !important;
    }
    .modal .modal-body {
        padding: 1rem !important;
        background: #fff;
    }
    .modal .modal-footer {
        background: #f8f9fc;
        border-top: 1px solid #e3e6f0;
        padding: 0.6rem 1rem;
        display: flex;
        justify-content: flex-end;
        gap: 0.5rem;
    }
    .modal .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;
    }
    .modal .modal-footer .btn-secondary {
        background: linear-gradient(135deg, #6c757d 0%, #545b62 100%);
        border: none;
        color: #fff;
    }
    .modal .modal-footer .btn-primary {
        background: linear-gradient(135deg, #6610f2 0%, #520dc2 100%);
        border: none;
        color: #fff;
    }
    .modal .modal-footer .btn-success {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        border: none;
        color: #fff;
    }

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

    /* Operators Display */
    .operator-badge {
        background: linear-gradient(135deg, #f0f0f0 0%, #e8e8e8 100%);
        padding: 4px 10px;
        border-radius: 12px;
        font-size: 0.75rem;
        white-space: nowrap;
        margin: 2px;
        display: inline-block;
    }
    .more-operators-btn {
        background: linear-gradient(135deg, #6610f2 0%, #520dc2 100%);
        border: none;
        padding: 4px 10px;
        border-radius: 12px;
        cursor: pointer;
        font-size: 0.75rem;
        color: #fff;
    }
    .operators-dropdown {
        position: absolute;
        background: white;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 8px;
        left: 12px;
        display: none;
        flex-wrap: wrap;
        gap: 8px;
        max-height: none;
        z-index: 1000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
    .row-details {
        padding: 12px;
        background: #f9f9f9;
        border-top: 1px solid #eee;
    }

    /* View Modal Tables */
    #machinesSummaryTable thead th,
    #operatorsSummaryTable thead th {
        background: linear-gradient(135deg, #f8f9fc 0%, #eaecf4 100%);
        color: #6610f2;
        font-weight: 700;
        text-transform: uppercase;
        font-size: 0.7rem;
        padding: 0.6rem 0.5rem;
        border-bottom: 2px solid #e3e6f0;
    }
    #machinesSummaryTable tbody td,
    #operatorsSummaryTable tbody td {
        vertical-align: middle;
        padding: 0.5rem;
        font-size: 0.78rem;
    }

    /* 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; }
        #processTable_wrapper .dataTables_filter input[type="search"] {
            min-width: 180px !important;
        }
    }
    @media (max-width: 576px) {
        #processTable_wrapper .row.bottom-controls {
            flex-direction: column !important;
            gap: 0.75rem;
        }
        #processTable_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-tasks mr-2" style="color: #6610f2;"></i>UEPL | Production Processes</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-indigo shadow">
                <i class="fas fa-tasks kpi-icon"></i>
                <div class="kpi-value" id="totalCount">0</div>
                <div class="kpi-label">Total Processes</div>
                <div class="kpi-info"><i class="fas fa-database mr-1"></i> All records</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-boxes kpi-icon"></i>
                <div class="kpi-value" id="productTypeCount">0</div>
                <div class="kpi-label">Product Types</div>
                <div class="kpi-info"><i class="fas fa-list mr-1"></i> Categories</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" style="font-size: 0.85rem; color: #6610f2;">
                <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">
                    <div class="quick-link-card" id="quickAddBtn">
                        <i class="fas fa-plus-circle text-success"></i>
                        <div class="link-title">Add Process</div>
                    </div>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <div class="quick-link-card" data-toggle="modal" data-target="#assignModal" data-assign-mode="m2o">
                        <i class="fas fa-cogs text-primary"></i>
                        <div class="link-title">Assign Machines</div>
                    </div>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <div class="quick-link-card" data-toggle="modal" data-target="#machineModel" data-assign-mode="o2m">
                        <i class="fas fa-user-cog text-warning"></i>
                        <div class="link-title">Assign Operators</div>
                    </div>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <div class="quick-link-card" data-toggle="modal" data-target="#viewMachinesModal">
                        <i class="fas fa-tools text-info"></i>
                        <div class="link-title">View Machines</div>
                    </div>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <div class="quick-link-card" data-toggle="modal" data-target="#viewOperatorsModal">
                        <i class="fas fa-users text-secondary"></i>
                        <div class="link-title">View Operators</div>
                    </div>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.conversionprocess.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-exchange-alt" style="color: #6f42c1;"></i>
                            <div class="link-title">Conversion</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> Process Directory
            </h6>
            <button class="add-btn" id="addProcessBtn" title="Add Process">
                <i class="fas fa-plus mr-1"></i> Add Process
            </button>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="processTable">
                    <thead>
                        <tr class="text-center">
                            <th width="8%">Sl.No</th>
                            <th width="30%">Product Type</th>
                            <th width="35%">Process Name</th>
                            <th width="12%">Order</th>
                            <th width="15%">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Loaded by AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<!-- Add/Edit Process Modal -->
<div class="modal fade" id="processModal" tabindex="-1" aria-labelledby="processModalLabel" 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="processModalLabel">
                    <i class="fas fa-plus-circle mr-2" id="modalIcon"></i>Add Process
                </h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>

            <form id="processForm">
                @csrf
                <input type="hidden" id="process_id" name="process_id">
                <div class="modal-body">
                    <div class="mb-2">
                        <label class="form-label"><i class="fas fa-boxes" style="color: #6610f2;"></i> Product Type <span class="text-danger">*</span></label>
                        <select class="form-select form-control-modern" name="product_type_id" id="product_type_id" required>
                            <option value="">Select Product Type</option>
                            @foreach ($productTypes as $type)
                                <option value="{{ $type->id }}">{{ $type->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label"><i class="fas fa-tasks" style="color: #6610f2;"></i> Process Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control form-control-modern" name="name" id="name" placeholder="Enter process name" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label"><i class="fas fa-sort-numeric-up" style="color: #6610f2;"></i> Order <span class="text-danger">*</span></label>
                        <input type="number" class="form-control form-control-modern" name="order" id="order" placeholder="Enter sequence order" min="1" required>
                    </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="saveProcessBtn">
                        <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>

<!-- Assign Machines Modal -->
<div class="modal fade" id="assignModal" tabindex="-1" aria-labelledby="assignModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header success-header">
                <h6 class="modal-title mb-0" id="assignModalLabel">
                    <i class="fas fa-cogs mr-2"></i>Assign Machines
                </h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>

            <form id="assignForm">
                @csrf
                <div class="modal-body">
                    <div class="mb-2">
                        <label class="form-label"><i class="fas fa-boxes text-success"></i> Product Type</label>
                        <select class="form-select form-control-modern" id="assign_product_type_id">
                            <option value="">Select Type</option>
                            @foreach ($productTypes as $type)
                                <option value="{{ $type->id }}">{{ $type->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label"><i class="fas fa-tasks text-success"></i> Process</label>
                        <select class="form-select form-control-modern" id="assign_process_dropdown" name="process_id" required>
                            <option value="">Select process</option>
                        </select>
                    </div>
                    <div class="mb-2 form-group">
                        <label class="form-label"><i class="fas fa-cogs text-success"></i> Machines</label>
                        <select class="form-control selectpicker" name="machines[]" id="assign_machines" multiple data-live-search="true">
                            @foreach ($machines as $machine)
                                <option value="{{ $machine->id }}">{{ $machine->machine_name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-2 form-group d-none">
                        <label class="form-label"><i class="fas fa-users text-success"></i> Operators</label>
                        <select class="form-control selectpicker" name="operators" id="assign_operators" data-live-search="true">
                            @foreach ($employees as $emp)
                                <option value="{{ $emp->id }}">{{ $emp->name }}</option>
                            @endforeach
                        </select>
                    </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-success" id="assignMachinesBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <i class="fas fa-check btn-icon"></i>
                        <span class="btn-text">Assign</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Machines Modal -->
<div class="modal fade" id="viewMachinesModal" tabindex="-1" aria-labelledby="viewMachinesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header info-header">
                <h6 class="modal-title mb-0" id="viewMachinesModalLabel">
                    <i class="fas fa-tools mr-2"></i>Assigned Machines
                </h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="machinesSummaryTable" width="100%">
                        <thead>
                            <tr class="text-center">
                                <th width="60">Sl No</th>
                                <th>Product Type</th>
                                <th>Process</th>
                                <th>Assigned Machines</th>
                                <th width="100">Actions</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

@include('superadmin.master.viewoperators')
@include('superadmin.master.assign_operators')
@endsection

@section('scripts')
@stack('viewoperators_scripts')
@yield('viewoperators_scripts')
@stack('assign_operators_scripts')
@yield('assign_operators_scripts')

<script>
$(document).ready(function() {
    var processData = [];

    // 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);

    // 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(); });
    }

    window.showToast = showToast;

    // Format operators display
    window.formatOperators = function(names, maxShow) {
        if (!names || names.length === 0) return '<span class="text-muted">None</span>';
        if (maxShow === 0 || names.length <= maxShow) {
            return names.map(n => `<span class="operator-badge">${n}</span>`).join('');
        }
        const visible = names.slice(0, maxShow);
        const hidden = names.slice(maxShow);
        return visible.map(n => `<span class="operator-badge">${n}</span>`).join('') +
            `<button class="more-operators-btn">+${hidden.length} more</button>
             <div class="operators-dropdown">${hidden.map(n => `<span class="operator-badge">${n}</span>`).join('')}</div>`;
    };

    // Initialize DataTable for machines summary
    const machinesSummaryTableInstance = $('#machinesSummaryTable').DataTable({
        responsive: true,
        scrollX: false,
        autoWidth: false,
        columnDefs: [{
            targets: 0,
            className: 'control',
            orderable: false,
            render: function(data, type, row, meta) {
                return type === 'display' ?
                    `<span>${meta.row + 1}</span>
                    <i class="fas toggle-row-details ml-2 fa-chevron-down" data-row-index="${meta.row}"></i>` :
                    meta.row + 1;
            }
        }],
        order: [[1, 'asc']]
    });

    // Load Processes
    function loadProcesses() {
        if ($.fn.DataTable.isDataTable('#processTable')) {
            $('#processTable').DataTable().clear().destroy();
        }
        $('#processTable tbody').empty();

        $.get('{{ route('superadmin.process.api') }}', function(res) {
            processData = res.data;
            let rows = '';

            $.each(res.data, function(i, item) {
                rows += `<tr class="text-center">
                    <td class="font-weight-bold text-muted">${i + 1}</td>
                    <td class="text-left">
                        <i class="fas fa-boxes mr-1 text-success"></i>
                        <span class="font-weight-500">${item.product_type?.name || '-'}</span>
                    </td>
                    <td class="text-left">
                        <i class="fas fa-tasks mr-1" style="color: #6610f2;"></i>
                        <span class="font-weight-500">${item.name || '-'}</span>
                    </td>
                    <td><span class="badge badge-light">${item.order || '-'}</span></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.name}">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </td>
                </tr>`;
            });

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

            // Initialize DataTable
            $('#processTable').DataTable({
                pageLength: 10,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                order: [[0, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [4] },
                    { className: 'align-middle', targets: '_all' }
                ],
                language: {
                    search: '',
                    searchPlaceholder: 'Search processes...',
                    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-tasks fa-3x text-muted mb-3"></i><p class="text-muted">No processes 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 processes:', err);
            showToast('error', 'Failed to load data. Please refresh the page.');
        });
    }

    loadProcesses();

    function updateSummaryCards() {
        $('#totalCount').text(processData.length);
        var uniqueTypes = [...new Set(processData.map(p => p.product_type_id))];
        $('#productTypeCount').text(uniqueTypes.length);
    }

    // Reset Form
    function resetForm() {
        $('#processForm')[0].reset();
        $('#process_id').val('');
    }

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

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

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

        $.get("{{ url('superadmin/processes') }}/" + id, function(data) {
            $('#process_id').val(data.id);
            $('#name').val(data.name || '');
            $('#order').val(data.order || '');
            $('#product_type_id').val(data.product_type_id || '');

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

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

        var $btn = $('#saveProcessBtn');
        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 = $('#process_id').val();
        var url = id
            ? "{{ url('superadmin/processes/update') }}/" + id
            : "{{ route('superadmin.process.store') }}";

        var formData = new FormData(this);
        if (id) formData.append('_method', 'PUT');

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: { 'X-CSRF-TOKEN': "{{ csrf_token() }}" },
            success: function(res) {
                if (res.success) {
                    $('#processModal').modal('hide');
                    loadProcesses();
                    showToast('success', res.message || 'Process saved successfully!');
                } else {
                    showToast('error', res.message || 'Something went wrong.');
                }
            },
            error: function(err) {
                if (err.status === 422) {
                    var errors = err.responseJSON.errors;
                    var firstError = Object.values(errors)[0][0];
                    showToast('error', firstError);
                } else {
                    showToast('error', err.responseJSON?.message || 'An error occurred');
                }
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $text.text('Save');
            }
        });
    });

    // Delete button click
    $('#processTable').on('click', '.deleteBtn', function() {
        var deleteId = $(this).data('id');
        var deleteName = $(this).data('name');

        if (confirm('Are you sure you want to delete "' + deleteName + '"?')) {
            $.ajax({
                url: "{{ url('superadmin/processes/delete') }}/" + deleteId,
                type: 'DELETE',
                data: { '_token': '{{ csrf_token() }}' },
                success: function(res) {
                    if (res.success) {
                        loadProcesses();
                        showToast('success', res.message || 'Process deleted successfully!');
                    } else {
                        showToast('error', 'Failed to delete process');
                    }
                },
                error: function() {
                    showToast('error', 'Failed to delete process');
                }
            });
        }
    });

    // View Machines Modal Load
    $('#viewMachinesModal').on('show.bs.modal', function() {
        $.ajax({
            url: "{{ route('superadmin.process.viewMachinesSummary') }}",
            type: 'GET',
            success: function(response) {
                machinesSummaryTableInstance.backdata = {};
                machinesSummaryTableInstance.clear();
                response.data.forEach(function(row, index) {
                    machinesSummaryTableInstance.backdata[index] = row;
                    machinesSummaryTableInstance.row.add([
                        index + 1,
                        row.product_type.name,
                        row.name,
                        formatOperators(row.machines.map(v => v.machine_name), 3),
                        `<button id="edit-process" class="action-btn edit-btn"
                            data-machines="${row.machines.map(v => v.id).join(', ')}"
                            data-process="${row.id}"
                            data-process-type="${row.product_type.id}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button id="delete-process" class="action-btn delete-btn">
                            <i class="fas fa-trash-alt"></i>
                        </button>`
                    ]);
                });
                machinesSummaryTableInstance.draw();
            },
            error: function() {
                showToast('error', 'Failed to load machines summary');
            }
        });
    });

    // Edit machine assignment
    $(document).on('click', '#edit-process', function() {
        const machines = $(this).data('machines').toString().split(',').map(Number);
        const processId = $(this).data('process');
        const processTypeId = $(this).data('process-type');
        $('#viewMachinesModal .close').click();
        $('#assign_machines').val(machines);
        $('#assign_machines').selectpicker('refresh');
        $('#assign_product_type_id').val(processTypeId);
        $('#assign_process_dropdown').attr('data-process', processId);
        $('#assign_product_type_id').change();
        $('#assignModal').modal('show');
    });

    // Delete machine assignment
    $(document).on('click', '#delete-process', function() {
        const row = $(this).closest('tr');
        const processId = row.find('#edit-process').data('process');
        if (confirm('Are you sure to delete this process assignment?')) {
            $.ajax({
                url: "{{ url('superadmin/processes/delete') }}/" + processId,
                type: 'DELETE',
                data: { '_token': '{{ csrf_token() }}' },
                success: function(res) {
                    if (res.success) {
                        row.remove();
                        showToast('success', res.message);
                    } else {
                        showToast('error', 'Error deleting process');
                    }
                },
                error: function() {
                    showToast('error', 'Failed to delete process');
                }
            });
        }
    });

    // Toggle row details in machines table
    $(document).on('click', '#machinesSummaryTable .toggle-row-details', function() {
        const rowIndex = $(this).data('row-index');
        const row = machinesSummaryTableInstance.row(rowIndex);
        const brow = machinesSummaryTableInstance.backdata[rowIndex];
        const $icon = $(this);
        if (row.child.isShown()) {
            row.child.hide();
            $icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
        } else {
            const detailsContent = `
                <div class="row-details">
                    <h6>Machine Details</h6>
                    ${formatOperators(brow.machines.map(v => v.machine_name), 0)}
                </div>
            `;
            row.child(detailsContent).show();
            $icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
        }
    });

    // Assign Modal mode handling
    $('#assignModal').on('show.bs.modal', function(event) {
        const button = event?.relatedTarget;
        const assignMode = button?.dataset?.assignMode || "m2o";
        const machinesSelect = $('#assign_machines');
        const operatorsSelect = $('#assign_operators');
        if (assignMode == "m2o") {
            operatorsSelect.parent().addClass("d-none");
            operatorsSelect.removeAttr('required');
            machinesSelect.parent().removeClass("d-none");
            machinesSelect.attr('required', true);
        } else {
            machinesSelect.parent().addClass("d-none");
            machinesSelect.removeAttr('required');
            operatorsSelect.parent().removeClass("d-none");
            operatorsSelect.attr('required', true);
        }
    });

    // Product type change in assign modal
    $('#assign_product_type_id').on('change', function() {
        const typeId = this.value;
        const selectedProcess = $('#assign_process_dropdown').data('process') || '';
        $.ajax({
            url: "{{ url('superadmin/processes/api') }}?product_type_id=" + typeId,
            type: 'GET',
            success: function(response) {
                const dropdown = $('#assign_process_dropdown');
                dropdown.html('<option value="">Select process</option>');
                response.data.forEach(function(proc) {
                    dropdown.append(`<option value="${proc.id}" ${selectedProcess == proc.id ? 'selected' : ''}>${proc.name}</option>`);
                });
            }
        });
    });

    // Assign form submission
    $('#assignForm').on('submit', function(e) {
        e.preventDefault();

        var $btn = $('#assignMachinesBtn');
        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('Assigning...');

        var formData = new FormData(this);

        $.ajax({
            url: "{{ route('superadmin.process.assign') }}",
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: { 'X-CSRF-TOKEN': "{{ csrf_token() }}" },
            success: function(response) {
                this.reset();
                $('#assign_machines').selectpicker('refresh');
                $('#assign_operators').selectpicker('refresh');
                showToast(response.success ? 'success' : 'error', response.message || (response.success ? "Assigned successfully!" : "Error!"));
                if (response.success) {
                    $('#assignModal').modal('hide');
                }
            }.bind(this),
            error: function() {
                showToast('error', 'An error occurred while submitting');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $text.text('Assign');
            }
        });
    });
});
</script>
@endsection
