@extends('layouts.dashboard.app')

@section('style')
<style>
/* ============================================
   DEVIS SHOW - MODERN REDESIGN WITH TABS
   ============================================ */

/* Header Card */
.page-header {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    border-radius: 16px;
    padding: 20px 25px;
    margin-bottom: 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.page-header .header-content {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
}

.page-header .header-left {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.page-header .header-title {
    font-size: 22px;
    font-weight: 700;
    color: #fff;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-header .header-title i {
    color: #10b981;
}

.page-header .header-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 12px;
}

/* Navigation Buttons */
.nav-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.nav-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 14px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
    white-space: nowrap;
}

.nav-btn.primary {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
}

.nav-btn.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
    color: #fff;
}

.nav-btn.secondary {
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.nav-btn.secondary:hover {
    background: rgba(255, 255, 255, 0.2);
    color: #fff;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    white-space: nowrap;
}

.status-badge.devis-number {
    background: rgba(255, 255, 255, 0.15);
    color: #fff;
}

.status-badge.warning {
    background: rgba(245, 158, 11, 0.2);
    color: #fbbf24;
}

.status-badge.info {
    background: rgba(59, 130, 246, 0.2);
    color: #60a5fa;
}

.status-badge.success {
    background: rgba(16, 185, 129, 0.2);
    color: #34d399;
}

.status-badge.danger {
    background: rgba(239, 68, 68, 0.2);
    color: #f87171;
}

.status-badge.dark {
    background: rgba(0, 0, 0, 0.3);
    color: #fff;
}

/* Action Bar - FIXED OVERFLOW */
.action-bar {
    background: #fff;
    border-radius: 12px;
    padding: 12px 15px;
    margin-bottom: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
}

.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;
    min-width: fit-content;
    flex-shrink: 0;
    text-decoration: none;
}

.action-btn i {
    font-size: 14px;
    flex-shrink: 0;
}

.action-btn.success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
}

.action-btn.success:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

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

.action-btn.danger:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

.action-btn.warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: #fff;
}

.action-btn.warning:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
}

.action-btn.info {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: #fff;
}

.action-btn.info:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

/* Summary Cards Row */
.summary-cards {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 12px;
    margin-bottom: 20px;
}

@media (max-width: 1200px) {
    .summary-cards {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 768px) {
    .summary-cards {
        grid-template-columns: repeat(2, 1fr);
    }
}

.summary-card {
    background: #fff;
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
    transition: all 0.2s ease;
}

.summary-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.summary-card .card-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
}

.summary-card .card-icon i {
    font-size: 20px;
    color: #fff;
}

.summary-card .card-icon.green { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.summary-card .card-icon.blue { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); }
.summary-card .card-icon.orange { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
.summary-card .card-icon.purple { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); }

.summary-card .card-label {
    font-size: 11px;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 4px;
}

.summary-card .card-value {
    font-size: 16px;
    font-weight: 700;
    color: #1e293b;
}

.summary-card .card-value input {
    font-size: 14px;
    font-weight: 600;
    color: #1e293b;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    padding: 6px 10px;
    width: 100%;
    background: #f8fafc;
}

.summary-card .card-value input:focus {
    border-color: #10b981;
    outline: none;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.1);
}

.summary-card .card-value input[readonly] {
    background: #f1f5f9;
    color: #64748b;
}

/* ============================================
   TABS NAVIGATION
   ============================================ */
.tabs-container {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    border: 1px solid #e2e8f0;
    margin-bottom: 20px;
}

.tabs-nav {
    display: flex;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.tabs-nav::-webkit-scrollbar {
    height: 0;
}

.tab-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 14px 20px;
    font-size: 13px;
    font-weight: 600;
    color: #64748b;
    background: transparent;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;
    border-bottom: 3px solid transparent;
    margin-bottom: -1px;
}

.tab-btn i {
    font-size: 16px;
}

.tab-btn:hover {
    color: #10b981;
    background: rgba(16, 185, 129, 0.05);
}

.tab-btn.active {
    color: #10b981;
    background: #fff;
    border-bottom-color: #10b981;
}

