<?php

namespace App\Http\Controllers;

use App\Models\Province;
use App\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class ProvinceController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = Province::with('country');

            // Filter by country
            if ($request->has('country_id')) {
                $query->byCountry($request->get('country_id'));
            }

            // Filter by active status
            if ($request->has('active_only') && $request->boolean('active_only')) {
                $query->active();
            }

            // Search by province name or code
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->where('province_name', 'like', "%{$search}%")
                        ->orWhere('province_code', 'like', "%{$search}%");
                });
            }

            // Order by
            $orderBy = $request->get('order_by', 'province_name');
            $orderDirection = $request->get('order_direction', 'asc');
            $query->orderBy($orderBy, $orderDirection);

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

            return response()->json([
                'success' => true,
                'data' => $provinces->items(),
                'pagination' => [
                    'current_page' => $provinces->currentPage(),
                    'per_page' => $provinces->perPage(),
                    'total' => $provinces->total(),
                    'last_page' => $provinces->lastPage(),
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch provinces',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }


    /**
 * Get provinces for dropdown
 */
public function dropdownList(Request $request): JsonResponse
{
    try {
        $query = Province::select('province_id', 'province_name', 'province_code', 'country_id')
            ->with(['country:country_id,country_name'])
            ->where('is_active', true);

        // Filter by country - IMPORTANT: yeh fix karein
        if ($request->has('country_id') && $request->country_id) {
            $query->where('country_id', $request->country_id);
        }

        // Search by province name
        if ($request->has('search') && $request->search) {
            $query->where('province_name', 'like', "%{$request->search}%");
        }

        $provinces = $query->orderBy('province_name', 'asc')
            ->get()
            ->map(function ($province) {
                return [
                    'id' => $province->province_id,
                    'name' => $province->province_name,
                    'code' => $province->province_code,
                    'country_name' => $province->country->country_name ?? 'N/A'
                ];
            });

        return response()->json([
            'success' => true,
            'data' => $provinces,
            'total' => $provinces->count()
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch provinces dropdown list',
            'error' => config('app.debug') ? $e->getMessage() : null
        ], 500);
    }
}

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'country_id' => 'required|exists:countries,country_id',
                'province_code' => 'required|string|max:10',
                'province_name' => 'required|string|max:100',
                'is_active' => 'boolean'
            ]);

            // Check unique province code within country
            $exists = Province::where('country_id', $validated['country_id'])
                ->where('province_code', $validated['province_code'])
                ->exists();

            if ($exists) {
                return response()->json([
                    'success' => false,
                    'message' => 'Province code already exists for this country'
                ], 422);
            }

            $province = Province::create($validated);
            $province->load('country');

            return response()->json([
                'success' => true,
                'message' => 'Province created successfully',
                'data' => $province
            ], 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create province',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        try {
            $province = Province::with('country', 'cities')->find($id);

            if (!$province) {
                return response()->json([
                    'success' => false,
                    'message' => 'Province not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $province
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch province',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $province = Province::find($id);

            if (!$province) {
                return response()->json([
                    'success' => false,
                    'message' => 'Province not found'
                ], 404);
            }

            $validated = $request->validate([
                'country_id' => 'sometimes|exists:countries,country_id',
                'province_code' => 'sometimes|string|max:10',
                'province_name' => 'sometimes|string|max:100',
                'is_active' => 'boolean'
            ]);

            // Check unique province code within country if province_code is being updated
            if (isset($validated['province_code'])) {
                $countryId = $validated['country_id'] ?? $province->country_id;
                $exists = Province::where('country_id', $countryId)
                    ->where('province_code', $validated['province_code'])
                    ->where('province_id', '!=', $id)
                    ->exists();

                if ($exists) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Province code already exists for this country'
                    ], 422);
                }
            }

            $province->update($validated);
            $province->load('country');

            return response()->json([
                'success' => true,
                'message' => 'Province updated successfully',
                'data' => $province
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update province',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $province = Province::find($id);

            if (!$province) {
                return response()->json([
                    'success' => false,
                    'message' => 'Province not found'
                ], 404);
            }

            // Check if province has cities
            if ($province->cities()->exists()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot delete province with associated cities'
                ], 422);
            }

            $province->delete();

            return response()->json([
                'success' => true,
                'message' => 'Province deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete province',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get provinces by country
     */
    public function getByCountry(string $countryId): JsonResponse
    {
        try {
            $country = Country::find($countryId);

            if (!$country) {
                return response()->json([
                    'success' => false,
                    'message' => 'Country not found'
                ], 404);
            }

            $provinces = Province::with('cities')
                ->where('country_id', $countryId)
                ->active()
                ->orderBy('province_name')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $provinces,
                'country' => $country
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch provinces',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get province by code and country
     */
    public function getByCode(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'code' => 'required|string',
                'country_id' => 'required|exists:countries,country_id'
            ]);

            $province = Province::with('country')
                ->where('province_code', $request->code)
                ->where('country_id', $request->country_id)
                ->first();

            if (!$province) {
                return response()->json([
                    'success' => false,
                    'message' => 'Province not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $province
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch province',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
