<?php

use App\Http\Controllers\Admin\AdminUserController;
use App\Http\Controllers\Admin\AdvertisementController as AdminAdvertisementController;
use App\Http\Controllers\Admin\AmenityController;
use App\Http\Controllers\Admin\AnalyticsController;
use App\Http\Controllers\Admin\CategoryController;
use App\Http\Controllers\Admin\CategoryTemplateController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\DisplaySettingController;
use App\Http\Controllers\Admin\GeographyController;
use App\Http\Controllers\Admin\LanguageController;
use App\Http\Controllers\Admin\LocationController as AdminLocationController;
use App\Http\Controllers\Admin\RatingController;
use App\Http\Controllers\Admin\SecuritySettingController;
use App\Http\Controllers\Admin\TranslationController;
use App\Http\Controllers\ApiController;
use App\Http\Controllers\Auth\AdminAuthController;
use App\Http\Controllers\Auth\UserAuthController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ReviewController;
use App\Http\Controllers\User\DashboardController as UserDashboardController;
use App\Http\Controllers\User\LocationSubmissionController;
use App\Http\Controllers\User\RatingController as UserRatingController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LocationController; // اطمینان از وجود ایمپورت
use Illuminate\Support\Facades\Schema;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use App\Http\Controllers\Admin\SiteSettingController;
use App\Http\Controllers\Admin\TemplateController;
use App\Http\Controllers\Admin\MessageController;
use App\Http\Controllers\Admin\NotificationController;
use App\Http\Controllers\Admin\StatisticsController;
use App\Http\Controllers\Admin\BackupController;
use App\Http\Controllers\Admin\LogController;
use App\Http\Controllers\Admin\TagController;
use App\Http\Controllers\Admin\RoleController;
use App\Http\Controllers\Admin\PermissionController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\ReportController;
use App\Http\Controllers\Admin\DatabaseController;
use App\Http\Controllers\LocationRatingController;
use App\Http\Controllers\Admin\MenuManagementController;
use App\Http\Controllers\Admin\HeaderSettingsController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::group(
    [
        'prefix' => LaravelLocalization::setLocale(),
        'middleware' => [
            \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
            \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
            \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
            \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class,
        ],
    ], function () {
        // Public API endpoints (moved to routes/api.php to avoid conflicts)
        // Ajax search routes
        Route::prefix('api')->group(function () {
            Route::get('/search', [HomeController::class, 'search'])->name('search');

            // Geographic hierarchy API routes
            Route::get('/countries/{country}/provinces', [HomeController::class, 'getProvincesByCountry'])->name('provinces.by.country');
            Route::get('/provinces/{province}/counties', [HomeController::class, 'getCountiesByProvince'])->name('counties.by.province');
            Route::get('/counties/{county}/districts', [HomeController::class, 'getDistrictsByCounty'])->name('districts.by.county');
            Route::get('/districts/{district}/cities', [HomeController::class, 'getCitiesByDistrict'])->name('cities.by.district');
            Route::get('/districts/{district}/villages', [HomeController::class, 'getVillagesByDistrict'])->name('villages.by.district');
            Route::get('/countries/{country}/zones', [HomeController::class, 'getZonesByCountry'])->name('zones.by.country');
            Route::get('/cities/{city}/zones', [HomeController::class, 'getZonesByCity'])->name('zones.by.city');
        });



        // Database test route
        Route::get('/db-test', function () {
            try {
                // Test database connection
                $pdo = DB::connection()->getPdo();
                echo '<h1>اتصال به دیتابیس با موفقیت برقرار شد</h1>';
                echo '<p>نام دیتابیس: '.DB::connection()->getDatabaseName().'</p>';

                // Test read ability
                $categories = DB::table('categories')->select('id', 'category_fa')->limit(5)->get();
                echo '<h2>تست خواندن از دیتابیس:</h2>';
                echo '<ul>';
                foreach ($categories as $category) {
                    echo "<li>آیدی: {$category->id}, نام: {$category->category_fa}</li>";
                }
                echo '</ul>';

                // Create a test table if it doesn't exist
                if (! Schema::hasTable('db_write_test')) {
                    Schema::create('db_write_test', function ($table) {
                        $table->id();
                        $table->string('test_text');
                        $table->timestamps();
                    });
                    echo '<p>جدول تست با موفقیت ساخته شد.</p>';
                }

                // Test write ability
                $insertId = DB::table('db_write_test')->insertGetId([
                    'test_text' => 'تست نوشتن در دیتابیس - '.now()->format('H:i:s'),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                echo '<h2>تست نوشتن در دیتابیس:</h2>';
                echo "<p>رکورد جدید با آیدی {$insertId} با موفقیت ثبت شد.</p>";

                // Test read the newly inserted record
                $newRecord = DB::table('db_write_test')->where('id', $insertId)->first();
                echo "<p>محتوای رکورد جدید: {$newRecord->test_text}</p>";

                echo "<hr><a href='/admin/locations/create' class='btn btn-primary'>بازگشت به فرم ایجاد مکان</a>";

            } catch (\Exception $e) {
                echo "<h1 style='color:red'>خطا در دسترسی به دیتابیس</h1>";
                echo "<p>{$e->getMessage()}</p>";
                echo "<pre>{$e->getTraceAsString()}</pre>";
            }
        });

        // Direct location creation test
        Route::get('/location-test-create', function () {
            try {
                // Enable query log
                DB::enableQueryLog();

                echo '<h1>آزمایش مستقیم ایجاد مکان</h1>';

                // Get first category for testing
                $category = DB::table('categories')->first();
                if (! $category) {
                    throw new \Exception('هیچ دسته‌بندی در دیتابیس یافت نشد. ابتدا یک دسته‌بندی ایجاد کنید.');
                }

                echo "<p>دسته‌بندی انتخاب شده برای تست: {$category->category_fa} (آیدی: {$category->id})</p>";

                // Create location with minimal data
                $data = [
                    'title' => 'تست مستقیم مکان - '.now()->format('H:i:s'),
                    'title_id' => 'direct-test-'.time(),
                    'category_id' => $category->id,
                    'category' => $category->category_key,
                    'category_fa' => $category->category_fa,
                    'description' => 'این یک رکورد تست است که مستقیماً از طریق روت ایجاد شده است.',
                    'is_active' => 1,
                    'Slogan' => 'یک شعار تستی',
                    'created_at' => now(),
                    'updated_at' => now(),
                ];

                echo '<h2>داده‌های مکان برای درج:</h2>';
                echo '<pre>'.json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE).'</pre>';

                // Attempt direct insertion
                $locationId = DB::table('locations')->insertGetId($data);

                echo "<h2 style='color:green'>مکان با موفقیت ایجاد شد!</h2>";
                echo "<p>شناسه مکان جدید: {$locationId}</p>";

                // Show the DB queries executed
                $queries = DB::getQueryLog();
                echo '<h3>کوئری‌های اجرا شده:</h3>';
                echo '<pre>'.json_encode($queries, JSON_PRETTY_PRINT).'</pre>';

                echo "<hr><a href='/admin/locations' class='btn btn-primary'>نمایش لیست مکان‌ها</a>";

            } catch (\Exception $e) {
                echo "<h1 style='color:red'>خطا در ایجاد مکان</h1>";
                echo "<p>{$e->getMessage()}</p>";
                echo "<pre>{$e->getTraceAsString()}</pre>";

                // Show the DB queries that were attempted
                $queries = DB::getQueryLog();
                if (count($queries) > 0) {
                    echo '<h3>کوئری‌های اجرا شده:</h3>';
                    echo '<pre>'.json_encode($queries, JSON_PRETTY_PRINT).'</pre>';
                }
            }
        });

        // Storage image serving route (fallback for symlink issues)
        Route::get('/storage/{path}', function ($path) {
            // First try the symlink path (if it exists and works)
            $symlinkPath = public_path('storage/' . $path);
            if (file_exists($symlinkPath) && is_readable($symlinkPath)) {
                $mimeType = mime_content_type($symlinkPath);
                return response()->file($symlinkPath, [
                    'Content-Type' => $mimeType,
                    'Cache-Control' => 'public, max-age=31536000',
                ]);
            }

            // Fallback to direct storage path
            $fullPath = storage_path('app/public/' . $path);
            if (!file_exists($fullPath)) {
                abort(404, 'Image not found');
            }

            $mimeType = mime_content_type($fullPath);

            return response()->file($fullPath, [
                'Content-Type' => $mimeType,
                'Cache-Control' => 'public, max-age=31536000',
                'X-Served-By' => 'Laravel-Storage-Route',
            ]);
        })->where('path', '.*')->name('storage.serve');

        // Public routes
        Route::get('/', [HomeController::class, 'index'])->name('home');

        // Language routes
        Route::get('languages/switch/{locale}', [LanguageController::class, 'switchLanguage'])->name('languages.switch');

        // Menu routes
        Route::get('/categories', [App\Http\Controllers\CategoryController::class, 'index'])->name('categories.index');
        Route::get('/categories/{category}', [App\Http\Controllers\CategoryController::class, 'show'])->name('categories.show');
        // مسیر برای نمایش مکان ها با ساختار سلسله مراتبی دسته بندی
Route::get('/{categoryPath}/{titleId}', [\App\Http\Controllers\LocationController::class, 'showWithCategories'])
    ->where(['categoryPath' => '.*', 'titleId' => '.*-\d+$'])
    ->name('locations.showWithCategories');

Route::get('/locations/{location}', [App\Http\Controllers\LocationController::class, 'show'])->name('locations.show');
        Route::get('/location/{id}', [App\Http\Controllers\LocationController::class, 'show'])->name('location.show');
        Route::get('/map', [HomeController::class, 'map'])->name('map');
        Route::get('/popular', [HomeController::class, 'popular'])->name('popular');
        Route::get('/about', [HomeController::class, 'about'])->name('about');
        Route::get('/contact', [HomeController::class, 'contact'])->name('contact');
        Route::post('/contact/submit', [HomeController::class, 'contactSubmit'])->name('contact.submit');

        // Review routes
        Route::prefix('reviews')->name('reviews.')->group(function () {
            Route::get('/create/{location_id}', [ReviewController::class, 'create'])->name('create');
            Route::post('/', [ReviewController::class, 'store'])->name('store');
        });





        // Table structure test
        Route::get('/table-structure', function () {
            try {
                echo '<h1>بررسی ساختار جدول locations</h1>';

                // Get column information
                $columns = DB::select('SHOW COLUMNS FROM locations');

                echo '<h2>ساختار ستون‌ها:</h2>';
                echo "<table border='1' cellpadding='5' style='border-collapse: collapse;'>";
                echo '<tr><th>نام فیلد</th><th>نوع</th><th>Null مجاز؟</th><th>کلید</th><th>مقدار پیش‌فرض</th><th>ویژگی‌های دیگر</th></tr>';

                foreach ($columns as $column) {
                    $style = '';
                    if ($column->Field == 'Slogan') {
                        $style = 'background-color: #ffdddd;';
                    }

                    echo "<tr style='{$style}'>";
                    echo "<td>{$column->Field}</td>";
                    echo "<td>{$column->Type}</td>";
                    echo "<td>{$column->Null}</td>";
                    echo "<td>{$column->Key}</td>";
                    echo '<td>'.($column->Default === null ? 'NULL' : $column->Default).'</td>';
                    echo "<td>{$column->Extra}</td>";
                    echo '</tr>';
                }
                echo '</table>';

                echo '<h3>راه‌حل پیشنهادی:</h3>';
                echo '<p>برای حل مشکل فیلد Slogan (با S بزرگ)، می‌توانید یکی از این کارها را انجام دهید:</p>';
                echo '<ol>';
                echo '<li>در همه فرم‌ها و کدها، مقداری برای این فیلد تعیین کنید</li>';
                echo '<li>در دیتابیس، این فیلد را به NULL مجاز تغییر دهید:<br><code>ALTER TABLE locations MODIFY COLUMN `Slogan` VARCHAR(255) NULL;</code></li>';
                echo "<li>در دیتابیس، مقدار پیش‌فرض برای این فیلد تعیین کنید:<br><code>ALTER TABLE locations ALTER COLUMN `Slogan` SET DEFAULT '';</code></li>";
                echo '</ol>';

                echo '<hr>';
                echo "<p><a href='/db-test'>آزمایش اتصال به دیتابیس</a> | <a href='/location-test-create'>ایجاد مستقیم مکان</a> | <a href='/raw-form-test'>فرم خام HTML</a></p>";

            } catch (\Exception $e) {
                echo "<h1 style='color:red'>خطا در بررسی ساختار جدول</h1>";
                echo "<p>{$e->getMessage()}</p>";
            }
        });

        // Data test route
        Route::get('/data-test', function () {
            try {
                $stats = [
                    'locations_count' => \App\Models\Location::count(),
                    'categories_count' => \App\Models\Category::count(),
                    'provinces_count' => \App\Models\Province::count(),
                    'sample_location' => \App\Models\Location::with('categoryRelation')->first(),
                    'sample_category' => \App\Models\Category::withCount('locations')->first(),
                    'sample_province' => \App\Models\Province::first()
                ];

                return response()->json($stats, 200, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            } catch (\Exception $e) {
                return response()->json(['error' => $e->getMessage()], 500);
            }
        });

        // Raw HTML form test
        Route::get('/raw-form-test', function () {
            // Get a list of all categories
            $categories = DB::table('categories')->select('id', 'category_fa')->get();

            // HTML content for a minimal form
            $html = <<<'HTML'
        <!DOCTYPE html>
        <html dir="rtl" lang="fa">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>فرم خام تست</title>
            <style>
                body { font-family: Tahoma, Arial; line-height: 1.6; margin: 20px; }
                h1 { color: #4a5568; }
                .container { max-width: 800px; margin: 0 auto; }
                .form-group { margin-bottom: 15px; }
                label { display: block; margin-bottom: 5px; font-weight: bold; }
                input, select, textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
                button { background: #3490dc; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer; }
                .alert { padding: 15px; margin-bottom: 20px; border-radius: 4px; }
                .alert-info { background-color: #ebf8ff; border: 1px solid #90cdf4; color: #2c5282; }
                .alert-warning { background-color: #fffaf0; border: 1px solid #fbd38d; color: #9c4221; }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>فرم خام برای تست ایجاد مکان</h1>

                <div class="alert alert-info">
                    این فرم بدون هیچ JavaScript و با حداقل CSS طراحی شده است تا مشکلات احتمالی را شناسایی کند.
                </div>

                <form action="/admin/locations" method="POST">
                    <input type="hidden" name="_token" value="'.csrf_token().'">

                    <div class="form-group">
                        <label for="title">عنوان مکان (الزامی)</label>
                        <input type="text" id="title" name="title" value="تست خام '.date('H:i:s').'" required>
                    </div>

                    <div class="form-group">
                        <label for="category_id">دسته‌بندی (الزامی)</label>
                        <select id="category_id" name="category_id" required>
                            <option value="">انتخاب کنید</option>
    HTML;

            // Add category options
            foreach ($categories as $category) {
                $html .= '<option value="'.$category->id.'">'.$category->category_fa.'</option>';
            }

            $html .= <<<'HTML'
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="description">توضیحات</label>
                        <textarea id="description" name="description" rows="3">این یک تست با فرم خام HTML است.</textarea>
                    </div>

                    <div class="form-group">
                        <label for="slogan">شعار (الزامی)</label>
                        <input type="text" id="slogan" name="Slogan" value="شعار تستی" required>
                        <small style="color: red;">توجه: نام فیلد دقیقاً Slogan (با S بزرگ) است!</small>
                    </div>

                    <div class="form-group">
                        <button type="submit">ثبت مکان</button>
                    </div>
                </form>

                <div class="alert alert-warning">
                    <p>اگر این فرم هم موفق به ثبت مکان نشد، احتمالاً مشکل در:</p>
                    <ul>
                        <li>دسترسی‌های دیتابیس</li>
                        <li>مسیریابی (routes)</li>
                        <li>تنظیمات CSRF</li>
                        <li>یا خطای سرور PHP</li>
                    </ul>
                    <p>می‌باشد. در این صورت از صفحات تست مستقیم دیتابیس استفاده کنید.</p>
                </div>

                <p><a href="/db-test">آزمایش اتصال به دیتابیس</a> | <a href="/location-test-create">ایجاد مستقیم مکان</a></p>
            </div>
        </body>
        </html>
        HTML;

            return $html;
        });

        // User Panel Routes
        Route::prefix('user')->name('user.')->group(function () {
            // Public user auth routes
            Route::get('/login', [UserAuthController::class, 'showLoginForm'])->name('login');
            Route::post('/login', [UserAuthController::class, 'login']);
            Route::get('/register', [UserAuthController::class, 'showRegistrationForm'])->name('register');
            Route::post('/register', [UserAuthController::class, 'register']);

            // Password reset routes
            Route::get('/password/reset', [\App\Http\Controllers\Auth\ForgotPasswordController::class, 'showLinkRequestForm'])->name('password.request');
            Route::post('/password/email', [\App\Http\Controllers\Auth\ForgotPasswordController::class, 'sendResetLinkEmail'])->name('password.email');
            Route::get('/password/reset/{token}', [\App\Http\Controllers\Auth\ForgotPasswordController::class, 'showResetForm'])->name('password.reset');
            Route::post('/password/reset', [\App\Http\Controllers\Auth\ForgotPasswordController::class, 'reset'])->name('password.update');

            // Protected user routes
            Route::middleware(['auth', 'web'])->group(function () {
                // Dashboard
                Route::get('/', [UserDashboardController::class, 'index'])->name('dashboard');
                Route::get('/dashboard', [UserDashboardController::class, 'index'])->name('dashboard.index');

                // Profile
                Route::get('/profile', [UserDashboardController::class, 'profile'])->name('profile');
                Route::post('/profile', [UserDashboardController::class, 'updateProfile'])->name('profile.update');
                Route::get('/change-password', [UserAuthController::class, 'showChangePasswordForm'])->name('change-password');
                Route::post('/change-password', [UserAuthController::class, 'changePassword'])->name('password.change');

                // Location submissions
                Route::get('/locations', [LocationSubmissionController::class, 'index'])->name('locations.index');
                Route::get('/locations/create', [LocationSubmissionController::class, 'create'])->name('locations.create');
                Route::post('/locations', [LocationSubmissionController::class, 'store'])->name('locations.store');
                Route::get('/locations/{id}', [LocationSubmissionController::class, 'show'])->name('locations.show');
                Route::get('/locations/{id}/edit', [LocationSubmissionController::class, 'edit'])->name('locations.edit');
                Route::put('/locations/{id}', [LocationSubmissionController::class, 'update'])->name('locations.update');
                Route::delete('/locations/{id}', [LocationSubmissionController::class, 'destroy'])->name('locations.destroy');

                // Ratings
                Route::resource('ratings', UserRatingController::class);

                // Logout
                Route::post('/logout', [UserAuthController::class, 'logout'])->name('logout');
            });
        });

        // Global login route for middleware redirects
        Route::get('/login', function () {
            return redirect()->route('user.login');
        })->name('login');



        // Admin Authentication & Protected Routes
        Route::prefix('admin')->name('admin.')->group(function () {
            // مسیرهای عمومی ادمین (بدون نیاز به احراز هویت)
            Route::get('/login', [AdminAuthController::class, 'showLoginForm'])->name('login');
            Route::post('/login', [AdminAuthController::class, 'login']);

            // API endpoint for quick stats (accessible without auth for login page)
            Route::get('/api/quick-stats', function () {
                try {
                    $stats = [
                        'locations' => \App\Models\Location::count(),
                        'users' => \App\Models\User::count(),
                        'ratings' => \App\Models\Rating::count(),
                        'categories' => \App\Models\Category::count(),
                        'timestamp' => now()->format('H:i:s')
                    ];

                    return response()->json($stats)
                        ->header('Access-Control-Allow-Origin', '*')
                        ->header('Access-Control-Allow-Methods', 'GET')
                        ->header('Access-Control-Allow-Headers', 'Content-Type');
                } catch (\Exception $e) {
                    \Log::error('Stats API Error: ' . $e->getMessage());
                    return response()->json([
                        'error' => 'Unable to fetch stats',
                        'message' => $e->getMessage(),
                        'timestamp' => now()->format('H:i:s')
                    ], 500)
                        ->header('Access-Control-Allow-Origin', '*')
                        ->header('Access-Control-Allow-Methods', 'GET')
                        ->header('Access-Control-Allow-Headers', 'Content-Type');
                }
            });

            // Test page for login design
            Route::get('/test-login', function () {
                return view('admin.test-login');
            });

            // مسیرهای محافظت‌شده ادمین
            Route::middleware(['auth:admin', 'admin'])->group(function () {
                Route::get('/', [DashboardController::class, 'index'])->name('dashboard.index');
                Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

                // Languages
                Route::resource('languages', LanguageController::class);
                Route::post('languages/{language}/toggle-active', [LanguageController::class, 'toggleActive'])->name('languages.toggle-active');
                Route::post('languages/{language}/set-default', [LanguageController::class, 'setDefault'])->name('languages.set-default');
                Route::get('languages/{language}/translations', [LanguageController::class, 'translations'])->name('languages.translations');

                // Translations
                Route::resource('translations', TranslationController::class);
                Route::post('translations/import', [TranslationController::class, 'import'])->name('translations.import');
                Route::get('translations/export', [TranslationController::class, 'export'])->name('translations.export');
                Route::post('translations/scan', [TranslationController::class, 'scan'])->name('translations.scan');

                // API routes for hierarchical selects
                Route::prefix('api')->name('api.')->group(function () {
                    Route::get('/categories', [App\Http\Controllers\Admin\ApiController::class, 'getCategories'])->name('categories');
                    Route::get('/geography/provinces/{countryId}', [App\Http\Controllers\Admin\ApiController::class, 'getProvincesByCountry'])->name('provinces.by.country');
                    Route::get('/geography/counties/{provinceId}', [App\Http\Controllers\Admin\ApiController::class, 'getCountiesByProvince'])->name('counties.by.province');
                    Route::get('/geography/districts/{countyId}', [App\Http\Controllers\Admin\ApiController::class, 'getDistrictsByCounty'])->name('districts.by.county');
                    Route::get('/geography/cities/{districtId}', [App\Http\Controllers\Admin\ApiController::class, 'getCitiesByDistrict'])->name('cities.by.district');
                    Route::get('/geography/villages/{districtId}', [App\Http\Controllers\Admin\ApiController::class, 'getVillagesByDistrict'])->name('villages.by.district');
                    Route::get('/geography/zones/{parentType}/{parentId}', [App\Http\Controllers\Admin\ApiController::class, 'getZonesByParent'])->name('zones.by.parent');
                    Route::get('/geography/zones/children/{parentZoneId}', [App\Http\Controllers\Admin\ApiController::class, 'getChildZones'])->name('zones.children');

                    // Route for popular page cities by province
                    Route::get('/geography/cities-by-province/{provinceId}', [HomeController::class, 'getCitiesByProvince'])->name('cities.by.province');

                    // New route for fetching boundary data
                    Route::get('/boundaries/{regionType}/{regionId}', [App\Http\Controllers\Admin\ApiController::class, 'getBoundaryData'])->name('boundaries');
                });

                // Analytics & Reports
                Route::prefix('analytics')->name('analytics.')->group(function () {
                    Route::get('/', [AnalyticsController::class, 'index'])->name('index');
                    Route::get('/user', [AnalyticsController::class, 'user'])->name('user');
                    Route::get('/geographic', [AnalyticsController::class, 'geographic'])->name('geographic');
                    Route::get('/predictive', [AnalyticsController::class, 'predictive'])->name('predictive');
                    Route::get('/performance', [AnalyticsController::class, 'performanceKPI'])->name('performance');
                    Route::get('/comparisons', [AnalyticsController::class, 'comparisons'])->name('comparisons');
                    Route::post('/export', [AnalyticsController::class, 'export'])->name('export');
                    Route::get('/geo-filter', [AnalyticsController::class, 'geoFilter'])->name('geo-filter');
                    Route::get('/refresh', [AnalyticsController::class, 'refreshAnalytics'])->name('refresh');
                    Route::get('/realtime', [AnalyticsController::class, 'getRealtimeAnalytics'])->name('realtime');
                });

                // Locations
                Route::resource('locations', AdminLocationController::class);
                Route::post('locations/toggle-active/{id}', [AdminLocationController::class, 'toggleActive'])->name('locations.toggle-active');
                Route::get('locations-select', [AdminLocationController::class, 'getLocationsForSelect'])->name('locations.select');
                Route::get('locations/{location}/direct-update', [AdminLocationController::class, 'directUpdate'])->name('locations.direct-update');
                Route::post('locations/{location}/simple-update', [AdminLocationController::class, 'simpleUpdate'])->name('locations.simple-update');

                // New AJAX routes for modern interface
                Route::get('locations/provinces', [AdminLocationController::class, 'getProvinces'])->name('locations.provinces');
                Route::get('locations/cities/{provinceId}', [AdminLocationController::class, 'getCities'])->name('locations.cities');
                Route::get('locations/stats', [AdminLocationController::class, 'getStats'])->name('locations.stats');
                Route::post('locations/{id}/toggle-status', [AdminLocationController::class, 'toggleStatus'])->name('locations.toggle-status');
                Route::post('locations/bulk-activate', [AdminLocationController::class, 'bulkActivate'])->name('locations.bulk-activate');
                Route::post('locations/bulk-deactivate', [AdminLocationController::class, 'bulkDeactivate'])->name('locations.bulk-deactivate');
                Route::post('locations/bulk-delete', [AdminLocationController::class, 'bulkDelete'])->name('locations.bulk-delete');
                Route::get('locations/export/excel', [AdminLocationController::class, 'exportExcel'])->name('locations.export-excel');
                Route::get('locations/export/pdf', [AdminLocationController::class, 'exportPDF'])->name('locations.export-pdf');
                Route::get('locations/search', [AdminLocationController::class, 'search'])->name('locations.search');

                // Reports
                Route::get('reports/locations', [ReportController::class, 'locations'])->name('reports.locations');
                Route::get('reports/users', [ReportController::class, 'users'])->name('reports.users');
                Route::get('reports/advertisements', [ReportController::class, 'advertisements'])->name('reports.advertisements');

                // API Routes
                Route::get('api/cities/{province}', [AdminLocationController::class, 'getCitiesByProvince'])->name('api.cities.by-province');
                Route::get('api/locations/today-count', [ReportController::class, 'getTodayCount'])->name('api.locations.today-count');
                Route::get('api/cities/{provinceId}', [ReportController::class, 'getCitiesByProvince'])->name('api.cities.by-province-reports');

                // Categories
                Route::resource('categories', CategoryController::class);
                Route::post('categories/toggle-active/{id}', [CategoryController::class, 'toggleActive'])->name('categories.toggle-active');
                Route::get('categories-tree', [CategoryController::class, 'tree'])->name('categories.tree');
                Route::get('/admin/api/categories/{parentId}/children', [CategoryController::class, 'getChildren'])->name('admin.categories.children');

                // Amenities
                Route::resource('amenities', AmenityController::class)->except(['show']);
                Route::resource('amenity-types', AmenityController::class)->names([
                    'index' => 'amenity-types.index',
                    'create' => 'amenity-types.create',
                    'store' => 'amenity-types.store',
                    'show' => 'amenity-types.show',
                    'edit' => 'amenity-types.edit',
                    'update' => 'amenity-types.update',
                    'destroy' => 'amenity-types.destroy',
                ]);

                // Ratings
                Route::resource('ratings', RatingController::class)->except(['show']);
                Route::post('ratings/update-status/{id}', [RatingController::class, 'updateStatus'])->name('ratings.update-status');
                Route::get('ratings/dashboard', [RatingController::class, 'dashboard'])->name('ratings.dashboard');
                Route::post('ratings/{id}/approve', [RatingController::class, 'approve'])->name('ratings.approve');
                Route::post('ratings/{id}/reject', [RatingController::class, 'reject'])->name('ratings.reject');
                Route::delete('ratings/{id}', [RatingController::class, 'delete'])->name('ratings.delete');
                // مسیر برای نمایش نظرات در انتظار تایید
                Route::get('ratings/pending', [RatingController::class, 'pending'])->name('ratings.pending');
                // مسیرهای جدید برای تنظیمات و آنالیز
                Route::get('ratings/settings', [RatingController::class, 'settings'])->name('ratings.settings');
                Route::post('ratings/settings', [RatingController::class, 'updateSettings'])->name('ratings.settings.update');
                Route::get('ratings/analytics', [RatingController::class, 'analytics'])->name('ratings.analytics');
                Route::post('ratings/bulk-action', [RatingController::class, 'bulkAction'])->name('ratings.bulk-action');
                Route::get('ratings/test-bulk', [RatingController::class, 'testBulkAction'])->name('ratings.test-bulk');

                // Geography
                Route::prefix('geography')->name('geography.')->group(function () {
                    Route::resource('countries', GeographyController::class)->names('countries');
                    Route::resource('provinces', GeographyController::class)->names('provinces');
                    Route::resource('counties', GeographyController::class)->names('counties');
                    Route::resource('districts', GeographyController::class)->names('districts');
                    Route::resource('cities', GeographyController::class)->names('cities');
                    Route::resource('villages', GeographyController::class)->names('villages');
                    Route::resource('zones', GeographyController::class)->names('zones');

                    // API routes for dropdowns
                    Route::get('provinces/{province}/counties', [GeographyController::class, 'getCountiesByProvince']);
                    Route::get('counties/{county}/districts', [GeographyController::class, 'getDistrictsByCounty']);
                    Route::get('districts/{district}/cities', [GeographyController::class, 'getCitiesByDistrict']);
                    Route::get('districts/{district}/villages', [GeographyController::class, 'getVillagesByDistrict']);

                    // Fix boundaries route
                    Route::get('provinces/{id}/fix-boundaries', [GeographyController::class, 'fixBoundaries'])->name('provinces.fix-boundaries');
                });

                // Admin Users
                Route::resource('admin-users', AdminUserController::class)->names('admins');
                Route::post('admin-users/toggle-active/{id}', [AdminUserController::class, 'toggleActive'])->name('admins.toggle-active');

                // Profile
                Route::get('profile', [AdminUserController::class, 'profile'])->name('profile');
                Route::post('profile', [AdminUserController::class, 'updateProfile'])->name('profile.update');
                Route::get('change-password', [AdminAuthController::class, 'showChangePasswordForm'])->name('change-password');
                Route::post('change-password', [AdminAuthController::class, 'changePassword'])->name('password.change');

                // Profile API endpoints
                Route::get('api/profile-stats', [AdminUserController::class, 'getProfileStatsApi'])->name('api.profile-stats');

                // Advertisements
                Route::resource('advertisements', AdminAdvertisementController::class);
                Route::post('advertisements/toggle-active/{id}', [AdminAdvertisementController::class, 'toggleActive'])->name('advertisements.toggle-active');

                // Ad Zones Management
                Route::prefix('ads')->name('ads.')->group(function () {
                    Route::get('display-zones', [App\Http\Controllers\Admin\AdController::class, 'displayZones'])->name('display-zones');
                    Route::post('create-zone', [App\Http\Controllers\Admin\AdController::class, 'createZone'])->name('create-zone');
                    Route::post('update-zone', [App\Http\Controllers\Admin\AdController::class, 'updateZone'])->name('update-zone');
                    Route::delete('delete-zone', [App\Http\Controllers\Admin\AdController::class, 'deleteZone'])->name('delete-zone');

                    // Zone Ads Management
                    Route::get('manage-zone-ads', [App\Http\Controllers\Admin\AdController::class, 'manageZoneAds'])->name('manage-zone-ads');
                    Route::post('assign-to-zone', [App\Http\Controllers\Admin\AdController::class, 'assignAdToZone'])->name('assign-to-zone');
                    Route::post('update-zone-ad', [App\Http\Controllers\Admin\AdController::class, 'updateZoneAdAssignment'])->name('update-zone-ad');
                    Route::delete('delete-zone-ad', [App\Http\Controllers\Admin\AdController::class, 'deleteZoneAdAssignment'])->name('delete-zone-ad');
                });

                // Category Templates
                Route::resource('category-templates', CategoryTemplateController::class);
                Route::post('category-templates/{id}/toggle-active', [CategoryTemplateController::class, 'toggleActive'])->name('category-templates.toggle-active');

                // تنظیمات امنیتی
                Route::get('security-settings', [SecuritySettingController::class, 'index'])->name('security-settings.index');
                Route::post('security-settings', [SecuritySettingController::class, 'update'])->name('security-settings.update');
                Route::post('security-settings/toggle', [SecuritySettingController::class, 'toggleSetting'])->name('security-settings.toggle');
                Route::get('security-settings/{group}', [SecuritySettingController::class, 'getSettings'])->name('security-settings.get');
                Route::get('security-settings/login-history', [SecuritySettingController::class, 'loginHistory'])->name('security-settings.login-history');
                Route::get('modules/active', [SecuritySettingController::class, 'activeModules'])->name('modules.active');
                Route::get('modules/install', [SecuritySettingController::class, 'installModule'])->name('modules.install');
                Route::get('backup/create', [SecuritySettingController::class, 'createBackup'])->name('backup.create');

                // Display Settings Management
                Route::prefix('display-settings')->name('display-settings.')->group(function () {
                    Route::get('/', [DisplaySettingController::class, 'index'])->name('index');
                    Route::get('/create', [DisplaySettingController::class, 'create'])->name('create');
                    Route::post('/', [DisplaySettingController::class, 'store'])->name('store');
                    Route::get('/{displaySetting}/edit', [DisplaySettingController::class, 'edit'])->name('edit');
                    Route::put('/{displaySetting}', [DisplaySettingController::class, 'update'])->name('update');
                    Route::delete('/{displaySetting}', [DisplaySettingController::class, 'destroy'])->name('destroy');
                    Route::get('/homepage', [DisplaySettingController::class, 'homepage'])->name('homepage');
                    Route::post('/homepage', [DisplaySettingController::class, 'updateHomepage'])->name('homepage.update');
                });

                // تنظیمات سایت
                Route::prefix('settings')->name('settings.')->group(function () {
                    Route::get('/', [SiteSettingController::class, 'index'])->name('index');
                    Route::get('/general', [SiteSettingController::class, 'general'])->name('general');
                    Route::get('/email', [SiteSettingController::class, 'email'])->name('email');
                    Route::get('/payment', [SiteSettingController::class, 'payment'])->name('payment');
                    Route::post('/', [SiteSettingController::class, 'store'])->name('store');
                    Route::post('/clear-cache', [SiteSettingController::class, 'clearCache'])->name('clear-cache');
                    Route::post('/toggle-maintenance', [SiteSettingController::class, 'toggleMaintenanceMode'])->name('toggle-maintenance');
                });

                // Templates
                Route::resource('templates', TemplateController::class);
                // پیش‌نمایش زنده قالب (فقط برای ادمین)
                Route::post('templates/preview', [TemplateController::class, 'preview'])->name('admin.templates.preview');
                Route::get('templates/ajax-search', [TemplateController::class, 'ajaxSearch'])->name('templates.ajax_search');

                // Logout
                Route::post('/logout', [AdminAuthController::class, 'logout'])->name('logout');

                // پیام‌ها
                // مسیرهای خاص باید قبل از مسیرهای عمومی تعریف شوند
                Route::get('/messages/inbox', [MessageController::class, 'inbox'])->name('messages.inbox');
                Route::get('/messages/sent', [MessageController::class, 'sent'])->name('messages.sent');
                Route::get('/messages/trash', [MessageController::class, 'trash'])->name('messages.trash');
                Route::post('/messages/restore/{message}', [MessageController::class, 'restore'])->name('messages.restore');
                Route::delete('/messages/force-delete/{message}', [MessageController::class, 'forceDelete'])->name('messages.force_delete');

                // مسیرهای عمومی پیام‌ها
                Route::get('/messages', [MessageController::class, 'index'])->name('messages.index');
                Route::get('/messages/{message}', [MessageController::class, 'show'])->name('messages.show');
                Route::delete('/messages/{message}', [MessageController::class, 'destroy'])->name('messages.destroy');

                // اعلان‌ها
                Route::get('/notifications', [NotificationController::class, 'index'])->name('admin.notifications.index');
                Route::get('/notifications/{notification}', [NotificationController::class, 'show'])->name('admin.notifications.show');
                Route::delete('/notifications/{notification}', [NotificationController::class, 'destroy'])->name('admin.notifications.destroy');
                Route::post('/notifications/mark-all-read', [NotificationController::class, 'markAllAsRead'])->name('admin.notifications.mark-all-read');

                // تنظیمات اعلان‌ها
                Route::get('/notifications/settings', [NotificationController::class, 'settings'])->name('admin.notifications.settings');
                Route::post('/notifications/settings', [NotificationController::class, 'updateSettings'])->name('admin.notifications.settings.update');
                Route::post('/notifications/settings/toggle', [NotificationController::class, 'toggleSetting'])->name('admin.notifications.settings.toggle');

                // آمار و گزارشات
                Route::get('/statistics', [StatisticsController::class, 'index'])->name('statistics.index');
                Route::get('/statistics/users', [StatisticsController::class, 'users'])->name('statistics.users');
                Route::get('/statistics/locations', [StatisticsController::class, 'locations'])->name('statistics.locations');
                Route::get('/statistics/visits', [StatisticsController::class, 'visits'])->name('statistics.visits');

                // مدیریت نقش‌ها و دسترسی‌ها
                Route::resource('roles', RoleController::class);
                Route::resource('permissions', PermissionController::class);

                // مدیریت کاربران
                Route::resource('users', UserController::class);

                // مدیریت تگ‌ها
                Route::resource('tags', TagController::class);

                // گزارش‌ها
                Route::prefix('reports')->name('reports.')->group(function () {
                    Route::get('/locations', [ReportController::class, 'locations'])->name('locations');
                    Route::get('/users', [ReportController::class, 'users'])->name('users');
                    Route::get('/visits', [ReportController::class, 'visits'])->name('visits');
                    Route::get('/advertisements', [ReportController::class, 'advertisements'])->name('advertisements');
                });

                // Backup routes
                Route::get('/backup', [App\Http\Controllers\Admin\BackupController::class, 'index'])->name('backup.index');
                Route::get('/backup/create', [App\Http\Controllers\Admin\BackupController::class, 'create'])->name('backup.create');
                Route::get('/backup/download/{filename}', [App\Http\Controllers\Admin\BackupController::class, 'download'])->name('backup.download');
                Route::delete('/backup/{filename}', [App\Http\Controllers\Admin\BackupController::class, 'destroy'])->name('backup.destroy');

                // Database optimization routes
                Route::prefix('tools')->group(function () {
                    Route::get('/database', [DatabaseController::class, 'index'])->name('tools.database');
                    Route::post('/optimize-database', [DatabaseController::class, 'optimize'])->name('tools.optimize-database');
                    Route::post('/repair-tables', [DatabaseController::class, 'repair'])->name('tools.repair-tables');
                    Route::post('/analyze-tables', [DatabaseController::class, 'analyze'])->name('tools.analyze-tables');
                    Route::post('/clear-cache', [DatabaseController::class, 'clearCache'])->name('tools.clear-cache');
                    Route::get('/advanced-search', [DatabaseController::class, 'advancedSearch'])->name('tools.advanced-search');
                });

                // Logs routes
                Route::get('/logs', [App\Http\Controllers\Admin\LogController::class, 'index'])->name('logs.index');
                Route::get('/logs/{filename}', [App\Http\Controllers\Admin\LogController::class, 'show'])->name('logs.show');
                Route::delete('/logs/{filename}', [App\Http\Controllers\Admin\LogController::class, 'destroy'])->name('logs.destroy');
                Route::get('/logs/download/{filename}', [App\Http\Controllers\Admin\LogController::class, 'download'])->name('logs.download');

                // Menu Management routes
                Route::prefix('menu-management')->name('menu-management.')->group(function () {
                    Route::get('/', [MenuManagementController::class, 'index'])->name('index');
                    Route::get('/create', [MenuManagementController::class, 'create'])->name('create');
                    Route::get('/{menu}', [MenuManagementController::class, 'show'])->name('show');
                    Route::get('/{menu}/edit', [MenuManagementController::class, 'edit'])->name('edit');

                    // Routes that modify data
                    Route::post('/', [MenuManagementController::class, 'store'])->name('store');
                    Route::put('/{menu}', [MenuManagementController::class, 'update'])->name('update');
                    Route::delete('/{menu}', [MenuManagementController::class, 'destroy'])->name('destroy');
                    Route::post('/update-order', [MenuManagementController::class, 'updateOrder'])->name('update-order');
                    Route::post('/{menu}/toggle-status', [MenuManagementController::class, 'toggleStatus'])->name('toggle-status');
                });

                // Header Settings routes
                Route::prefix('header-settings')->name('header-settings.')->group(function () {
                    Route::get('/', [HeaderSettingsController::class, 'index'])->name('index');

                    // Routes that modify data
                    Route::post('/update-header', [HeaderSettingsController::class, 'updateHeaderSettings'])->name('update-header');
                    Route::post('/update-buttons', [HeaderSettingsController::class, 'updateButtonSettings'])->name('update-buttons');
                    Route::post('/add-button', [HeaderSettingsController::class, 'addButton'])->name('add-button');
                    Route::delete('/buttons/{button}', [HeaderSettingsController::class, 'deleteButton'])->name('delete-button');
                    Route::post('/buttons/{button}/toggle-visibility', [HeaderSettingsController::class, 'toggleButtonVisibility'])->name('toggle-button-visibility');
                    Route::get('/reset-default', [HeaderSettingsController::class, 'resetToDefault'])->name('reset-default');
                    Route::get('/reset-all-default', [HeaderSettingsController::class, 'resetAllToDefault'])->name('reset-all-default');
                });

                // User Menu Management routes
                Route::prefix('user-menu')->name('user-menu.')->group(function () {
                    Route::get('/', [\App\Http\Controllers\Admin\UserMenuController::class, 'index'])->name('index');
                    Route::post('/update-buttons', [\App\Http\Controllers\Admin\UserMenuController::class, 'updateButtons'])->name('update-buttons');
                    Route::post('/add-button', [\App\Http\Controllers\Admin\UserMenuController::class, 'addButton'])->name('add-button');
                    Route::post('/buttons/{button}/toggle-visibility', [\App\Http\Controllers\Admin\UserMenuController::class, 'toggleButtonVisibility'])->name('toggle-button-visibility');
                    Route::get('/reset-default', [\App\Http\Controllers\Admin\UserMenuController::class, 'resetToDefault'])->name('reset-default');
                });
            });
        });
    });

// Modern Rating & Comment System Routes (outside middleware groups)
Route::prefix('ratings')->name('ratings.')->group(function () {
    Route::post('/', [LocationRatingController::class, 'store'])->name('store');
    Route::get('/location/{titleId}', [LocationRatingController::class, 'getLocationRatings'])->name('location');
});

// API Routes for Rating System (outside middleware groups)
Route::prefix('api')->name('api.')->group(function () {
    Route::post('/ratings/react', [LocationRatingController::class, 'react'])->name('ratings.react');
    Route::post('/comments/react', [LocationRatingController::class, 'react'])->name('comments.react');
    Route::post('/comments/reply', [LocationRatingController::class, 'reply'])->name('comments.reply');
});