.tab-btn .tab-badge {
    background: #e2e8f0;
    color: #64748b;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 11px;
    font-weight: 700;
}

.tab-btn.active .tab-badge {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.tab-content {
    display: none !important;
    padding: 20px;
}

.tab-content.active {
    display: block !important;
}

/* ============================================
   DOCUMENTS GALLERY
   ============================================ */
.gallery-section {
    margin-bottom: 20px;
}

.gallery-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 15px;
}

.gallery-header h5 {
    margin: 0;
    font-size: 14px;
    font-weight: 700;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 8px;
}

.gallery-header h5 i {
    color: #10b981;
}

.gallery-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.gallery-tab {
    padding: 5px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
    background: #e2e8f0;
    color: #64748b;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
}

.gallery-tab:hover,
.gallery-tab.active {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
}

.gallery-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 12px;
}

.gallery-item {
    position: relative;
    border-radius: 10px;
    overflow: hidden;
    background: #f8fafc;
    transition: all 0.2s ease;
    cursor: pointer;
    border: 1px solid #e2e8f0;
}

.gallery-item:hover {
    transform: scale(1.03);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

.gallery-item img {
    width: 100%;
    height: 80px;
    object-fit: cover;
}

.gallery-item .item-badge {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 4px 6px;
    font-size: 9px;
    font-weight: 600;
    text-align: center;
    color: #fff;
}

.gallery-item .item-badge.primary { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); }
.gallery-item .item-badge.success { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.gallery-item .item-badge.info { background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); }

.gallery-item .item-overlay {
    position: absolute;
    top: 5px;
    right: 5px;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.gallery-item:hover .item-overlay {
    opacity: 1;
}

.gallery-item .item-overlay a {
    width: 24px;
    height: 24px;
    border-radius: 5px;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #1e293b;
    font-size: 12px;
    text-decoration: none;
}

.gallery-item .item-overlay a:hover {
    background: #10b981;
    color: #fff;
}

/* Hidden class for gallery filter */
.gallery-item.hidden {
    display: none;
}

/* ============================================
   PIECES TABLE
   ============================================ */
.table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 15px;
}

.table-header h5 {
    margin: 0;
    font-size: 14px;
    font-weight: 700;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 8px;
}

.table-header h5 i {
    color: #10b981;
}

.table-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}

.modern-table thead th {
    background: #f8fafc;
    border-bottom: 2px solid #e2e8f0;
    padding: 10px 8px;
    font-size: 10px;
    font-weight: 600;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    text-align: left;
    white-space: nowrap;
}

.modern-table tbody td {
    padding: 8px;
    border-bottom: 1px solid #f1f5f9;
    font-size: 12px;
    color: #334155;
    vertical-align: middle;
}

.modern-table tbody tr:hover {
    background: #f8fafc;
}

.modern-table .form-control,
.modern-table .form-select {
    padding: 6px 8px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 11px;
    background: #fff;
    min-width: 80px;
}

.modern-table .form-control:focus,
.modern-table .form-select:focus {
    border-color: #10b981;
    outline: none;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.1);
}

.modern-table .form-check-input {
    width: 16px;
    height: 16px;
    border: 2px solid #e2e8f0;
    border-radius: 4px;
    cursor: pointer;
}

.modern-table .form-check-input:checked {
    background-color: #10b981;
    border-color: #10b981;
}

/* ============================================
   OBSERVATIONS
   ============================================ */
.observation-list {
    max-height: 400px;
    overflow-y: auto;
}

.observation-item {
    background: #f8fafc;
    border-radius: 10px;
    padding: 12px 15px;
    margin-bottom: 10px;
    border-left: 4px solid #10b981;
}

.observation-item .obs-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 6px;
}

.observation-item .obs-user {
    font-weight: 600;
    font-size: 13px;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 6px;
}

.observation-item .obs-user i {
    color: #10b981;
}

.observation-item .obs-date {
    font-size: 10px;
    color: #64748b;
}

.observation-item .obs-content {
    color: #475569;
    font-size: 13px;
    line-height: 1.5;
}

.observation-form textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    font-size: 13px;
    resize: vertical;
    min-height: 80px;
}

