<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ServiceController extends Controller
{
    /**
     * Display a listing of the services.
     */
    public function index()
    {
        $services = Service::with('country')->ordered()->paginate(20);
        $countries = Country::active()->ordered()->get();
        
        return view('admin.services.index', compact('services', 'countries'));
    }

    /**
     * Show the form for creating a new service.
     */
    public function create()
    {
        $countries = Country::active()->ordered()->get();
        return view('admin.services.create', compact('countries'));
    }

    /**
     * Store a newly created service in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:services,name',
            'price' => 'required|integer|min:0',
            'country_id' => 'nullable|exists:countries,id',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean'
        ]);

        $service = new Service();
        $service->name = $request->name;
        $service->price = $request->price;
        $service->country_id = $request->country_id;
        $service->description = $request->description;
        $service->sort_order = $request->sort_order ?? 0;
        $service->is_active = $request->has('is_active');

        // Handle image upload
        if ($request->hasFile(key: 'image')) {
            $image = $request->file('image');
            $imageName = time() . '_' . Str::slug($request->name) . '.' . $image->getClientOriginalExtension();

            // Move to public/uploads/services
            $image->move(public_path('uploads/services'), $imageName);

            $service->image = "uploads/services/".$imageName;
        }

        $service->save();

        return redirect()->route('admin.services.index')
            ->with('success', 'Service created successfully.');
    }

    /**
     * Show the form for editing the specified service.
     */
    public function edit(Service $service)
    {
        $countries = Country::active()->ordered()->get();
        return view('admin.services.edit', compact('service', 'countries'));
    }

    /**
     * Update the specified service in storage.
     */
    public function update(Request $request, Service $service)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:services,name,' . $service->id,
            'price' => 'required|integer|min:0',
            'country_id' => 'nullable|exists:countries,id',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean'
        ]);

        $service->name = $request->name;
        $service->price = $request->price;
        $service->country_id = $request->country_id;
        $service->description = $request->description;
        $service->sort_order = $request->sort_order ?? 0;
        $service->is_active = $request->has('is_active');

        if ($request->hasFile(key: 'image')) {
            // Delete old image if exists
            if ($service->image && file_exists(public_path($service->image))) {
                unlink(public_path($service->image));
            }

            $image = $request->file('image');
            $imageName = time() . '_' . Str::slug($request->name) . '.' . $image->getClientOriginalExtension();

            $image->move(public_path('uploads/services'), $imageName);

            $service->image = "uploads/services/".$imageName;
        }

        $service->save();

        return redirect()->route('admin.services.index')
            ->with('success', 'Service updated successfully.');
    }

    /**
     * Remove the specified service from storage.
     */
    public function destroy(Service $service)
    {
        // Delete image if exists
        if ($service->image && file_exists(public_path($service->image))) {
            unlink(public_path($service->image));
        }

        $service->delete();

        return redirect()->route('admin.services.index')
            ->with('success', 'Service deleted successfully.');
    }

    /**
     * Toggle service status
     */
    public function toggleStatus(Service $service)
    {
        $service->is_active = !$service->is_active;
        $service->save();

        $status = $service->is_active ? 'activated' : 'deactivated';

        return redirect()->route('admin.services.index')
            ->with('success', "Service {$status} successfully.");
    }

    /**
     * Filter services by country
     */
    public function filterByCountry(Request $request)
    {
        $countryId = $request->input('country_id');
        
        $services = Service::with('country')
            ->when($countryId, function($query) use ($countryId) {
                return $query->where('country_id', $countryId);
            })
            ->ordered()
            ->paginate(20);
            
        $countries = Country::active()->ordered()->get();
        
        return view('admin.services.index', compact('services', 'countries'))
            ->with('selectedCountry', $countryId);
    }
}