<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Amenity;
use App\Models\AmenityType;
use App\Models\Category;
use App\Models\City;
use App\Models\Country;
use App\Models\County;
use App\Models\District;
use App\Models\Location;
use App\Models\LocationAmenity;
use App\Models\LocationSeo;
use App\Models\Province;
use App\Models\Village;
use App\Models\Zone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class LocationController extends Controller
{
    /**
     * Display a listing of locations
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = Location::with(['categoryRelation', 'province', 'city']);

        // Apply filters
        if ($request->has('category_id') && $request->category_id) {
            $query->where('category_id', $request->category_id);
        }

        if ($request->has('is_active') && $request->is_active != '') {
            $query->where('is_active', $request->is_active);
        }

        if ($request->has('province_id') && $request->province_id) {
            $query->where('province_id', $request->province_id);
        }

        if ($request->has('city_id') && $request->city_id) {
            $query->where('city_id', $request->city_id);
        }

        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                    ->orWhere('title_id', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhere('address', 'like', "%{$search}%")
                    ->orWhere('tags', 'like', "%{$search}%");
            });
        }

        if ($request->has('created_date') && $request->created_date) {
            $query->whereDate('created_at', $request->created_date);
        }

        if ($request->has('has_coordinates')) {
            if ($request->has_coordinates == '1') {
                $query->whereNotNull('lat')->whereNotNull('lng');
            } else {
                $query->where(function($q) {
                    $q->whereNull('lat')->orWhereNull('lng');
                });
            }
        }

        // Sort
        $sortField = $request->sort ?? 'created_at';
        $sortDirection = $request->direction ?? 'desc';
        $query->orderBy($sortField, $sortDirection);

        $locations = $query->paginate(25)->withQueryString();

        // Get categories with location counts
        $categories = Category::where('is_active', 1)
            ->withCount('locations')
            ->orderBy('category_fa')
            ->get();

        // Calculate statistics with error handling
        try {
            $stats = [
                'total' => Location::count(),
                'active' => Location::where('is_active', 1)->count(),
                'inactive' => Location::where('is_active', 0)->count(),
                'with_coordinates' => Location::whereNotNull('lat')->whereNotNull('lng')->count(),
                'without_coordinates' => Location::where(function($q) {
                    $q->whereNull('lat')->orWhereNull('lng');
                })->count(),
                'today' => Location::whereDate('created_at', today())->count(),
                'this_week' => Location::whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
                'this_month' => Location::whereMonth('created_at', now()->month)->whereYear('created_at', now()->year)->count(),
            ];
        } catch (\Exception $e) {
            // Fallback stats in case of error
            $stats = [
                'total' => 0,
                'active' => 0,
                'inactive' => 0,
                'with_coordinates' => 0,
                'without_coordinates' => 0,
                'today' => 0,
                'this_week' => 0,
                'this_month' => 0,
            ];
            \Log::error('Error calculating location stats: ' . $e->getMessage());
        }

        if ($request->ajax()) {
            return response()->json([
                'html' => view('admin.locations.partials.locations-table', compact('locations'))->render(),
                'pagination' => view('admin.partials.pagination', ['paginator' => $locations])->render(),
                'stats' => $stats,
            ]);
        }

        // Chart data
        $chartData = [
            'monthly' => $this->getMonthlyData(),
            'provinces' => $this->getProvinceData(),
            'ratings' => $this->getRatingData()
        ];

        return view('admin.locations.index', compact('locations', 'categories', 'stats', 'chartData'));
    }

    /**
     * Get provinces for AJAX requests
     */
    public function getProvinces()
    {
        try {
            $provinces = Province::orderBy('name')
                ->select('id', 'name')
                ->get();

            return response()->json($provinces);
        } catch (\Exception $e) {
            \Log::error('Error fetching provinces: ' . $e->getMessage());
            return response()->json(['error' => 'خطا در بارگذاری استان‌ها'], 500);
        }
    }

    /**
     * Get cities by province for AJAX requests
     */
    public function getCities($provinceId)
    {
        try {
            // Check if the relationship field exists in cities table
            $cities = City::where('county_id', function($query) use ($provinceId) {
                    $query->select('id')
                          ->from('state3_counties')
                          ->where('province_id', $provinceId);
                })
                ->orderBy('name')
                ->select('id', 'name')
                ->get();

            // If no cities found with county relationship, try direct province_id
            if ($cities->isEmpty()) {
                $cities = City::whereHas('county', function($query) use ($provinceId) {
                        $query->where('province_id', $provinceId);
                    })
                    ->orderBy('name')
                    ->select('id', 'name')
                    ->get();
            }

            return response()->json($cities);
        } catch (\Exception $e) {
            \Log::error('Error fetching cities: ' . $e->getMessage());
            return response()->json(['error' => 'خطا در بارگذاری شهرها'], 500);
        }
    }

    /**
     * Get current statistics for AJAX requests
     */
    public function getStats()
    {
        $stats = [
            'total' => Location::count(),
            'active' => Location::where('is_active', 1)->count(),
            'inactive' => Location::where('is_active', 0)->count(),
            'with_coordinates' => Location::whereNotNull('lat')->whereNotNull('lng')->count(),
            'without_coordinates' => Location::where(function($q) {
                $q->whereNull('lat')->orWhereNull('lng');
            })->count(),
            'today' => Location::whereDate('created_at', today())->count(),
            'this_week' => Location::whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
            'this_month' => Location::whereMonth('created_at', now()->month)->whereYear('created_at', now()->year)->count(),
        ];

        return response()->json($stats);
    }

    /**
     * Toggle location status
     */
    public function toggleStatus($id)
    {
        try {
            $location = Location::findOrFail($id);
            $location->is_active = !$location->is_active;
            $location->save();

            return response()->json([
                'success' => true,
                'message' => 'وضعیت مکان با موفقیت تغییر کرد',
                'new_status' => $location->is_active
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در تغییر وضعیت: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk activate locations
     */
    public function bulkActivate(Request $request)
    {
        try {
            $ids = $request->input('ids', []);

            if (empty($ids)) {
                return response()->json([
                    'success' => false,
                    'message' => 'هیچ موردی انتخاب نشده است'
                ], 400);
            }

            $updated = Location::whereIn('id', $ids)->update(['is_active' => 1]);

            return response()->json([
                'success' => true,
                'message' => "{$updated} مکان با موفقیت فعال شدند"
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در فعال‌سازی: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk deactivate locations
     */
    public function bulkDeactivate(Request $request)
    {
        try {
            $ids = $request->input('ids', []);

            if (empty($ids)) {
                return response()->json([
                    'success' => false,
                    'message' => 'هیچ موردی انتخاب نشده است'
                ], 400);
            }

            $updated = Location::whereIn('id', $ids)->update(['is_active' => 0]);

            return response()->json([
                'success' => true,
                'message' => "{$updated} مکان با موفقیت غیرفعال شدند"
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در غیرفعال‌سازی: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk delete locations
     */
    public function bulkDelete(Request $request)
    {
        try {
            $ids = $request->input('ids', []);

            if (empty($ids)) {
                return response()->json([
                    'success' => false,
                    'message' => 'هیچ موردی انتخاب نشده است'
                ], 400);
            }

            $deleted = Location::whereIn('id', $ids)->delete();

            return response()->json([
                'success' => true,
                'message' => "{$deleted} مکان با موفقیت حذف شدند"
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در حذف: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Export locations to Excel
     */
    public function exportExcel(Request $request)
    {
        try {
            // Get filtered locations
            $query = Location::with(['categoryRelation', 'province', 'city']);

            // Apply filters if provided
            if ($request->has('category_id') && $request->category_id) {
                $query->where('category_id', $request->category_id);
            }

            if ($request->has('is_active') && $request->is_active !== '') {
                $query->where('is_active', $request->is_active);
            }

            if ($request->has('province_id') && $request->province_id) {
                $query->where('province_id', $request->province_id);
            }

            if ($request->has('city_id') && $request->city_id) {
                $query->where('city_id', $request->city_id);
            }

            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('title', 'like', "%{$search}%")
                        ->orWhere('description', 'like', "%{$search}%")
                        ->orWhere('address', 'like', "%{$search}%");
                });
            }

            if ($request->has('date_from') && $request->date_from) {
                $query->whereDate('created_at', '>=', $request->date_from);
            }

            if ($request->has('date_to') && $request->date_to) {
                $query->whereDate('created_at', '<=', $request->date_to);
            }

            if ($request->has('has_coordinates')) {
                if ($request->has_coordinates == '1') {
                    $query->whereNotNull('lat')->whereNotNull('lng');
                } else {
                    $query->where(function($q) {
                        $q->whereNull('lat')->orWhereNull('lng');
                    });
                }
            }

            $locations = $query->get();

            // Create CSV content with BOM for proper UTF-8 encoding
            $csvContent = "\xEF\xBB\xBF"; // UTF-8 BOM
            $csvContent .= "شناسه,عنوان,دسته‌بندی,وضعیت,استان,شهر,امتیاز,تاریخ ایجاد,مختصات\n";

            foreach ($locations as $location) {
                $csvContent .= sprintf(
                    "%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n",
                    $location->id,
                    str_replace('"', '""', $location->title),
                    str_replace('"', '""', $location->categoryRelation->getTranslatedName(app()->getLocale()) ?? 'بدون دسته‌بندی'),
                    $location->is_active ? 'فعال' : 'غیرفعال',
                    str_replace('"', '""', $location->province->name ?? 'نامشخص'),
                    str_replace('"', '""', $location->city->name ?? 'نامشخص'),
                    $location->star_rating ? $location->star_rating . '/5' : 'بدون امتیاز',
                    \Morilog\Jalali\Jalalian::fromDateTime($location->created_at)->format('Y/m/d H:i'),
                    ($location->lat && $location->lng) ? $location->lat . ',' . $location->lng : 'ندارد'
                );
            }

            // Return CSV file
            return response($csvContent)
                ->header('Content-Type', 'text/csv; charset=UTF-8')
                ->header('Content-Disposition', 'attachment; filename="locations_' . date('Y-m-d') . '.csv"');

        } catch (\Exception $e) {
            return back()->with('error', 'خطا در تولید فایل Excel: ' . $e->getMessage());
        }
    }

    /**
     * Export locations to PDF
     */
    public function exportPDF(Request $request)
    {
        try {
            // Get filtered locations (limit to 1000 for performance)
            $query = Location::with(['categoryRelation', 'province', 'city']);

            // Apply same filters as Excel export
            if ($request->has('category_id') && $request->category_id) {
                $query->where('category_id', $request->category_id);
            }

            if ($request->has('is_active') && $request->is_active !== '') {
                $query->where('is_active', $request->is_active);
            }

            if ($request->has('province_id') && $request->province_id) {
                $query->where('province_id', $request->province_id);
            }

            if ($request->has('city_id') && $request->city_id) {
                $query->where('city_id', $request->city_id);
            }

            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('title', 'like', "%{$search}%")
                        ->orWhere('description', 'like', "%{$search}%")
                        ->orWhere('address', 'like', "%{$search}%");
                });
            }

            $locations = $query->limit(1000)->get();

            // Generate HTML content for PDF
            $html = view('admin.locations.exports.pdf', compact('locations'))->render();

            // For now, return HTML (you can integrate with a PDF library like DomPDF later)
            return response($html)
                ->header('Content-Type', 'text/html; charset=UTF-8')
                ->header('Content-Disposition', 'attachment; filename="locations_' . date('Y-m-d') . '.html"');

        } catch (\Exception $e) {
            return back()->with('error', 'خطا در تولید فایل PDF: ' . $e->getMessage());
        }
    }

    /**
     * Search locations for live search
     */
    public function search(Request $request)
    {
        $query = $request->get('q', '');

        if (strlen($query) < 2) {
            return response()->json(['suggestions' => []]);
        }

        $locations = Location::with('categoryRelation')
            ->where('title', 'like', "%{$query}%")
            ->orWhere('description', 'like', "%{$query}%")
            ->orWhere('address', 'like', "%{$query}%")
            ->limit(10)
            ->get();

        $suggestions = $locations->map(function ($location) {
            return [
                'id' => $location->id,
                'title' => $location->title,
                'category' => $location->categoryRelation->getTranslatedName(app()->getLocale()) ?? 'بدون دسته‌بندی',
                'address' => $location->address ?? ''
            ];
        });

        return response()->json(['suggestions' => $suggestions]);
    }

    /**
     * Get monthly data for chart
     */
    private function getMonthlyData()
    {
        try {
            $monthlyData = [];
            for ($i = 11; $i >= 0; $i--) {
                $date = now()->subMonths($i);
                $count = Location::whereYear('created_at', $date->year)
                    ->whereMonth('created_at', $date->month)
                    ->count();

                $monthlyData[] = [
                    'year' => $date->year,
                    'month' => $date->month,
                    'count' => $count
                ];
            }
            return $monthlyData;
        } catch (\Exception $e) {
            \Log::error('Error getting monthly data: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * Get province data for chart
     */
    private function getProvinceData()
    {
        try {
            return Province::withCount('locations')
                ->orderBy('locations_count', 'desc')
                ->take(10)
                ->get()
                ->map(function($province) {
                    return [
                        'name' => $province->name,
                        'count' => $province->locations_count
                    ];
                })
                ->toArray();
        } catch (\Exception $e) {
            \Log::error('Error getting province data: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * Get rating data for chart
     */
    private function getRatingData()
    {
        try {
            return [
                Location::where('star_rating', 1)->count(),
                Location::where('star_rating', 2)->count(),
                Location::where('star_rating', 3)->count(),
                Location::where('star_rating', 4)->count(),
                Location::where('star_rating', 5)->count()
            ];
        } catch (\Exception $e) {
            \Log::error('Error getting rating data: ' . $e->getMessage());
            return [0, 0, 0, 0, 0];
        }
    }



    /**
     * Show the form for creating a new location
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $categories = Category::all();
        $countries = Country::where('is_active', 1)->orderBy('name')->get();
        $amenityTypes = AmenityType::all();
        $amenities = Amenity::all();
        return view('admin.locations.create', compact('categories', 'countries', 'amenityTypes', 'amenities'));
    }

    /**
     * Store a newly created location in storage
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // اعتبارسنجی ورودی‌ها
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'lat' => 'nullable|numeric',
            'lng' => 'nullable|numeric',
            'open_hours' => 'nullable|string',
            'closing_hours' => 'nullable|string',
            'slogan' => 'nullable|string|max:255',
            'emoji' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:50',
            'url' => 'nullable|string|max:255',
            'address' => 'nullable|string',
            'tags' => 'nullable|string',
            'country_id' => 'nullable|exists:state1_countries,id',
            'province_id' => 'nullable|exists:state2_provinces,id',
            'county_id' => 'nullable|exists:state3_counties,id',
            'district_id' => 'nullable|exists:state4_districts,id',
            'city_id' => 'nullable|exists:state5_cities,id',
            'village_id' => 'nullable|exists:state6_village,id',
            'zone_id' => 'nullable|exists:state7_zone,id',
            'images.*' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:10240',
        ]);

        // فعال‌سازی ثبت کوئری‌ها
        \DB::enableQueryLog();

        // ثبت لاگ از درخواست
        \Log::info('✅ Location create request started', [
            'method' => $request->method(),
            'user_id' => auth()->id(),
            'validated_data' => $validated,
        ]);

        // Generate title_id if not provided
        $titleId = $request->title_id ?? Str::slug($request->title).'-'.time();

        // Process category info
        $category = Category::findOrFail($validated['category_id']);
        \Log::info('✅ Category found', ['category' => $category->toArray()]);

        // Begin transaction
        \DB::beginTransaction();
        \Log::info('✅ Transaction started');

        try {
            // Create new location
            $location = new Location;

            // Set basic fields
            $location->title = $validated['title'];
            $location->title_id = $titleId;
            $location->description = $validated['description'] ?? null;
            $location->category_id = $category->id;
            $location->category = $category->category_key;
            $location->category_fa = $category->category_fa;
            $location->is_active = isset($validated['is_active']) && $validated['is_active'] ? 1 : 0;

            // Set geographic fields
            $location->country_id = $validated['country_id'] ?? null;
            $location->province_id = $validated['province_id'] ?? null;
            $location->county_id = $validated['county_id'] ?? null;
            $location->district_id = $validated['district_id'] ?? null;
            $location->city_id = $validated['city_id'] ?? null;
            $location->village_id = $validated['village_id'] ?? null;
            $location->zone_id = $validated['zone_id'] ?? null;

            // Set contact and additional details
            $location->phone = $validated['phone'] ?? null;
            $location->url = $validated['url'] ?? null;
            $location->open_hours = $validated['open_hours'] ?? null;
            $location->closing_hours = $validated['closing_hours'] ?? null;
            $location->Slogan = $validated['slogan'] ?? null;
            $location->emoji = $validated['emoji'] ?? null;
            $location->address = $validated['address'] ?? null;
            $location->tags = $validated['tags'] ?? null;
            $location->lat = $validated['lat'] ?? null;
            $location->lng = $validated['lng'] ?? null;

            // Log model data before save
            \Log::info('✅ Location model prepared', [
                'attributes' => $location->getAttributes(),
            ]);

            // Handle image uploads
            $images = [];
            if ($request->hasFile('images')) {
                foreach ($request->file('images') as $image) {
                    try {
                        // Validate image
                        if (!$image->isValid()) {
                            \Log::warning('Invalid image file skipped', ['original_name' => $image->getClientOriginalName()]);
                            continue;
                        }

                        $path = $image->store('locations/'.$titleId, 'public');
                        if ($path) {
                            $images[] = $path;
                            \Log::info('Image uploaded successfully', ['path' => $path]);
                        }
                    } catch (\Exception $e) {
                        \Log::error('Failed to upload image', [
                            'error' => $e->getMessage(),
                            'file' => $image->getClientOriginalName()
                        ]);
                    }
                }
            }
            // Store images using the model's custom setter
            $location->images = $images;

            // Temporarily disable model events to test if they are interfering
            \Log::info('Temporarily disabling model events before save');
            $originalDispatcher = \Illuminate\Database\Eloquent\Model::getEventDispatcher();
            \Illuminate\Database\Eloquent\Model::unsetEventDispatcher();

            // Try saving with events disabled
            $saveResult = $location->save();

            // Restore event dispatcher
            \Illuminate\Database\Eloquent\Model::setEventDispatcher($originalDispatcher);

            \Log::info('✅ Location save result: '.($saveResult ? 'success' : 'FAILED'), [
                'location_id' => $location->id ?? null,
            ]);

            // If Eloquent save fails, try direct database insert
            if (! $saveResult) {
                \Log::warning('⚠️ Eloquent save failed, attempting direct DB insert');

                try {
                    $insertData = $location->getAttributes();
                    // Set timestamps manually
                    $now = now();
                    $insertData['created_at'] = $now;
                    $insertData['updated_at'] = $now;

                    // Attempt direct insert
                    $insertId = \DB::table('locations')->insertGetId($insertData);
                    \Log::info('✅ Direct DB insert succeeded', ['new_id' => $insertId]);

                    // Update model with new ID
                    $location->id = $insertId;
                } catch (\Exception $e) {
                    \Log::error('❌ Direct DB insert failed', [
                        'error' => $e->getMessage(),
                        'trace' => $e->getTraceAsString(),
                    ]);
                    throw $e;
                }
            }

            // Handle amenities (using new array format)
            if ($request->has('amenities')) {
                foreach ($request->amenities as $amenityId => $value) {
                    if ($value) {
                        try {
                            LocationAmenity::create([
                                'location_id' => $location->id,
                                'amenity_id' => $amenityId,
                                'value' => is_array($value) ? null : $value,
                            ]);
                            \Log::info('✅ Amenity added', [
                                'amenity_id' => $amenityId,
                                'value' => $value,
                            ]);
                        } catch (\Exception $e) {
                            \Log::warning('⚠️ Failed to add amenity', [
                                'amenity_id' => $amenityId,
                                'error' => $e->getMessage(),
                            ]);
                        }
                    }
                }
            }

            // Handle SEO data
            if ($request->has('meta_title')) {
                try {
                    LocationSeo::create([
                        'location_id' => $location->id,
                        'meta_title' => $request->meta_title,
                        'meta_description' => $request->meta_description,
                        'meta_keywords' => $request->meta_keywords,
                        'og_title' => $request->og_title,
                        'og_description' => $request->og_description,
                    ]);
                    \Log::info('✅ SEO data saved');
                } catch (\Exception $e) {
                    \Log::warning('⚠️ Failed to add SEO data', [
                        'error' => $e->getMessage(),
                    ]);
                }
            }

            // Log queries executed
            \Log::info('✅ DB Queries:', [
                'queries' => \DB::getQueryLog(),
            ]);

            \DB::commit();
            \Log::info('✅ Transaction committed successfully');

            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'مکان با موفقیت ایجاد شد',
                    'redirect' => route('admin.locations.index'),
                ]);
            }

            return redirect()->route('admin.locations.index')
                ->with('success', 'مکان با موفقیت ایجاد شد');

        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error('❌ ERROR in location create', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'خطا در ایجاد مکان: '.$e->getMessage(),
                ], 500);
            }

            return back()->withInput()->withErrors(['error' => 'خطا در ایجاد مکان: '.$e->getMessage()]);
        }
    }

    /**
     * Display the specified location
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $location = Location::with([
            'categoryRelation',
            'locationAmenities.amenity.type',
            'ratings',
            'contents.contentType',
            'seo',
        ])->findOrFail($id);

        return view('admin.locations.show', compact('location'));
    }

    /**
     * Show the form for editing the specified location
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $location = Location::with([
            'locationAmenities.amenity.type',
            'seo',
            'categoryRelation',  // Add category to eager loading
        ])->findOrFail($id);

        $categories = Category::all();
        $parentCategories = Category::whereNull('parent_id')->pluck('category_fa', 'id');
        $countries = Country::where('is_active', 1)->orderBy('name')->pluck('name', 'id');

        // Load provinces based on country
        $provinces = Province::where('country_id', $location->country_id)
            ->where('is_active', 1)
            ->orderBy('name')
            ->pluck('name', 'id');

        // Load counties based on province
        $counties = County::where('province_id', $location->province_id)
            ->where('is_active', 1)
            ->orderBy('name')
            ->pluck('name', 'id');

        // Load districts based on county
        $districts = District::where('county_id', $location->county_id)
            ->where('is_active', 1)
            ->orderBy('name')
            ->pluck('name', 'id');

        // Load cities based on district
        $cities = City::where('district_id', $location->district_id)
            ->where('is_active', 1)
            ->orderBy('name')
            ->pluck('name', 'id');

        // Load villages based on city
        $villages = Village::where('city_id', $location->city_id)
            ->where('is_active', 1)
            ->orderBy('name')
            ->pluck('name', 'id');

        // Load zones based on village
        $zones = Zone::where('village_id', $location->village_id)
            ->where('is_active', 1)
            ->orderBy('name')
            ->pluck('name', 'id');

        $amenityTypes = AmenityType::all();
        $amenities = Amenity::all();

        // Create a lookup of selected amenities for easier access in the view
        $selectedAmenities = $location->locationAmenities->pluck('value', 'amenity_id')->toArray();

        return view('admin.locations.edit', compact(
            'location',
            'categories',
            'parentCategories',
            'countries',
            'provinces',
            'counties',
            'districts',
            'cities',
            'villages',
            'zones',
            'amenityTypes',
            'amenities',
            'selectedAmenities'
        ));
    }

    /**
     * Update the specified location in storage
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Enable query logging
        \DB::enableQueryLog();

        // Log detailed request information
        \Log::info('Location update request started', [
            'location_id' => $id,
            'method' => $request->method(),
            'user_id' => auth()->id(),
            'content_type' => $request->header('Content-Type'),
            'has_file' => $request->hasFile('image'),
            'request_data' => $request->except(['image', '_token']),
        ]);

        // Check for model observers
        try {
            $observers = [];
            $container = app();
            $reflectionService = new \ReflectionClass($container);

            if ($reflectionService->hasProperty('bindings')) {
                $property = $reflectionService->getProperty('bindings');
                $property->setAccessible(true);
                $bindings = $property->getValue($container);

                // Look for observer bindings
                foreach ($bindings as $key => $binding) {
                    if (strpos($key, 'App\\Models\\Location') !== false && strpos($key, 'observer') !== false) {
                        $observers[] = $key;
                    }
                }

                \Log::info('Location model observers found:', [
                    'observers' => $observers,
                ]);
            }
        } catch (\Exception $e) {
            \Log::info('Could not inspect observers: '.$e->getMessage());
        }

        // Log SQL queries to understand what's happening
        \Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
            \Log::info('SQL QUERY: '.$query->sql, [
                'bindings' => $query->bindings,
                'time' => $query->time,
            ]);
        });

        try {
            // Validate the request
            $validator = \Validator::make($request->all(), $this->getValidationRules($id));

            if ($validator->fails()) {
                \Log::warning('Location update validation failed', [
                    'location_id' => $id,
                    'errors' => $validator->errors()->toArray(),
                ]);

                return $this->returnError($validator->errors()->first());
            }

            \Log::info('Location update validation passed', ['location_id' => $id]);

            // Start database transaction
            \Log::info('Starting DB transaction for location update', ['location_id' => $id]);
            \DB::beginTransaction();

            try {
                // Find the location
                $location = Location::findOrFail($id);
                \Log::info('Location found for update', [
                    'location_id' => $id,
                    'original_attributes' => $location->getOriginal(),
                ]);

                // Store original values for logging changes
                $originalData = $location->getAttributes();

                // Fill the model with request data except specific fields
                $location->fill($request->except([
                    'image', 'amenities', 'categories',
                    'seo_title', 'seo_description', 'seo_keywords',
                ]));

                // Check for changes
                $changes = array_diff_assoc($location->getDirty(), $originalData);
                \Log::info('Location attributes updated', [
                    'location_id' => $id,
                    'changes' => $changes,
                    'dirty_attributes' => $location->getDirty(),
                ]);

                // Update coordinates if provided
                if ($request->filled('lat') && $request->filled('long')) {
                    $location->lat = $request->lat;
                    $location->long = $request->long;
                    \Log::info('Location coordinates updated', [
                        'location_id' => $id,
                        'lat' => $request->lat,
                        'long' => $request->long,
                    ]);
                }

                // Handle image removal first
                $currentImages = $location->images_array;
                if ($request->has('remove_images') && is_array($request->remove_images)) {
                    \Log::info('Processing image removals for location', [
                        'location_id' => $id,
                        'images_to_remove' => $request->remove_images
                    ]);

                    foreach ($request->remove_images as $imageToRemove) {
                        // Remove from storage
                        try {
                            \Storage::disk('public')->delete($imageToRemove);
                            \Log::info('Image file deleted from storage', ['path' => $imageToRemove]);
                        } catch (\Exception $e) {
                            \Log::warning('Failed to delete image file from storage', [
                                'path' => $imageToRemove,
                                'error' => $e->getMessage()
                            ]);
                        }

                        // Remove from array
                        $currentImages = array_filter($currentImages, function($image) use ($imageToRemove) {
                            return $image !== $imageToRemove;
                        });
                    }

                    // Update the location with remaining images
                    $location->images = array_values($currentImages);
                    \Log::info('Images removed from location', [
                        'location_id' => $id,
                        'remaining_images' => count($currentImages)
                    ]);
                }

                // Handle image uploads (multiple images)
                if ($request->hasFile('images')) {
                    \Log::info('Processing image uploads for location', ['location_id' => $id]);
                    try {
                        $newImages = [];

                        foreach ($request->file('images') as $image) {
                            try {
                                // Validate image
                                if (!$image->isValid()) {
                                    \Log::warning('Invalid image file skipped', ['original_name' => $image->getClientOriginalName()]);
                                    continue;
                                }

                                $path = $image->store('locations/'.$location->title_id, 'public');
                                if ($path) {
                                    $newImages[] = $path;
                                    \Log::info('Image uploaded successfully', ['path' => $path]);
                                }
                            } catch (\Exception $e) {
                                \Log::error('Failed to upload individual image', [
                                    'error' => $e->getMessage(),
                                    'file' => $image->getClientOriginalName()
                                ]);
                            }
                        }

                        // Merge with existing images (after removals)
                        $allImages = array_merge($currentImages, $newImages);
                        $location->images = $allImages;

                        \Log::info('Images updated for location', [
                            'location_id' => $id,
                            'total_images' => count($allImages),
                        ]);
                    } catch (\Exception $e) {
                        \Log::error('Error processing image uploads', [
                            'location_id' => $id,
                            'error' => $e->getMessage(),
                            'trace' => $e->getTraceAsString(),
                        ]);
                    }
                }

                // Log what we're about to save
                \Log::info('About to save location with data:', [
                    'location_id' => $location->id,
                    'dirty_attributes' => $location->getDirty(),
                    'attributes' => $location->getAttributes(),
                ]);

                // Temporarily disable model events to test if they are interfering
                \Log::info('Temporarily disabling model events before save');
                $originalDispatcher = \Illuminate\Database\Eloquent\Model::getEventDispatcher();
                \Illuminate\Database\Eloquent\Model::unsetEventDispatcher();

                // Try saving with events disabled
                $saved = $location->save();

                // Restore event dispatcher
                \Illuminate\Database\Eloquent\Model::setEventDispatcher($originalDispatcher);

                \Log::info('Model events restored. Location save result: '.($saved ? 'success' : 'failed'));

                // If Eloquent save fails, try direct database update as fallback
                if (! $saved) {
                    \Log::warning('Eloquent save failed, attempting direct DB update');
                    try {
                        // Enable detailed database debugging
                        \DB::connection()->enableQueryLog();
                        \DB::listen(function ($query) {
                            \Log::alert('QUERY: '.$query->sql, [
                                'bindings' => $query->bindings,
                                'time' => $query->time,
                                'connection' => $query->connectionName,
                            ]);
                        });

                        // For existing records
                        if ($location->exists) {
                            // Get the raw attributes for logging
                            $rawAttributes = $location->getAttributes();
                            $dirtyFields = $location->getDirty();

                            \Log::info('Attempting direct update with fields:', [
                                'table' => $location->getTable(),
                                'primary_key' => $location->getKeyName(),
                                'id' => $location->getKey(),
                                'dirty_fields' => $dirtyFields,
                                'timestamps_enabled' => $location->timestamps,
                            ]);

                            // Manually create update query to gain more control
                            $updated = \DB::table('locations')
                                ->where('id', $location->id)
                                ->update($location->getDirty());
                            \Log::info("Direct DB update result: {$updated}");

                            // Verify the update
                            $verifyRecord = \DB::table('locations')->where('id', $location->id)->first();
                            \Log::info('Verification query result:', [
                                'record_exists' => $verifyRecord ? 'yes' : 'no',
                                'record_data' => $verifyRecord ? json_encode($verifyRecord) : 'null',
                            ]);

                            // If the DB update failed, try PDO directly
                            if (! $updated) {
                                \Log::alert('DB::table update failed, attempting direct PDO query');
                                try {
                                    $pdo = \DB::connection()->getPdo();

                                    // Manually build a PDO query
                                    $dirtyColumns = array_keys($location->getDirty());
                                    $sets = [];
                                    $bindings = [];

                                    foreach ($dirtyColumns as $column) {
                                        $sets[] = "`$column` = ?";
                                        $bindings[] = $location->getAttribute($column);
                                    }

                                    // Add updated_at timestamp
                                    if ($location->timestamps) {
                                        $sets[] = '`updated_at` = ?';
                                        $bindings[] = now()->format('Y-m-d H:i:s');
                                    }

                                    $setClause = implode(', ', $sets);
                                    $sql = "UPDATE `locations` SET $setClause WHERE `id` = ?";
                                    $bindings[] = $location->id;

                                    \Log::alert('Executing raw PDO query', [
                                        'sql' => $sql,
                                        'bindings' => $bindings,
                                    ]);

                                    $statement = $pdo->prepare($sql);
                                    $result = $statement->execute($bindings);
                                    $rowCount = $statement->rowCount();

                                    \Log::alert('PDO direct query result', [
                                        'success' => $result ? 'true' : 'false',
                                        'rows_affected' => $rowCount,
                                    ]);
                                } catch (\PDOException $e) {
                                    \Log::alert('PDO direct query failed', [
                                        'error' => $e->getMessage(),
                                        'code' => $e->getCode(),
                                    ]);
                                }
                            }
                        }
                        // For new records
                        else {
                            $insertId = \DB::table('locations')->insertGetId($location->getAttributes());
                            $location->id = $insertId;
                            \Log::info("Direct DB insert result: {$insertId}");
                        }
                    } catch (\Exception $e) {
                        \Log::error('Direct DB operation failed', [
                            'exception' => $e->getMessage(),
                            'trace' => $e->getTraceAsString(),
                        ]);
                        throw $e;
                    }
                }

                // Log the query log after save operation
                \Log::info('DB queries executed:', [
                    'queries' => \DB::getQueryLog(),
                ]);

                // Handle amenities
                if ($request->has('amenities')) {
                    \Log::info('Processing amenities for location', [
                        'location_id' => $id,
                        'amenities' => $request->amenities,
                    ]);

                    try {
                        $location->amenities()->sync($request->amenities);
                        \Log::info('Amenities synced for location', [
                            'location_id' => $id,
                            'amenities_count' => count($request->amenities),
                        ]);
                    } catch (\Exception $e) {
                        \Log::error('Error syncing amenities', [
                            'location_id' => $id,
                            'error' => $e->getMessage(),
                            'trace' => $e->getTraceAsString(),
                        ]);
                    }
                }

                // Handle categories
                if ($request->has('categories')) {
                    \Log::info('Processing categories for location', [
                        'location_id' => $id,
                        'categories' => $request->categories,
                    ]);

                    try {
                        $location->categories()->sync($request->categories);
                        \Log::info('Categories synced for location', [
                            'location_id' => $id,
                            'categories_count' => count($request->categories),
                        ]);
                    } catch (\Exception $e) {
                        \Log::error('Error syncing categories', [
                            'location_id' => $id,
                            'error' => $e->getMessage(),
                            'trace' => $e->getTraceAsString(),
                        ]);
                    }
                }

                // Handle SEO data
                if ($request->filled('seo_title') || $request->filled('seo_description') || $request->filled('seo_keywords')) {
                    \Log::info('Processing SEO data for location', [
                        'location_id' => $id,
                        'seo_data' => $request->only(['seo_title', 'seo_description', 'seo_keywords']),
                    ]);

                    try {
                        $seo = $location->seo ?? new LocationSeo;
                        $seo->location_id = $location->id;
                        $seo->title = $request->seo_title;
                        $seo->description = $request->seo_description;
                        $seo->keywords = $request->seo_keywords;
                        $seo->save();

                        \Log::info('SEO data saved for location', [
                            'location_id' => $id,
                            'seo_id' => $seo->id,
                        ]);
                    } catch (\Exception $e) {
                        \Log::error('Error saving SEO data', [
                            'location_id' => $id,
                            'error' => $e->getMessage(),
                            'trace' => $e->getTraceAsString(),
                        ]);
                    }
                }

                // Verify changes were saved to the database
                $freshLocation = Location::find($id);
                \Log::info('Verifying location update in database', [
                    'location_id' => $id,
                    'fresh_attributes' => $freshLocation ? $freshLocation->getAttributes() : 'Location not found',
                    'expected_attributes' => $location->getAttributes(),
                    'verification_result' => $freshLocation && $freshLocation->getAttributes() == $location->getAttributes()
                        ? 'Success'
                        : 'Failed to verify changes',
                ]);

                // Commit the transaction
                \DB::commit();
                \Log::info('DB transaction committed for location update', ['location_id' => $id]);

                if ($request->ajax()) {
                    return response()->json([
                        'success' => true,
                        'message' => 'Location updated successfully',
                    ]);
                }

                return redirect()->route('admin.locations.index')
                    ->with('success', 'Location updated successfully');

            } catch (\Exception $e) {
                // Rollback the transaction in case of error
                \DB::rollBack();
                \Log::error('Error in location update transaction', [
                    'location_id' => $id,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString(),
                ]);

                return $this->returnError('Error updating location: '.$e->getMessage());
            }
        } catch (\Exception $e) {
            \Log::error('Unexpected error in location update', [
                'location_id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return $this->returnError('Unexpected error: '.$e->getMessage());
        }
    }

    /**
     * Remove the specified location from storage
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $location = Location::findOrFail($id);

        // Begin transaction
        DB::beginTransaction();

        try {
            // Delete all related records
            LocationAmenity::where('location_id', $id)->delete();
            LocationSeo::where('location_id', $id)->delete();

            // Delete images
            if (! empty($location->images)) {
                foreach ($location->images as $image) {
                    Storage::disk('public')->delete($image);
                }
            }

            // Delete the location
            $location->delete();

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'مکان با موفقیت حذف شد',
            ]);

        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json([
                'success' => false,
                'message' => 'خطا در حذف مکان: '.$e->getMessage(),
            ], 500);
        }
    }

    /**
     * Toggle active status of a location
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function toggleActive($id)
    {
        $location = Location::findOrFail($id);
        $location->is_active = ! $location->is_active;
        $location->save();

        return response()->json([
            'success' => true,
            'message' => $location->is_active ? 'مکان فعال شد' : 'مکان غیرفعال شد',
            'is_active' => $location->is_active,
        ]);
    }

    /**
     * Get locations data for dynamic selects via AJAX
     *
     * @return \Illuminate\Http\Response
     */
    public function getLocationsForSelect(Request $request)
    {
        $query = Location::query();

        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                    ->orWhere('title_id', 'like', "%{$search}%");
            });
        }

        if ($request->has('category') && $request->category) {
            $query->where('category', $request->category);
        }

        $locations = $query->select('id', 'title', 'title_id')
            ->where('is_active', 1)
            ->orderBy('title')
            ->limit(20)
            ->get();

        $results = $locations->map(function ($location) {
            return [
                'id' => $location->id,
                'text' => $location->title,
                'title_id' => $location->title_id,
            ];
        });

        return response()->json(['results' => $results]);
    }

    /**
     * Direct test update method to debug issues
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function directUpdate($id)
    {
        \Log::alert("⭐ DIRECT UPDATE TEST STARTED for Location ID: $id");

        try {
            // Test database connection first
            try {
                $pdo = \DB::connection()->getPdo();
                \Log::alert('✅ Database connection successful');
                \Log::alert('Database name: '.\DB::connection()->getDatabaseName());
                \Log::alert('Database driver: '.\DB::connection()->getDriverName());

                // Check database configuration
                $config = \DB::connection()->getConfig();
                \Log::alert('Database config: '.json_encode(array_diff_key($config, array_flip(['password']))));
            } catch (\Exception $e) {
                \Log::alert('⚠️ Database connection FAILED: '.$e->getMessage());

                return redirect()->back()->with('error', 'Database connection failed: '.$e->getMessage());
            }

            // Get the location
            $location = Location::find($id);
            if (! $location) {
                \Log::alert("⚠️ Location ID: $id NOT FOUND");

                return redirect()->back()->with('error', 'Location not found');
            }

            \Log::alert("✅ Location found: ID=$id, Title={$location->title}");
            \Log::alert('Location attributes: '.json_encode($location->getAttributes()));

            // Verify model is working correctly
            \Log::alert('Location is dirty before changes: '.($location->isDirty() ? 'YES' : 'NO'));

            // Update title with timestamp for tracking
            $newTitle = $location->title.' - Direct Update at '.now()->format('H:i:s');
            $oldTitle = $location->title;
            $location->title = $newTitle;

            \Log::alert('Is dirty after title change: '.($location->isDirty() ? 'YES' : 'NO'));
            \Log::alert('Changed attributes: '.json_encode($location->getDirty()));
            \Log::alert("Attempting to save with new title: $newTitle");

            // Test with Eloquent save - add tracking details to error logs
            $saveStartTime = microtime(true);
            $saveResult = $location->save();
            $saveEndTime = microtime(true);
            $saveTime = round(($saveEndTime - $saveStartTime) * 1000, 2);

            \Log::alert('Eloquent save() result: '.($saveResult ? 'TRUE ✅' : 'FALSE ❌')." (took {$saveTime}ms)");

            // Reload the model to verify persistence
            $reloadedLocation = Location::find($id);
            \Log::alert('Reloaded location title: '.($reloadedLocation ? $reloadedLocation->title : 'LOCATION NOT FOUND'));
            \Log::alert("Title changed from '$oldTitle' to '{$reloadedLocation->title}'");

            if (! $saveResult || $reloadedLocation->title !== $newTitle) {
                // Try direct database update as fallback
                \Log::alert('Eloquent save verification failed, trying direct DB update');

                // Query builder update with detailed error logging
                try {
                    $dbUpdateResult = \DB::table('locations')
                        ->where('id', $id)
                        ->update(['title' => $newTitle.' (DB direct)', 'updated_at' => now()]);

                    \Log::alert('Direct DB update result: '.($dbUpdateResult ? "SUCCESS ($dbUpdateResult rows)" : 'FAILED (0 rows)'));

                    // Verify the direct update
                    $verifyUpdate = \DB::table('locations')->where('id', $id)->first();
                    \Log::alert('Direct DB verification: '.($verifyUpdate ? "Title: {$verifyUpdate->title}" : 'FAILED - record not found'));

                    if ($dbUpdateResult) {
                        return redirect()->back()->with('success', 'Location updated directly through DB: '.$newTitle.' (DB direct)');
                    }
                } catch (\Exception $e) {
                    \Log::alert('DB::table update exception: '.$e->getMessage());
                }

                // Check permissions and table structure
                \Log::alert('Checking database permissions and table structure');
                try {
                    $tableInfo = \DB::select('SHOW COLUMNS FROM locations');
                    \Log::alert('Table columns exist: '.json_encode(array_column($tableInfo, 'Field')));
                } catch (\Exception $e) {
                    \Log::alert('Cannot view table structure: '.$e->getMessage());
                }

                try {
                    $privileges = \DB::select('SHOW GRANTS FOR CURRENT_USER()');
                    \Log::alert('Current user privileges: '.json_encode($privileges));
                } catch (\Exception $e) {
                    \Log::alert('Cannot view privileges: '.$e->getMessage());
                }

                // Try raw SQL as last resort
                try {
                    $rawSql = 'UPDATE locations SET title = ?, updated_at = ? WHERE id = ?';
                    $params = [$newTitle.' (Raw SQL)', now(), $id];
                    \Log::alert('Attempting raw SQL update: '.$rawSql.' with params: '.json_encode($params));

                    $rawResult = \DB::statement($rawSql, $params);
                    \Log::alert('Raw SQL update result: '.($rawResult ? 'SUCCESS' : 'FAILED'));

                    if ($rawResult) {
                        return redirect()->back()->with('success', 'Location updated with raw SQL: '.$newTitle.' (Raw SQL)');
                    }
                } catch (\Exception $e) {
                    \Log::alert('Raw SQL exception: '.$e->getMessage());
                }

                return redirect()->back()->with('error', 'All update methods failed. See logs for details.');
            }

            return redirect()->back()->with('success', 'Location updated successfully: '.$newTitle);

        } catch (\Exception $e) {
            \Log::alert('⚠️ EXCEPTION in directUpdate: '.$e->getMessage());
            \Log::alert('Stack trace: '.$e->getTraceAsString());

            return redirect()->back()->with('error', 'Update failed: '.$e->getMessage());
        }
    }

    /**
     * Get cities by province ID
     *
     * @param  int  $provinceId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCitiesByProvince($provinceId)
    {
        $cities = City::where('province_id', $provinceId)
            ->where('is_active', true)
            ->orderBy('name')
            ->get(['id', 'name']);

        return response()->json($cities);
    }

    private function getValidationRules($id = null)
    {
        return [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'address' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'website' => 'nullable|url|max:255',
            'lat' => 'nullable|numeric',
            'long' => 'nullable|numeric',
            'is_active' => 'boolean',
            'category_id' => 'required|exists:categories,id',
            'amenities' => 'nullable|array',
            'amenities.*' => 'exists:amenities,id',
            'images.*' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:10240',
            'remove_images' => 'nullable|array',
            'remove_images.*' => 'nullable|string',
            'Slogan' => 'nullable|string|max:255',
            'seo_title' => 'nullable|string|max:255',
            'seo_description' => 'nullable|string',
            'seo_keywords' => 'nullable|string',
            'package_type' => 'nullable|string|in:regular,bronze,silver,gold,diamond',
            'package_expires_at' => 'nullable|date|after_or_equal:today',
        ];
    }

    private function returnError($message)
    {
        if (request()->ajax()) {
            return response()->json(['success' => false, 'message' => $message], 422);
        }

        return redirect()->back()->with('error', $message)->withInput();
    }

    /**
     * Simple update method - bypasses most Laravel features for debugging
     */
    public function simpleUpdate($id, Request $request)
    {
        \Log::alert("🔥 SIMPLE UPDATE TEST STARTED for Location ID: $id");

        try {
            // Log the request data
            \Log::alert('Request data:', [
                'method' => $request->method(),
                'all_data' => $request->all(),
                'has_token' => $request->has('_token'),
                'token' => $request->input('_token'),
            ]);

            // Verify database connection and permissions first
            try {
                $pdo = \DB::connection()->getPdo();
                \Log::alert('✅ Database connection successful');
                \Log::alert('Database name: '.\DB::connection()->getDatabaseName());

                // Check if the user has necessary privileges
                $stmt = $pdo->prepare('SHOW GRANTS FOR CURRENT_USER');
                $stmt->execute();
                $grants = $stmt->fetchAll(\PDO::FETCH_COLUMN);
                \Log::alert('Database permissions:', $grants);

                // Check write access by trying a harmless temp table
                try {
                    $tempTableName = 'temp_write_test_'.time();
                    $pdo->exec("CREATE TEMPORARY TABLE {$tempTableName} (id INT)");
                    $pdo->exec("INSERT INTO {$tempTableName} VALUES (1)");
                    $pdo->exec("DROP TEMPORARY TABLE IF EXISTS {$tempTableName}");
                    \Log::alert('✅ Write permissions confirmed - able to create temp table');
                } catch (\Exception $e) {
                    \Log::alert('⚠️ Could not verify write permissions: '.$e->getMessage());
                }

                // Check locations table structure
                $stmt = $pdo->prepare('DESCRIBE locations');
                $stmt->execute();
                $columns = $stmt->fetchAll(\PDO::FETCH_ASSOC);
                $columnNames = array_column($columns, 'Field');
                \Log::alert("Table structure for 'locations':", $columnNames);

            } catch (\Exception $e) {
                \Log::alert('⚠️ Database connection or permission check failed: '.$e->getMessage());

                return redirect()->back()->with('error', 'خطا در اتصال به دیتابیس: '.$e->getMessage());
            }

            // Try 3 different update methods

            // Method 1: Raw PDO - most direct
            try {
                \Log::alert('Attempting method 1: Raw PDO');
                $title = $request->input('title').' [RAW PDO]';
                $stmt = $pdo->prepare('UPDATE locations SET title = ?, updated_at = NOW() WHERE id = ?');
                $result = $stmt->execute([$title, $id]);
                $rowCount = $stmt->rowCount();

                \Log::alert('PDO RESULT:', [
                    'success' => $result ? 'YES' : 'NO',
                    'rows_affected' => $rowCount,
                ]);

                if ($rowCount > 0) {
                    return redirect()->back()->with('success', "آپدیت با متد PDO انجام شد: $title");
                }
            } catch (\Exception $e) {
                \Log::alert('PDO ERROR: '.$e->getMessage());
                // continue to next method
            }

            // Method 2: DB Facade
            try {
                \Log::alert('Attempting method 2: DB Facade');
                $title = $request->input('title').' [DB Facade]';
                $result = \DB::table('locations')
                    ->where('id', $id)
                    ->update([
                        'title' => $title,
                        'updated_at' => now(),
                    ]);

                \Log::alert('DB RESULT:', [
                    'rows_affected' => $result,
                ]);

                if ($result > 0) {
                    return redirect()->back()->with('success', "آپدیت با متد DB انجام شد: $title");
                }
            } catch (\Exception $e) {
                \Log::alert('DB ERROR: '.$e->getMessage());
                // continue to next method
            }

            // Method 3: Basic Eloquent
            try {
                \Log::alert('Attempting method 3: Eloquent without events');
                $title = $request->input('title').' [Eloquent]';

                // Unset global dispatcher first
                $originalDispatcher = \Illuminate\Database\Eloquent\Model::getEventDispatcher();
                \Illuminate\Database\Eloquent\Model::unsetEventDispatcher();

                $location = \App\Models\Location::find($id);
                $location->title = $title;
                $result = $location->save();

                // Restore dispatcher
                \Illuminate\Database\Eloquent\Model::setEventDispatcher($originalDispatcher);

                \Log::alert('ELOQUENT RESULT:', [
                    'success' => $result ? 'YES' : 'NO',
                ]);

                if ($result) {
                    return redirect()->back()->with('success', "آپدیت با متد Eloquent انجام شد: $title");
                }
            } catch (\Exception $e) {
                \Log::alert('ELOQUENT ERROR: '.$e->getMessage());
            }

            return redirect()->back()
                ->with('error', 'همه متدها شکست خوردند. لطفاً لاگ‌ها را بررسی کنید.');

        } catch (\Exception $e) {
            \Log::alert('CRITICAL ERROR: '.$e->getMessage());
            \Log::alert($e->getTraceAsString());

            return redirect()->back()
                ->with('error', 'خطای بحرانی: '.$e->getMessage());
        }
    }
}