.observation-form textarea:focus {
    border-color: #10b981;
    outline: none;
    box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

/* Quick Observation */
.quick-obs-card {
    background: #fff;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
}

.quick-obs-card .obs-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

.quick-obs-card h6 {
    margin: 0;
    font-size: 13px;
    font-weight: 600;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 6px;
}

.quick-obs-card h6 i {
    color: #10b981;
}

.quick-obs-card textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 12px;
    resize: none;
    height: 60px;
}

.quick-obs-card textarea:focus {
    border-color: #10b981;
    outline: none;
}

/* Responsive */
@media (max-width: 768px) {
    .page-header {
        padding: 15px;
    }
    
    .page-header .header-content {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .page-header .header-title {
        font-size: 18px;
    }
    
    .nav-buttons {
        width: 100%;
    }
    
    .nav-btn {
        flex: 1;
        justify-content: center;
        padding: 8px 10px;
        font-size: 11px;
    }
    
    .action-bar {
        padding: 10px;
    }
    
    .action-btn {
        padding: 6px 12px;
        font-size: 11px;
    }
    
    .tab-btn {
        padding: 10px 15px;
        font-size: 12px;
    }
    
    .tab-btn i {
        font-size: 14px;
    }
    
    .modern-table {
        display: block;
        overflow-x: auto;
    }
}
</style>
@endsection

@section('content')
@can('update', App\Models\Devis::class)
<form action="{{ route('Devis.status', $devis->id) }}" method="post">
    @csrf
    @method('PUT')
    
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <div class="header-left">
                <h1 class="header-title">
                    <i class="uil uil-file-edit-alt"></i>
                    Devis
                    @if (intval($devis->devis) == 1)
                        <span class="status-badge devis-number">{{ $devis->devis }}er</span>
                    @elseif(intval($devis->devis) > 1)
                        <span class="status-badge devis-number">{{ $devis->devis }}ème</span>
                    @endif
                </h1>
            </div>
            <div class="nav-buttons">
                <a href="{{ route('Dossier.show', $devis->dossier_id) }}" class="nav-btn secondary">
                    <i class="uil uil-folder"></i> Dossier
                </a>
                <a href="{{ route('Devis.index', $dossier->id) }}" class="nav-btn primary">
                    <i class="uil uil-files-landscapes"></i> Liste
                </a>
            </div>
        </div>
        <div class="header-badges">
            @if ($devis->devisstatus)
                @foreach ($devis->devisstatus as $item)
                    <span class="status-badge bg-{{ $item->color }}">{{ $item->status }}</span>
                    @php $user = App\Models\User::whereId($item->user_id)->first(); @endphp
                    @if($user)
                        <span class="status-badge dark">{{ $user->name }}</span>
                    @endif
                @endforeach
            @endif
            @if ($dossier->typeexpertise)
                <span class="status-badge warning">{{ $dossier->typeexpertise->type ?? null }}</span>
            @endif
            @if ($dossier->mode)
                <span class="status-badge info">{{ $dossier->mode->mode ?? null }}</span>
            @endif
            @if ($historiques > 0)
                <span class="status-badge danger">En cours: {{ $historiques }}</span>
            @endif
            @if ($devis->dossier->sinistre_douteux)
                <span class="status-badge danger">Douteux</span>
            @endif
        </div>
    </div>

    <!-- Action Bar -->
    @php
        $showActionBar = false;
        if ($devis->devis_status_id == 2 && (Auth::user()->role_id == 1 || Auth::user()->role_id == 4)) $showActionBar = true;
        if (in_array($devis->devis_status_id, [2, 6, 7]) && Auth::user()->can('modifieraccord', App\Models\Devis::class)) $showActionBar = true;
        if ($devis->devis_status_id == 5 && Auth::user()->can('chiffrage', App\Models\Devis::class)) $showActionBar = true;
        if ($devis->devis_status_id == 4 && Auth::user()->can('chiffrage', App\Models\Devis::class)) $showActionBar = true;
        if (in_array($devis->devis_status_id, [3, 8]) && Auth::user()->can('controler', App\Models\Devis::class)) $showActionBar = true;
    @endphp
    
    @if($showActionBar)
    <div class="action-bar">
        @if ($devis->devis_status_id == 2 && (Auth::user()->role_id == 1 || Auth::user()->role_id == 4))
            <button name="action" value="envoyer" class="action-btn info">
                <i class="uil uil-message"></i> Envoyer
            </button>
        @endif

        @if (in_array($devis->devis_status_id, [2, 6, 7]))
            @can('modifieraccord', App\Models\Devis::class)
                <button name="action" value="accord" class="action-btn success">
                    <i class="uil uil-edit"></i> Mod. Accord
                </button>
            @endcan
        @endif

        @if ($devis->devis_status_id == 5)
            @can('chiffrage', App\Models\Devis::class)
                <button name="action" value="accord" class="action-btn success">
                    <i class="uil uil-check"></i> Accord
                </button>
                <button name="action" value="rejeter" class="action-btn danger">
                    <i class="uil uil-times"></i> Rejeter
                </button>
            @endcan
        @elseif ($devis->devis_status_id == 4)
            @can('chiffrage', App\Models\Devis::class)
                <button name="action" value="accord" class="action-btn success">
                    <i class="uil uil-check"></i> Accord
                </button>
                @if (Auth::user()->role_id == 4)
                    <button name="action" value="rejeter" class="action-btn danger">
                        <i class="uil uil-times"></i> Rejeter
                    </button>
                @endif
                <button name="action" value="avis" class="action-btn warning">
                    <i class="uil uil-question"></i> Avis
                </button>
            @endcan
        @elseif (in_array($devis->devis_status_id, [3, 8]))
            @can('controler', App\Models\Devis::class)
                <button name="action" value="accord" class="action-btn success">
                    <i class="uil uil-check"></i> Accord
                </button>
                <button name="action" value="retraiter" class="action-btn warning">
                    <i class="uil uil-redo"></i> Retraiter
                </button>
                <button name="action" value="rejeter" class="action-btn danger">
                    <i class="uil uil-times"></i> Rejeter
                </button>
            @endcan
        @endif
    </div>
    @endif

    <!-- Summary Cards -->
    <div class="summary-cards">
        <div class="summary-card">
            <div class="card-icon green"><i class="uil uil-tag-alt"></i></div>
            <div class="card-label">Référence</div>
            <div class="card-value">{{ $devis->dossier->ref ?? '-' }}</div>
        </div>
        <div class="summary-card">
            <div class="card-icon blue"><i class="uil uil-calendar-alt"></i></div>
            <div class="card-label">Réception</div>
            <div class="card-value">{{ $devis->date_reception ?? '-' }}</div>
        </div>
        <div class="summary-card">
            <div class="card-icon orange"><i class="uil uil-receipt"></i></div>
            <div class="card-label">Mt. Devis</div>
            <div class="card-value">
                <input type="text" name="montant_devis" readonly value="{{ $montant->devis->montant_devis ?? null }}">
            </div>
        </div>
        <div class="summary-card">
            <div class="card-icon green"><i class="uil uil-check-square"></i></div>
            <div class="card-label">Mt. Accord</div>
            <div class="card-value">
                <input type="text" name="montant_accord" 
                    @if (!(Auth::user()->role_id == 4 || in_array($devis->devis_status_id, [3, 4, 5, 8]))) readonly @endif
                    @if (in_array($dossier->type_expertise_id, [3, 4, 5, 6, 7]) && !in_array($dossier->mode_id, [2, 3])) readonly @endif
                    value="{{ $montant->montant_accord ?? null }}">
            </div>
        </div>
        <div class="summary-card">
            <div class="card-icon purple"><i class="uil uil-invoice"></i></div>
            <div class="card-label">Mt. Facture</div>
            <div class="card-value">
                <input type="text" readonly value="{{ $montant->facture->montant_facture ?? null }}" name="montant_facture">
            </div>
        </div>
        <div class="summary-card">
            <div class="card-icon blue"><i class="uil uil-file-check-alt"></i></div>
            <div class="card-label">Mt. Rapport</div>
            <div class="card-value">
                <input type="text" value="{{ $montant->montant_rapport ?? null }}" name="montant_rapport" readonly>
            </div>
        </div>
    </div>

    <!-- Quick Observation -->
    <div class="quick-obs-card">
        <div class="obs-header">
            <h6><i class="uil uil-comment-alt-notes"></i> Observation</h6>
            <span class="status-badge bg-{{ $devis->status->color }}">{{ $devis->status->status }}</span>
        </div>
        <textarea class="form-control @error('observation') is-invalid @enderror" name="observation" 
            placeholder="Ajouter une observation..."></textarea>
        @error('observation')
            <span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>
        @enderror
    </div>
</form>
@endcan

<!-- Tab Script - Must be before tabs HTML -->
<script>
// Tab switching function - global scope
function switchTab(tabId) {
    // Remove active from all tabs
    var tabs = document.querySelectorAll('.tab-btn');
    for (var i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove('active');
    }
    
    // Remove active from all tab contents
    var contents = document.querySelectorAll('.tab-content');
    for (var j = 0; j < contents.length; j++) {
        contents[j].classList.remove('active');
    }
    
    // Add active to clicked tab
    var clickedTab = document.querySelector('.tab-btn[data-tab="' + tabId + '"]');
    if (clickedTab) {
        clickedTab.classList.add('active');
    }
    
    // Add active to corresponding content
    var tabContent = document.getElementById('tab-' + tabId);
    if (tabContent) {
        tabContent.classList.add('active');
    }
}

// Gallery filter function
function filterGallery(filter, btn) {
    // Update active state
    var galleryTabs = document.querySelectorAll('.gallery-tab.link');
    for (var i = 0; i < galleryTabs.length; i++) {
        galleryTabs[i].classList.remove('active');
    }
    btn.classList.add('active');
    
    var items = document.querySelectorAll('.gallery-item.media');
    for (var j = 0; j < items.length; j++) {
        if (filter === 'ALL') {
            items[j].classList.remove('hidden');
        } else {
            if (items[j].classList.contains(filter)) {
                items[j].classList.remove('hidden');
            } else {
                items[j].classList.add('hidden');
            }
        }
    }
}
</script>

<!-- TABS CONTAINER -->
<div class="tabs-container">
    <div class="tabs-nav" id="devisTabs">
        <button type="button" class="tab-btn active" data-tab="documents" onclick="switchTab('documents')">
            <i class="uil uil-images"></i> Documents
            <span class="tab-badge">{{ $dossier->document ? count($dossier->document) : 0 }}</span>
        </button>
        @if ($devis->devis_status_id == 4 || $devis->devis_status_id == 5 || $devis->devis_status_id == 8 || 
            (Auth::user()->role_id == 4 && in_array($devis->devis_status_id, [2, 3, 7])))
        <button type="button" class="tab-btn" data-tab="editor" onclick="switchTab('editor')">
            <i class="uil uil-edit"></i> Éditeur
        </button>
        @endif
        <button type="button" class="tab-btn" data-tab="pieces" onclick="switchTab('pieces')">
            <i class="uil uil-list-ul"></i> Pièces
            <span class="tab-badge">{{ count($devis->piece) }}</span>
        </button>
        <button type="button" class="tab-btn" data-tab="observations" onclick="switchTab('observations')">
            <i class="uil uil-comments-alt"></i> Observations
            <span class="tab-badge">{{ $observations ? count($observations) : 0 }}</span>
        </button>
    </div>

    <!-- TAB 1: Documents -->
    <div class="tab-content active" id="tab-documents">
        <div class="row" id="galley">
            <!-- Devis Documents -->
            <div class="col-lg-6 mb-3">
                <div class="gallery-section">
                    <div class="gallery-header">
                        <h5><i class="uil uil-file-alt"></i> Documents Devis</h5>
                    </div>
                    @if ($docdevis && count($docdevis) > 0)
                        <div class="gallery-grid">
                            @foreach ($docdevis as $doc)
                                <div class="gallery-item">
                                    <img src="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) ?? null }}"
                                         data-original="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) ?? null }}"
                                         alt="Document">
                                    @if ($doc->devis[0]->id == $devis->id)
                                        <div class="item-overlay">
                                            <a href="{{ route('Devis.show', ['id' => $devis->id, 'doc_id' => $doc->id]) }}" title="Éditer">
                                                <i class="uil uil-edit"></i>
                                            </a>
                                        </div>
                                    @endif
                                    <span class="item-badge info">{{ $doc->typedocument->type ?? null }}</span>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <p class="text-muted text-center py-3">Aucun document devis</p>
                    @endif
                </div>
            </div>

            <!-- All Documents -->
            <div class="col-lg-6 mb-3">
                <div class="gallery-section">
                    <div class="gallery-header">
                        <h5><i class="uil uil-folder-open"></i> Documents Dossier</h5>
                        <div class="gallery-tabs">
                            <button type="button" data-filter="ALL" class="gallery-tab link active" onclick="filterGallery('ALL', this)">Tous</button>
                            @foreach ($typedocuments as $type)
                                <button type="button" data-filter="{{ $type->type }}" class="gallery-tab link" onclick="filterGallery('{{ $type->type }}', this)">{{ $type->type }}</button>
                            @endforeach
                        </div>
                    </div>
                    <input type="hidden" id="id" name="dossier_id" value="{{ $dossier->id }}">
                    @if ($dossier->document && count($dossier->document) > 0)
                        <div class="gallery-grid" id="row">
                            @foreach ($dossier->document as $doc)
                                @if ($doc->type_document_id != 10)
                                    <div class="gallery-item media {{ $doc->typedocument->type ?? null }}">
                                        @php
                                            $cacheKey = 'document_' . $doc->id;
                                            $imageUrl = Cache::remember($cacheKey, 30, function () use ($doc) {
                                                return Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30));
                                            });
                                        @endphp
                                        <img data-original="{{ $imageUrl }}" src="{{ $imageUrl }}" alt="Document">
                                        <div class="item-overlay">
                                            <a href="{{ route('Document.edit', $doc->id) }}" title="Éditer">
                                                <i class="uil uil-edit"></i>
                                            </a>
                                        </div>
                                        <span class="item-badge {{ $doc->edited ? 'success' : 'primary' }}">{{ $doc->typedocument->type ?? null }}</span>
                                    </div>
                                @endif
                            @endforeach
                        </div>
                    @else
                        <p class="text-muted text-center py-3">Aucun document</p>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- TAB 2: Editor -->
    @if ($devis->devis_status_id == 4 || $devis->devis_status_id == 5)
        @can('chiffrage', App\Models\Devis::class)
        <div class="tab-content" id="tab-editor">
            @include('devis.editor_devis2')
        </div>
        @endcan
    @elseif ($devis->devis_status_id == 8)
        @can('controler', App\Models\Devis::class)
        <div class="tab-content" id="tab-editor">
            @include('devis.editor_devis2')
        </div>
        @endcan
    @elseif (Auth::user()->role_id == 4 && in_array($devis->devis_status_id, [2, 3, 7]))
        <div class="tab-content" id="tab-editor">
            @include('devis.editor_devis2')
        </div>
    @endif

    <!-- TAB 3: Pieces -->
    <div class="tab-content" id="tab-pieces">
        @if ($devis->devis_status_id == 4 || $devis->devis_status_id == 5)
            @can('chiffrage', App\Models\Devis::class)
                @include('devis.piece')
            @endcan
        @elseif ($devis->devis_status_id == 8)
            @can('controler', App\Models\Devis::class)
                @include('devis.piece')
            @endcan
        @elseif (Auth::user()->role_id == 4 && in_array($devis->devis_status_id, [2, 3, 7]))
            @include('devis.piece')
        @endif

        @include('devis.valeurs')
        
        <input type="hidden" value="{{ $devis->id }}" name="devis_id">
        
        <div class="table-header">
            <h5><i class="uil uil-list-ul"></i> Liste des Pièces</h5>
            <div class="table-actions">
                @if ($dossier->dossier_status_id != 3)
                    @if (in_array($devis->devis_status_id, [4, 5]))
                        @can('chiffrage', App\Models\Devis::class)
                            <a class="action-btn success savedevis"><i class="uil uil-save"></i> Enregistrer</a>
                        @endcan
                    @elseif ($devis->devis_status_id == 8)
                        @can('controler', App\Models\Devis::class)
                            <a class="action-btn success savedevis"><i class="uil uil-save"></i> Enregistrer</a>
                        @endcan
                    @elseif (Auth::user()->role_id == 4 && in_array($devis->devis_status_id, [2, 3, 7]))
                        <a class="action-btn success savedevis"><i class="uil uil-save"></i> Enregistrer</a>
                    @endif
                @endif
                <button type="button" class="action-btn info" data-bs-toggle="modal" data-bs-target="#full-width-modal2">
                    <i class="uil uil-setting"></i> Valeurs
                </button>
                @if (in_array($devis->devis_status_id, [4, 5, 8]) || (Auth::user()->role_id == 4 && in_array($devis->devis_status_id, [2, 3, 7])))
                    <button type="button" class="action-btn info" data-bs-toggle="modal" data-bs-target="#full-width-modal">
                        <i class="uil uil-percentage"></i> Taux
                    </button>
                @endif
            </div>
        </div>

        <div class="table-responsive">
            <table class="modern-table">
                <thead>
                    <tr>
                        <th>Catégorie</th>
                        <th>Pièce</th>
                        <th>Opération</th>
                        <th>Réparation</th>
                        <th>Prix U.</th>
                        <th>Qté</th>
                        <th>Gravité</th>
                        <th>État</th>
                        <th>Vét. %</th>
                        <th>Rem. %</th>
                        <th><i class="uil uil-check"></i></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($devis->piece as $piece)
                        <tr>
                            <td>
                                @if (Auth::user()->role_id != 4 && in_array($devis->devis_status_id, [1, 2, 6, 7]))
                                    <input type="text" readonly class="form-control" value="{{ $piece->piecetype->type ?? null }}">
                                @else
                                    <select class="form-select" name="op" onchange="list({{ $piece->id }},this.value)" id="pt{{ $piece->id }}">
                                        <option value="{{ $piece->piecetype->id }}">{{ $piece->piecetype->type }}</option>
                                        @foreach ($piecetypes as $piecetype)
                                            @if ($piecetype->id != $piece->piecetype->id)
                                                <option value="{{ $piecetype->id }}">{{ $piecetype->type }}</option>
                                            @endif
                                        @endforeach
                                    </select>
                                @endif
                            </td>
                            <td>
                                @if (Auth::user()->role_id != 4 && in_array($devis->devis_status_id, [1, 2, 6, 7]))
                                    <input type="text" readonly class="form-control" value="{{ $piece->piece ?? null }}">
                                @else
                                    <select class="form-select" name="op" id="pc{{ $piece->id }}">
                                        <option selected value="{{ $piece->id }}">{{ $piece->piece }}</option>
                                    </select>
                                @endif
                            </td>
                            <td>
                                @if (Auth::user()->role_id != 4 && in_array($devis->devis_status_id, [1, 2, 6, 7]))
                                    <input type="text" readonly class="form-control" value="{{ $piece->pivot->operation->operation ?? null }}">
                                @else
                                    <select class="form-select" name="op" id="o{{ $piece->id }}">
                                        <option selected value="{{ $piece->pivot->operation->id ?? '' }}">{{ $piece->pivot->operation->operation ?? '' }}</option>
                                        @foreach ($operations as $operation)
                                            @if (isset($piece->pivot->operation->id) && $operation->id != $piece->pivot->operation->id)
                                                <option value="{{ $operation->id }}">{{ $operation->operation }}</option>
                                            @endif
                                        @endforeach
                                    </select>
                                @endif
                            </td>
                            <td>
                                @if (Auth::user()->role_id != 4 && in_array($devis->devis_status_id, [1, 2, 6, 7]))
                                    <input type="text" readonly class="form-control" value="{{ $piece->pivot->typereparation->type ?? null }}">
                                @else
                                    <select class="form-select" name="type" id="t{{ $piece->id }}">
                                        <option selected value="{{ $piece->pivot->typereparation->id ?? '' }}">{{ $piece->pivot->typereparation->type ?? '' }}</option>
                                        @foreach ($types as $type)
                                            @if (isset($piece->pivot->typereparation->id) && $type->id != $piece->pivot->typereparation->id)
                                                <option value="{{ $type->id }}">{{ $type->type }}</option>
                                            @endif
                                        @endforeach
                                    </select>
                                @endif
                            </td>
                            <td>
                                <input type="number" id="p{{ $piece->id }}" min="0"
                                    @if (Auth::user()->role_id != 4 && in_array($devis->devis_status_id, [1, 2, 6, 7])) readonly @endif
                                    name="prix_unitaire" class="form-control" value="{{ $piece->pivot->prix_unitaire }}">
                            </td>
                            <td>
                                <input type="number" id="id{{ $piece->id }}" min="0" name="qte" class="form-control"
                                    value="{{ $piece->pivot->qte ?? 1 }}">
                            </td>
                            <td>
                                <input type="number" id="g{{ $piece->id }}" min="0" name="gravite" class="form-control"
                                    value="{{ $piece->pivot->gravite ?? 0 }}">
                            </td>
                            <td>
                                <input type="text" id="e{{ $piece->id }}" name="etat" class="form-control"
                                    value="{{ $piece->pivot->etat ?? '' }}">
                            </td>
                            <td>
                                <input type="number" id="v{{ $piece->id }}" min="0" name="vetuste" class="form-control" value="0">
                            </td>
                            <td>
                                <input type="number" id="r{{ $piece->id }}" name="remise" class="form-control" value="0">
                            </td>
                            <td>
                                <input class="form-check-input check" type="checkbox" name="piece" value="{{ $piece->id }}">
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        @if (in_array($devis->devis_status_id, [4, 5]))
            @can('chiffrage', App\Models\Devis::class)
                @include('devis.taux')
            @endcan
        @elseif ($devis->devis_status_id == 8)
            @can('controler', App\Models\Devis::class)
                @include('devis.taux')
            @endcan
        @elseif (Auth::user()->role_id == 4 && in_array($devis->devis_status_id, [2, 3, 7]))
            @include('devis.taux')
        @endif
    </div>

    <!-- TAB 4: Observations -->
    <div class="tab-content" id="tab-observations">
        <div class="row">
            <div class="col-lg-8">
                <h5 style="margin-bottom: 15px; font-size: 14px; font-weight: 700; color: #1e293b;">
                    <i class="uil uil-history" style="color: #10b981;"></i> Historique
                </h5>
                <div class="observation-list">
                    @if ($observations && count($observations) > 0)
                        @foreach ($observations as $observation)
                            <div class="observation-item">
                                <div class="obs-header">
                                    <span class="obs-user">
                                        <i class="uil uil-user"></i> {{ $observation->user->name ?? 'Utilisateur' }}
                                    </span>
                                    <span class="obs-date">{{ $observation->created_at->format('d/m/Y H:i') }}</span>
                                </div>
                                <div class="obs-content">{{ $observation->observation }}</div>
                            </div>
                        @endforeach
                    @else
                        <p class="text-muted text-center py-4">Aucune observation</p>
                    @endif
                </div>
            </div>
            <div class="col-lg-4">
                @can('update', App\Models\Devis::class)
                    <h5 style="margin-bottom: 15px; font-size: 14px; font-weight: 700; color: #1e293b;">
                        <i class="uil uil-plus-circle" style="color: #10b981;"></i> Nouvelle
                    </h5>
                    <form method="POST" action="{{ route('Observation.store') }}" class="observation-form">
                        @csrf
                        <input type="hidden" name="dossier_id" value="{{ $dossier->id }}">
                        <textarea name="observation" class="form-control @error('observation') is-invalid @enderror mb-2"
                            placeholder="Écrire une observation..." rows="4"></textarea>
                        @error('observation')
                            <span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>
                        @enderror
                        <button type="submit" class="action-btn success" style="width: 100%;">
                            <i class="uil uil-plus"></i> Ajouter
                        </button>
                    </form>
                @endcan
            </div>
        </div>
    </div>
</div>

@endsection

@section('script')
{{-- Tab functions are defined inline above the tabs --}}
@endsection