<!doctype html>
<html lang="fa" dir="rtl">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link href="{{ asset('static/patients/css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet" type='text/css'>
    <link href="{{ asset('static/my_auth/font.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="{{ asset('static/patients/css/spur.css') }}">

    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.bootstrap4.min.css">

    <title>پنل مدیریت - لیست بیماران</title>

    <style>
        .stats-card {
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            color: white;
            text-align: center;
            transition: transform 0.3s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
        }
        
        .stats-card.total {
            background: linear-gradient(135deg, #0d6efd 0%, #6610f2 100%);
        }
        
        .stats-card.male {
            background: linear-gradient(135deg, #20c997 0%, #198754 100%);
        }
        
        .stats-card.female {
            background: linear-gradient(135deg, #fd7e14 0%, #dc3545 100%);
        }
        
        .stats-card.avg-age {
            background: linear-gradient(135deg, #6f42c1 0%, #0dcaf0 100%);
        }
        
        .stats-icon {
            font-size: 2.5rem;
            margin-bottom: 10px;
            opacity: 0.9;
        }
        
        .stats-number {
            font-size: 1.8rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .stats-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .search-box {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border: 2px solid #e9ecef;
        }
        
        .patient-row {
            transition: all 0.3s ease;
            border-right: 3px solid transparent;
        }
        
        .patient-row:hover {
            background-color: #f8f9fa;
            border-right-color: #0d6efd;
            transform: translateX(-5px);
        }
        
        .patient-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 10px;
        }
        
        .patient-avatar.male {
            background-color: #e7f5ff;
            color: #0d6efd;
        }
        
        .patient-avatar.female {
            background-color: #fff0f6;
            color: #e64980;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }
        
        .action-btn {
            min-width: 80px;
            font-size: 0.85rem;
        }
        
        .filter-badge {
            background-color: #e7f5ff;
            color: #0d6efd;
            border: 1px solid #b6d4fe;
            border-radius: 20px;
            padding: 5px 15px;
            margin-left: 5px;
            display: inline-flex;
            align-items: center;
            cursor: pointer;
        }
        
        .filter-badge:hover {
            background-color: #d0ebff;
        }
        
        .filter-badge .close {
            margin-right: 5px;
            font-size: 1rem;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        
        .empty-state-icon {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.3;
        }
        
        .export-options {
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            position: absolute;
            z-index: 1000;
            display: none;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .export-options.show {
            display: block;
        }
        
        .pagination-custom .page-link {
            border-radius: 5px;
            margin: 0 3px;
            border: 1px solid #dee2e6;
        }
        
        .pagination-custom .page-item.active .page-link {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        
        .table-header-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .bulk-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        .bulk-checkbox {
            transform: scale(1.2);
        }
        
        @media (max-width: 768px) {
            .stats-card {
                margin-bottom: 15px;
            }
            
            .table-header-actions {
                flex-direction: column;
                align-items: stretch;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .action-btn {
                width: 100%;
                margin-bottom: 5px;
            }
        }
        
        .highlight {
            background-color: #fff3cd !important;
        }
        
        .diagnosis-count {
            display: inline-block;
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 2px 8px;
            font-size: 0.8rem;
            color: #6c757d;
            margin-top: 3px;
        }
        
        .patient-status {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-left: 5px;
        }
        
        .status-active {
            background-color: #198754;
        }
        
        .status-inactive {
            background-color: #dc3545;
        }
        
        .quick-filters {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        
        .quick-filter-btn {
            border-radius: 20px;
            padding: 5px 15px;
            font-size: 0.85rem;
        }
    </style>
</head>

<body dir="rtl">
<div class="dash">
    <div class="dash-nav dash-nav-dark" style="right: 0">
        <header>
            <a href="#!" class="menu-toggle">
                <i class="fa fa-bars"></i>
            </a>
            <a href="{{ route('patients.index') }}" class="spur-logo">
                <span>پنل مدیریت</span>
            </a>
        </header>
        <nav class="dash-nav-list">
            <a href="{{ route('patients.index') }}" class="dash-nav-item active">
                <i class="fa fa-list ml-2"></i>
                مدیریت بیماران
            </a>
            <a href="{{ route('diagnose.clinical') }}" class="dash-nav-item">
                <i class="fa fa-file-text ml-2"></i>
                تشخیص با داده های بالینی
            </a>
            <a href="{{ route('diagnose.scan') }}" class="dash-nav-item">
                <i class="fa fa-camera ml-2"></i>
                تشخیص با تصویر
            </a>
            <a href="{{ route('diagnose.result') }}" class="dash-nav-item">
                <i class="fa fa-chart-bar ml-2"></i>
                نتایج تشخیص
            </a>
        </nav>
    </div>
    <div class="dash-app">
        <header class="dash-toolbar d-flex justify-content-around">
            <a href="#!" class="menu-toggle">
                <i class="fa fa-bars"></i>
            </a>
            <span>پنل مدیریت - لیست بیماران</span>

            <div class="tools">
                <div class="dropdown tools-item">
                    <a href="#" class="" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <i class="fa fa-user"></i>
                    </a>
                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenu1">
                        <a class="dropdown-item" href="{{ route('logout') }}"
                           onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                            خروج
                        </a>
                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                            @csrf
                        </form>
                    </div>
                </div>
            </div>
        </header>
        <main class="dash-content">
            <div class="container-fluid">
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6">
                        <div class="stats-card total">
                            <div class="stats-icon">
                                <i class="fa fa-users"></i>
                            </div>
                            <div class="stats-number" id="totalPatients">{{ $patients->total() }}</div>
                            <div class="stats-label">کل بیماران</div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stats-card male">
                            <div class="stats-icon">
                                <i class="fa fa-male"></i>
                            </div>
                            <div class="stats-number" id="malePatients">{{ $maleCount ?? 0 }}</div>
                            <div class="stats-label">بیماران مرد</div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stats-card female">
                            <div class="stats-icon">
                                <i class="fa fa-female"></i>
                            </div>
                            <div class="stats-number" id="femalePatients">{{ $femaleCount ?? 0 }}</div>
                            <div class="stats-label">بیماران زن</div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stats-card avg-age">
                            <div class="stats-icon">
                                <i class="fa fa-chart-line"></i>
                            </div>
                            <div class="stats-number" id="avgAge">{{ $averageAge ?? 0 }}</div>
                            <div class="stats-label">میانگین سن</div>
                        </div>
                    </div>
                </div>

                <!-- Search and Filters -->
               
                
                <!-- Quick Filters -->
                {{-- <div class="quick-filters">
                    <button class="btn btn-sm btn-outline-primary quick-filter-btn" data-filter="new">
                        <i class="fa fa-star"></i> جدیدترین
                    </button>
                    <button class="btn btn-sm btn-outline-primary quick-filter-btn" data-filter="old">
                        <i class="fa fa-history"></i> قدیمی‌ترین
                    </button>
                    <button class="btn btn-sm btn-outline-primary quick-filter-btn" data-filter="young">
                        <i class="fa fa-child"></i> جوان‌ترین
                    </button>
                    <button class="btn btn-sm btn-outline-primary quick-filter-btn" data-filter="oldest">
                        <i class="fa fa-user-md"></i> مسن‌ترین
                    </button>
                    <button class="btn btn-sm btn-outline-danger quick-filter-btn" data-filter="high-risk">
                        <i class="fa fa-exclamation-triangle"></i> ریسک بالا
                    </button>
                </div> --}}

                <!-- Table Header Actions -->
                <div class="table-header-actions">
                    <div>
                        <h4 class="mb-0">لیست بیماران</h4>
                        <p class="text-muted mb-0">
                            نمایش {{ $patients->firstItem() ?? 0 }} تا {{ $patients->lastItem() ?? 0 }} از {{ $patients->total() }} بیمار
                        </p>
                    </div>
                    
                    <div class="d-flex align-items-center">
                        <div class="bulk-actions" style="display: none;" id="bulkActions">
                            <div class="form-check mr-3">
                                <input class="form-check-input bulk-checkbox" type="checkbox" id="selectAll">
                                <label class="form-check-label" for="selectAll">
                                    انتخاب همه
                                </label>
                            </div>
                            <button class="btn btn-sm btn-outline-danger" id="bulkDelete">
                                <i class="fa fa-trash"></i> حذف انتخاب‌شده‌ها
                            </button>
                            <button class="btn btn-sm btn-outline-secondary" id="bulkExport">
                                <i class="fa fa-download"></i> خروجی انتخاب‌شده‌ها
                            </button>
                        </div>
                        
                        <a href="{{ route('patients.create') }}" class="btn btn-primary">
                            <i class="fa fa-plus"></i> افزودن بیمار جدید
                        </a>
                    </div>
                </div>

                <!-- Patients Table -->
                <div class="card spur-card">
                    <div class="card-body">
                        @if($patients->count() > 0)
                            <div class="table-responsive">
                                <table class="table table-hover" id="patientsTable">
                                    <thead>
                                        <tr>
                                            <th width="50">
                                                <input type="checkbox" class="bulk-select" id="selectAllRows">
                                            </th>
                                            <th>نام و نام خانوادگی</th>
                                            <th>کد ملی</th>
                                            <th>جنسیت</th>
                                            <th>سن</th>
                                            <th>تلفن</th>
                                            <th>آخرین تشخیص</th>
                                            <th>عملیات ویرایش و حذف</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($patients as $patient)
                                            <tr class="patient-row" data-id="{{ $patient->id }}">
                                                <td>
                                                    <input type="checkbox" class="patient-checkbox bulk-select" 
                                                           value="{{ $patient->id }}">
                                                </td>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <div class="patient-avatar {{ $patient->sex == 'مرد' ? 'male' : 'female' }}">
                                                            <i class="fa fa-{{ $patient->sex == 'مرد' ? 'male' : 'female' }}"></i>
                                                        </div>
                                                        <div>
                                                            <strong>{{ $patient->first_name }} {{ $patient->last_name }}</strong>
                                                            <div class="diagnosis-count">
                                                                <i class="fa fa-stethoscope"></i>
                                                                {{ $patient->diagnoses_count ?? 0 }} تشخیص
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <code>{{ $patient->national_code }}</code>
                                                </td>
                                                <td>
                                                    {{ $patient->sex }}
                                                    <span class="patient-status status-active"></span>
                                                </td>
                                                <td>
                                                    <span class="badge badge-info">{{ $patient->age }}</span> سال
                                                </td>
                                                <td>
                                                    <a href="tel:{{ $patient->phone_number }}" class="text-decoration-none">
                                                        <i class="fa fa-phone"></i>
                                                        {{ $patient->phone_number }}
                                                    </a>
                                                </td>
                                                <td>
                                                    @if($patient->latest_diagnosis)
                                                        <span class="badge {{ $patient->latest_diagnosis->result == 'positive' ? 'badge-danger' : 'badge-success' }}">
                                                            {{ $patient->latest_diagnosis->result == 'positive' ? 'مثبت' : 'منفی' }}
                                                        </span>
                                                        <small class="text-muted">
                                                            {{ verta($patient->latest_diagnosis->created_at)->format('Y/m/d') }}
                                                        </small>
                                                    @else
                                                        <span class="text-muted">بدون سابقه</span>
                                                    @endif
                                                </td>
                                                <td>
                                                    <div class="action-buttons">
                                                        <a href="{{ route('patients.show', $patient->id) }}" 
                                                           class="btn btn-sm btn-info action-btn" 
                                                           title="مشاهده">
                                                            <i class="fa fa-eye"></i>
                                                        </a>
                                                        {{-- <a href="{{ route('patients.edit', $patient->id) }}" 
                                                           class="btn btn-sm btn-warning action-btn" 
                                                           title="ویرایش">
                                                            <i class="fa fa-edit"></i>
                                                        </a> --}}
                                                        <a href="{{ route('diagnose.clinical') }}?patient_id={{ $patient->id }}" 
                                                           class="btn btn-sm btn-success action-btn" 
                                                           title="تشخیص با داده های بالینی">
                                                            <i class="fa fa-stethoscope"></i>
                                                        </a>
                                                        <form action="{{ route('patients.destroy', $patient->id) }}" 
                                                              method="POST" class="d-inline delete-form">
                                                            @csrf
                                                            @method('DELETE')
                                                            <button type="button" 
                                                                    class="btn btn-sm btn-danger action-btn delete-btn" 
                                                                    title="حذف"
                                                                    data-name="{{ $patient->first_name }} {{ $patient->last_name }}">
                                                                <i class="fa fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    </div>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Pagination -->
                            <div class="d-flex justify-content-between align-items-center mt-4">
                                <div>
                                    <select class="form-control form-control-sm d-inline-block w-auto" id="perPage">
                                        <option value="10" {{ request('per_page', 20) == 10 ? 'selected' : '' }}>10</option>
                                        <option value="20" {{ request('per_page', 20) == 20 ? 'selected' : '' }}>20</option>
                                        <option value="50" {{ request('per_page', 20) == 50 ? 'selected' : '' }}>50</option>
                                        <option value="100" {{ request('per_page', 20) == 100 ? 'selected' : '' }}>100</option>
                                    </select>
                                    <span class="text-muted">رکورد در هر صفحه</span>
                                </div>
                                
                                <nav aria-label="Page navigation">
                                    {{ $patients->appends(request()->query())->links() }}
                                </nav>
                            </div>
                        @else
                            <!-- Empty State -->
                            <div class="empty-state">
                                <div class="empty-state-icon">
                                    <i class="fa fa-users"></i>
                                </div>
                                <h4>بیماری یافت نشد</h4>
                                <p class="text-muted mb-4">هنوز هیچ بیماری در سیستم ثبت نشده است.</p>
                                <a href="{{ route('patients.create') }}" class="btn btn-primary btn-lg">
                                    <i class="fa fa-plus"></i> افزودن اولین بیمار
                                </a>
                            </div>
                        @endif
                    </div>
                </div>

                <!-- Flash Messages -->
                @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
                        <i class="fa fa-check-circle mr-2"></i>
                        {{ session('success') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                @endif

                @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert">
                        <i class="fa fa-exclamation-circle mr-2"></i>
                        {{ session('error') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                @endif
            </div>
        </main>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">حذف بیمار</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                آیا مطمئن هستید که می‌خواهید بیمار "<span id="patientName"></span>" را حذف کنید؟
                <div class="alert alert-warning mt-3">
                    <i class="fa fa-exclamation-triangle"></i>
                    این عمل غیرقابل بازگشت است و تمام اطلاعات مرتبط با این بیمار نیز حذف خواهند شد.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">انصراف</button>
                <form id="deleteFormModal" method="POST" style="display: inline;">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">حذف بیمار</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Delete Modal -->
<div class="modal fade" id="bulkDeleteModal" tabindex="-1" role="dialog" aria-labelledby="bulkDeleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bulkDeleteModalLabel">حذف گروهی بیماران</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                آیا مطمئن هستید که می‌خواهید <span id="selectedCount">0</span> بیمار انتخاب‌شده را حذف کنید؟
                <div class="alert alert-danger mt-3">
                    <i class="fa fa-exclamation-triangle"></i>
                    این عمل غیرقابل بازگشت است و تمام اطلاعات مرتبط با این بیماران نیز حذف خواهند شد.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">انصراف</button>
                <button type="button" class="btn btn-danger" id="confirmBulkDelete">حذف انتخاب‌شده‌ها</button>
            </div>
        </div>
    </div>
</div>

<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.4.1/js/responsive.bootstrap4.min.js"></script>

<!-- Export Libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>

<script>
    // Initialize DataTable
    $(document).ready(function() {
        // Initialize DataTable if needed
        // $('#patientsTable').DataTable({
        //     "language": {
        //         "url": "//cdn.datatables.net/plug-ins/1.13.4/i18n/fa.json"
        //     },
        //     "responsive": true,
        //     "order": [[1, 'asc']]
        // });
    });
    
    // Search functionality
    document.getElementById('searchButton').addEventListener('click', function() {
        const searchValue = document.getElementById('searchInput').value;
        if (searchValue) {
            const url = new URL(window.location.href);
            url.searchParams.set('search', searchValue);
            window.location.href = url.toString();
        }
    });
    
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('searchButton').click();
        }
    });
    
    document.getElementById('clearSearch').addEventListener('click', function() {
        const url = new URL(window.location.href);
        url.searchParams.delete('search');
        window.location.href = url.toString();
    });
    
    // Filter functionality
    document.querySelectorAll('.filter-gender').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const gender = this.dataset.gender;
            if (gender === 'all') {
                const url = new URL(window.location.href);
                url.searchParams.delete('gender');
                window.location.href = url.toString();
            } else {
                const url = new URL(window.location.href);
                url.searchParams.set('gender', gender);
                window.location.href = url.toString();
            }
        });
    });
    
    // Quick filters
    document.querySelectorAll('.quick-filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const filter = this.dataset.filter;
            let url = new URL(window.location.href);
            
            switch(filter) {
                case 'new':
                    url.searchParams.set('sort', 'created_at');
                    url.searchParams.set('order', 'desc');
                    break;
                case 'old':
                    url.searchParams.set('sort', 'created_at');
                    url.searchParams.set('order', 'asc');
                    break;
                case 'young':
                    url.searchParams.set('sort', 'age');
                    url.searchParams.set('order', 'asc');
                    break;
                case 'oldest':
                    url.searchParams.set('sort', 'age');
                    url.searchParams.set('order', 'desc');
                    break;
            }
            
            window.location.href = url.toString();
        });
    });
    
    // Per page selector
    document.getElementById('perPage').addEventListener('change', function() {
        const perPage = this.value;
        const url = new URL(window.location.href);
        url.searchParams.set('per_page', perPage);
        window.location.href = url.toString();
    });
    
    // Delete confirmation
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const patientName = this.dataset.name;
            const form = this.closest('.delete-form');
            
            document.getElementById('patientName').textContent = patientName;
            document.getElementById('deleteFormModal').action = form.action;
            
            $('#deleteModal').modal('show');
        });
    });
    
    // Bulk selection
    document.getElementById('selectAllRows').addEventListener('change', function() {
        const isChecked = this.checked;
        document.querySelectorAll('.patient-checkbox').forEach(checkbox => {
            checkbox.checked = isChecked;
        });
        toggleBulkActions();
    });
    
    document.querySelectorAll('.patient-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', toggleBulkActions);
    });
    
    function toggleBulkActions() {
        const checkedBoxes = document.querySelectorAll('.patient-checkbox:checked');
        const bulkActions = document.getElementById('bulkActions');
        
        if (checkedBoxes.length > 0) {
            bulkActions.style.display = 'flex';
        } else {
            bulkActions.style.display = 'none';
        }
        
        // Update select all checkbox
        const allCheckboxes = document.querySelectorAll('.patient-checkbox');
        const selectAll = document.getElementById('selectAllRows');
        selectAll.checked = allCheckboxes.length === checkedBoxes.length;
    }
    
    // Bulk delete
    document.getElementById('bulkDelete').addEventListener('click', function() {
        const checkedBoxes = document.querySelectorAll('.patient-checkbox:checked');
        document.getElementById('selectedCount').textContent = checkedBoxes.length;
        $('#bulkDeleteModal').modal('show');
    });
    
    document.getElementById('confirmBulkDelete').addEventListener('click', function() {
        const checkedBoxes = document.querySelectorAll('.patient-checkbox:checked');
        const patientIds = Array.from(checkedBoxes).map(cb => cb.value);
        
        
        
    });
    
    // Export functionality
    document.querySelectorAll('.export-option').forEach(option => {
        option.addEventListener('click', function(e) {
            e.preventDefault();
            const type = this.dataset.type;
            
            switch(type) {
                case 'excel':
                    exportToExcel();
                    break;
                case 'pdf':
                    exportToPDF();
                    break;
                case 'print':
                    window.print();
                    break;
            }
        });
    });
    
    function exportToExcel() {
        // Simple table export to CSV
        const table = document.getElementById('patientsTable');
        const rows = table.querySelectorAll('tr');
        let csv = [];
        
        rows.forEach(row => {
            const rowData = [];
            const cols = row.querySelectorAll('td, th');
            cols.forEach(col => {
                // Skip action columns and checkboxes
                if (!col.classList.contains('no-export')) {
                    rowData.push(col.innerText.trim());
                }
            });
            csv.push(rowData.join(','));
        });
        
        const csvString = csv.join('\n');
        const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `patients-${new Date().toISOString().split('T')[0]}.csv`;
        link.click();
    }
    
    function exportToPDF() {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();
        
        doc.text('لیست بیماران', 105, 15, { align: 'center' });
        
        // Simple table export (you can enhance this with jsPDF AutoTable)
        doc.save(`patients-${new Date().toISOString().split('T')[0]}.pdf`);
    }
    
    // Highlight search terms
    function highlightSearchTerms() {
        const searchParams = new URLSearchParams(window.location.search);
        const searchTerm = searchParams.get('search');
        
        if (searchTerm) {
            const regex = new RegExp(`(${searchTerm})`, 'gi');
            const cells = document.querySelectorAll('#patientsTable td');
            
            cells.forEach(cell => {
                const html = cell.innerHTML;
                const highlighted = html.replace(regex, '<mark>$1</mark>');
                if (highlighted !== html) {
                    cell.innerHTML = highlighted;
                    cell.closest('tr').classList.add('highlight');
                }
            });
        }
    }
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        highlightSearchTerms();
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+F to focus search
            if (e.ctrlKey && e.key === 'f') {
                e.preventDefault();
                document.getElementById('searchInput').focus();
            }
            
            // Ctrl+N to add new patient
            if (e.ctrlKey && e.key === 'n') {
                e.preventDefault();
                window.location.href = '{{ route("patients.create") }}';
            }
            
            // Esc to clear search
            if (e.key === 'Escape') {
                document.getElementById('searchInput').value = '';
            }
        });
        
        // Update active filters display
        const urlParams = new URLSearchParams(window.location.search);
        const activeFilters = [];
        
        if (urlParams.get('gender')) {
            activeFilters.push({
                name: 'جنسیت',
                value: urlParams.get('gender'),
                param: 'gender'
            });
        }
        
        if (urlParams.get('search')) {
            activeFilters.push({
                name: 'جستجو',
                value: urlParams.get('search'),
                param: 'search'
            });
        }
        
        if (activeFilters.length > 0) {
            const filterBadges = document.getElementById('filterBadges');
            filterBadges.innerHTML = '';
            
            activeFilters.forEach(filter => {
                const badge = document.createElement('span');
                badge.className = 'filter-badge';
                badge.innerHTML = `
                    ${filter.name}: ${filter.value}
                    <span class="close" data-param="${filter.param}">&times;</span>
                `;
                filterBadges.appendChild(badge);
            });
            
            document.getElementById('activeFilters').style.display = 'block';
            
            // Add remove filter functionality
            document.querySelectorAll('.filter-badge .close').forEach(closeBtn => {
                closeBtn.addEventListener('click', function() {
                    const param = this.dataset.param;
                    const url = new URL(window.location.href);
                    url.searchParams.delete(param);
                    window.location.href = url.toString();
                });
            });
        }
    });
</script>

<script src="{{ asset('static/my_auth/jquery.min.js') }}"></script>
<script src="{{ asset('static/my_auth/popper.js') }}"></script>
<script src="{{ asset('static/my_auth/bootstrap.min.js') }}"></script>
<script src="{{ asset('static/patients/js/spur.js') }}"></script>

</body>
</html>