<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\serviceRequest;
use App\Models\service;
use Illuminate\Support\Str;
use LaravelLocalization;
use App\Traits\allTraits;


class serviceController extends Controller
{
    use allTraits;

    public function addServices() {

        $services =  service::All();
        return view('admin.addService', compact('services'));
    }


    public function servicesPost(serviceRequest $request)
    {


        $file_name = $this->saveImage($request->photo, 'images/services');

        service::create([
            'photo' => $file_name,
            'title_ar' => $request -> title_ar,
            'title_en' => $request -> title_en,
            'details_ar' => $request -> details_ar,
            'details_en' => $request -> details_en,
            'slug' => preg_replace('/[^\p{Arabic}a-zA-Z0-9\-]+/u', '-', $request->title_ar),

        ]);

        return redirect()->back()->with(['successAdd' => '']);

    }


    public function allServices() {

        $services =  service::All();
        return view('admin.allService', compact('services'));
    }


    public function deleteServices($services_id)
    {

        $services = service::find($services_id);

        if (!$services)
            return redirect()->back()->with(['error' => __('messages.news not exist')]);

        $services->delete();

        return redirect()
            ->route('aboutUs')
            ->with(['successDelete' => __('messages.news deleted successfully')]);

    }


    public function editServices($services_id)
    {

        // addNews::findOrFail($news_id);
        $services = service::find($services_id);  // search in given table id only
        if (!$services)
            return redirect()->back();

        $services = service::all()->find($services_id);
        return view('admin.editServices', compact('services'));


    }


       public function UpdateService(serviceRequest $request, $services_id)
{
    // check if service exists
    $service = service::find($services_id);
    if (!$service) {
        return redirect()->back()->with(['error' => 'الخدمة غير موجودة']);
    }

    // جهز البيانات للتحديث
    $data = [

            'title_ar' => $request -> title_ar,
            'title_en' => $request -> title_en,
            'details_ar' => $request -> details_ar,
            'details_en' => $request -> details_en,
    ];

    // لو في صورة جديدة
    if ($request->hasFile('photo')) {
        $file_name = $this->saveImage($request->photo, 'images/services');
        $data['photo'] = $file_name;
    }

    // update مرة واحدة
    $service->update($data);

    return redirect()->back()->with(['successEdit' => 'تم التحديث بنجاح']);
}






}
