<?php

namespace App\Http\Controllers\Api;

use App\Models\TailorService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class TailorServiceController extends BaseController
{
    /**
     * Get all services for the authenticated tailor
     */
    public function index()
    {
        try {
            $services = TailorService::where('user_id', Auth::id())
                ->orderBy('created_at', 'desc')
                ->get();

            return $this->sendResponse($services, 'Data jasa berhasil diambil');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengambil data jasa'], 500);
        }
    }

    /**
     * Store a new service
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'description' => 'required|string|max:1000',
                'price' => 'required|numeric|min:0',
                'category' => 'required|string|in:Bawahan,Atasan,Terusan,Perbaikan',
                'estimated_days' => 'required|integer|min:1',
                'service_photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
            ]);

            if ($validator->fails()) {
                return $this->sendError('Error validasi.', $validator->errors(), 422);
            }

            $serviceData = $request->only([
                'name',
                'description',
                'price',
                'category',
                'estimated_days'
            ]);

            $serviceData['user_id'] = Auth::id();

            // Handle service photo upload
            if ($request->hasFile('service_photo')) {
                $path = $request->file('service_photo')->store('service_photos', 'public');
                $serviceData['service_photo'] = $path;
            }

            $service = TailorService::create($serviceData);

            return $this->sendResponse($service, 'Jasa berhasil ditambahkan');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat menambahkan jasa'], 500);
        }
    }

    /**
     * Update the specified service
     */
    public function update(Request $request, TailorService $service)
    {
        try {
            // Check if the service belongs to the authenticated tailor
            if ($service->user_id !== Auth::id()) {
                return $this->sendError('Unauthorized.', ['error' => 'Anda tidak memiliki akses untuk mengubah jasa ini'], 403);
            }

            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'description' => 'required|string|max:1000',
                'price' => 'required|numeric|min:0',
                'category' => 'required|string|in:Bawahan,Atasan,Terusan,Perbaikan',
                'estimated_days' => 'required|integer|min:1',
                'is_available' => 'required|boolean',
                'service_photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
            ]);

            if ($validator->fails()) {
                return $this->sendError('Error validasi.', $validator->errors(), 422);
            }

            // Handle service photo upload
            if ($request->hasFile('service_photo')) {
                // Delete old photo if exists
                if ($service->service_photo) {
                    Storage::disk('public')->delete($service->service_photo);
                }

                $path = $request->file('service_photo')->store('service_photos', 'public');
                $service->service_photo = $path;
            }

            $service->update($request->only([
                'name',
                'description',
                'price',
                'category',
                'estimated_days',
                'is_available'
            ]));

            return $this->sendResponse($service, 'Jasa berhasil diupdate');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengupdate jasa'], 500);
        }
    }

    /**
     * Delete the specified service
     */
    public function destroy(TailorService $service)
    {
        try {
            // Check if the service belongs to the authenticated tailor
            if ($service->user_id !== Auth::id()) {
                return $this->sendError('Unauthorized.', ['error' => 'Anda tidak memiliki akses untuk menghapus jasa ini'], 403);
            }

            // Delete service photo if exists
            if ($service->service_photo) {
                Storage::disk('public')->delete($service->service_photo);
            }

            $service->delete();

            return $this->sendResponse(null, 'Jasa berhasil dihapus');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat menghapus jasa'], 500);
        }
    }

    /**
     * Toggle service availability
     */
    public function toggleAvailability(TailorService $service)
    {
        try {
            // Check if the service belongs to the authenticated tailor
            if ($service->user_id !== Auth::id()) {
                return $this->sendError('Unauthorized.', ['error' => 'Anda tidak memiliki akses untuk mengubah status jasa ini'], 403);
            }

            $service->is_available = !$service->is_available;
            $service->save();

            return $this->sendResponse($service, 'Status ketersediaan jasa berhasil diubah');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengubah status jasa'], 500);
        }
    }

    /**
     * Get services by tailor ID (public)
     */
    public function getTailorServices($tailorId)
    {
        try {
            $services = TailorService::where('user_id', $tailorId)
                ->where('is_available', true)
                ->orderBy('created_at', 'desc')
                ->get();

            return $this->sendResponse($services, 'Data jasa penjahit berhasil diambil');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengambil data jasa'], 500);
        }
    }
}
