<?php

namespace App\Http\Controllers;

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

class CountryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = Country::query();

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

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

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

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

            return response()->json([
                'success' => true,
                'data' => $countries->items(),
                'pagination' => [
                    'current_page' => $countries->currentPage(),
                    'per_page' => $countries->perPage(),
                    'total' => $countries->total(),
                    'last_page' => $countries->lastPage(),
                ]
            ]);

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

    /**
 * Get all countries for dropdown (without pagination)
 */
public function getAllForDropdown(Request $request): JsonResponse
{
    try {
        $query = Country::query();

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

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

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

        $countries = $query->orderBy($orderBy, $orderDirection)
                          ->get(['country_id', 'country_code', 'country_name', 'is_active']);

        return response()->json([
            'success' => true,
            'data' => $countries,
            'total' => $countries->count()
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch countries for dropdown',
            '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_code' => 'required|string|max:5|unique:countries,country_code',
                'country_name' => 'required|string|max:100',
                'is_active' => 'boolean'
            ]);

            $country = Country::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Country created successfully',
                'data' => $country
            ], 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 country',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        try {
            $country = Country::find($id);

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

            return response()->json([
                'success' => true,
                'data' => $country
            ]);

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

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

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

            $validated = $request->validate([
                'country_code' => 'sometimes|string|max:5|unique:countries,country_code,' . $id . ',country_id',
                'country_name' => 'sometimes|string|max:100',
                'is_active' => 'boolean'
            ]);

            $country->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Country updated successfully',
                'data' => $country
            ]);

        } 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 country',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

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

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

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

            $country->delete();

            return response()->json([
                'success' => true,
                'message' => 'Country deleted successfully'
            ]);

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

    /**
     * Get country by code
     */
    public function getByCode(string $code): JsonResponse
    {
        try {
            $country = Country::where('country_code', $code)->first();

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

            return response()->json([
                'success' => true,
                'data' => $country
            ]);

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