<?php

namespace App\Http\Controllers\Services;

use App\Http\Controllers\Controller;
use App\Models\Services;
use App\Models\Specialties;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use PhpOffice\PhpSpreadsheet\Calculation\Web\Service;

class ServiceController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();

        $query = Services::with(['clinic:id,name', 'specialty:id,name'])
            ->orderByDesc('id');

        if ($user->clinic_id) {
            $query->where('clinic_id', $user->clinic_id);
        }

        if ($user->branch_id && $query->getModel()->isFillable('branch_id')) {
            $query->where('branch_id', $user->branch_id);
        }

        if ($request->specialty_id) {
            $query->where('specialty_id', $request->specialty_id);
        }

        $services = $query->get();

        return view('admin.services.index', compact('services'));
    }

    public function create()
    {
        $user = Auth::user();

        $specialties = Specialties::when($user->clinic_id, function ($q) use ($user) {
        })->orderBy('name')->get();

        return view('admin.services.create', compact('specialties'));
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        $data = $request->validate([
            'clinic_id' => ['nullable', 'integer'],
            'specialty_id' => ['required', 'exists:specialties,id'],
            'name' => ['required', 'string', 'max:255'],
            'category' => ['nullable', 'string', 'max:255'],
            'default_price' => ['required', 'numeric', 'min:0'],
            'duration_minutes' => ['nullable', 'integer', 'min:0'],
            'is_active' => ['nullable'],
        ]);

        if ($user->clinic_id) {
            $data['clinic_id'] = $user->clinic_id;
        }

        $data['is_active'] = $request->has('is_active');

        Services::create($data);

        return redirect()->route('services.index')
            ->with('success', 'تم إضافة الخدمة بنجاح.');
    }

    public function edit($id)
    {
        $user = Auth::user();

        $service = Services::findOrFail($id);

        // لو عندك صلاحيات / فلترة عيادة
        if ($user->clinic_id && $service->clinic_id != $user->clinic_id) {
            abort(403);
        }

        $specialties = Specialties::orderBy('name')->get();

        return view('admin.services.edit', compact('service', 'specialties'));
    }

    public function update(Request $request, $id)
    {
        $user = Auth::user();
        $service = Services::findOrFail($id);

        if ($user->clinic_id && $service->clinic_id != $user->clinic_id) {
            abort(403);
        }

        $data = $request->validate([
            'clinic_id' => ['nullable', 'integer'],
            'specialty_id' => ['required', 'exists:specialties,id'],
            'name' => ['required', 'string', 'max:255'],
            'category' => ['nullable', 'string', 'max:255'],
            'default_price' => ['required', 'numeric', 'min:0'],
            'duration_minutes' => ['nullable', 'integer', 'min:0'],
            'is_active' => ['nullable'],
        ]);

        if ($user->clinic_id) {
            $data['clinic_id'] = $user->clinic_id;
        }

        $data['is_active'] = $request->has('is_active');

        $service->update($data);

        return redirect()->route('services.index')
            ->with('success', 'تم تحديث بيانات الخدمة بنجاح.');
    }


    public function destroy($id)
    {
        $user = auth()->user();

        $service = Services::withCount(['treatmentPlanItems', 'invoiceItems'])->findOrFail($id);

        if ($user->clinic_id && $service->clinic_id != $user->clinic_id) {
            abort(403);
        }


        if ($service->treatment_plan_items_count > 0 || $service->invoice_items_count > 0) {
            return redirect()
                ->route('services.index')
                ->with('error', 'لا يمكن حذف هذه الخدمة لأنها مستخدمة في خطط علاجية أو فواتير.');
        }

        $service->delete();

        return redirect()
            ->route('services.index')
            ->with('success', 'تم حذف الخدمة بنجاح.');
    }


    public function toggleStatus($id)
    {
        $service = Services::findOrFail($id);

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

        return response()->json([
            'success' => true,
            'status' => $service->is_active ? 'نشطة' : 'غير نشطة'
        ]);
    }
}
