<?php

namespace App\Http\Controllers\API\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Traits\ApiResponse;
use App\Models\City;
use App\Models\Zone;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class ZoneController extends Controller
{
    use ApiResponse;

    /**
     * عرض قائمة المناطق
     */
    public function index(Request $request)
    {
        $query = Zone::with(['city'])->withCount(['users']);

        // البحث
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name_ar', 'like', "%{$search}%")
                  ->orWhere('name_en', 'like', "%{$search}%");
            });
        }

        // التصفية حسب المدينة
        if ($request->has('city_id')) {
            $query->where('city_id', $request->city_id);
        }

        // الترتيب
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        
        // السماح بالترتيب حسب name
        if ($sortBy === 'name') {
            $query->orderBy('name_ar', $sortOrder);
        } else {
            $query->orderBy($sortBy, $sortOrder);
        }

        // Pagination
        $perPage = $request->get('per_page', 15);
        $zones = $query->paginate($perPage);

        return $this->successResponse($zones, __('messages.zones_listed'));
    }

    /**
     * إنشاء منطقة جديدة
     */
    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'name_ar' => 'required|string|max:255',
                'name_en' => 'required|string|max:255',
                'city_id' => 'required|exists:cities,id',
            ]);
        } catch (ValidationException $e) {
            return $this->validationErrorResponse($e->errors());
        }

        // التحقق من عدم وجود منطقة بنفس الاسم في نفس المدينة
        $existingZone = Zone::where('city_id', $request->city_id)
            ->where(function($q) use ($request) {
                $q->where('name_ar', $request->name_ar)
                  ->orWhere('name_en', $request->name_en);
            })
            ->first();

        if ($existingZone) {
            return $this->errorResponse(__('messages.zone_already_exists'), 409);
        }

        $zone = Zone::create([
            'name_ar' => $request->name_ar,
            'name_en' => $request->name_en,
            'city_id' => $request->city_id,
        ]);

        return $this->successResponse([
            'zone' => $zone->load('city'),
        ], __('messages.zone_created'));
    }

    /**
     * عرض منطقة محددة
     */
    public function show($id)
    {
        $zone = Zone::with(['city', 'users'])->withCount(['users'])->find($id);

        if (!$zone) {
            return $this->notFoundResponse(__('messages.zone_not_found'));
        }

        return $this->successResponse($zone, __('messages.zone_retrieved'));
    }

    /**
     * تحديث منطقة
     */
    public function update(Request $request, $id)
    {
        $zone = Zone::find($id);

        if (!$zone) {
            return $this->notFoundResponse(__('messages.zone_not_found'));
        }

        try {
            $validated = $request->validate([
                'name_ar' => 'sometimes|required|string|max:255',
                'name_en' => 'sometimes|required|string|max:255',
                'city_id' => 'sometimes|required|exists:cities,id',
            ]);
        } catch (ValidationException $e) {
            return $this->validationErrorResponse($e->errors());
        }

        // التحقق من عدم وجود منطقة أخرى بنفس الاسم في نفس المدينة
        $cityId = $request->has('city_id') ? $request->city_id : $zone->city_id;
        
        if ($request->has('name_ar') || $request->has('name_en')) {
            $existingZone = Zone::where('city_id', $cityId)
                ->where(function($q) use ($request, $zone) {
                    if ($request->has('name_ar')) {
                        $q->where('name_ar', $request->name_ar);
                    }
                    if ($request->has('name_en')) {
                        $q->orWhere('name_en', $request->name_en);
                    }
                })
                ->where('id', '!=', $id)
                ->first();

            if ($existingZone) {
                return $this->errorResponse(__('messages.zone_already_exists'), 409);
            }
        }

        $zone->update($request->only(['name_ar', 'name_en', 'city_id']));

        return $this->successResponse([
            'zone' => $zone->load(['city', 'users'])->loadCount(['users']),
        ], __('messages.zone_updated'));
    }

    /**
     * حذف منطقة
     */
    public function destroy($id)
    {
        $zone = Zone::withCount(['users'])->find($id);

        if (!$zone) {
            return $this->notFoundResponse(__('messages.zone_not_found'));
        }

        // التحقق من وجود مستخدمين مرتبطين
        if ($zone->users_count > 0) {
            return $this->errorResponse(__('messages.zone_has_users'), 400);
        }

        $zone->delete();

        return $this->successResponse(null, __('messages.zone_deleted'));
    }

    /**
     * الحصول على مناطق مدينة محددة
     */
    public function getByCity($cityId)
    {
        $city = City::find($cityId);

        if (!$city) {
            return $this->notFoundResponse(__('messages.city_not_found'));
        }

        $zones = Zone::where('city_id', $cityId)
            ->orderBy('name_ar')
            ->get();

        return $this->successResponse([
            'city' => $city,
            'zones' => $zones,
        ], __('messages.zones_listed'));
    }
}
