<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\WebsiteSetting;
use App\Models\Work;
use App\Models\Work_image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class WorksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', WebsiteSetting::class);
        if ($request->ajax()) {
            // dd($request->all());
            $draw = $request->get('draw');
            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = Work::select('count(*) as allcount')->count();
            $totalRecordswithFilter = Work::select('count(*) as allcount')
                ->when($searchValue , function ($q) use ($searchValue){
                    $q->where('title', 'like', '%' . $searchValue . '%')
                    ->orWhere('title_ar', 'like', '%' . $searchValue . '%');
                })
                ->count();

            $works = Work::select('works.*')
                ->when($searchValue , function ($q) use ($searchValue){
                    $q->where('title', 'like', '%' . $searchValue . '%')
                    ->orWhere('title_ar', 'like', '%' . $searchValue . '%');
                })
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('works.id', 'desc')
                ->get();


            $records = [];

            foreach($works as $item)
            {
                $records[] = [
                    'record_select' =>view('admin.works.datatable.record',[ 'item' => $item ])->render(),
                    'id' => $item->id,
                    'image' => $item->image ? '<img src="'. asset('storage/works/'.$item->image) .'" width="100">' : __('No image uploaded'),
                    'title' => \LaravelLocalization::getCurrentLocale() == 'ar' ? ($item->title_ar ? $item->title_ar : __('No Added')) :( $item->title ? $item->title : __('No Added')),
                    'service' => \LaravelLocalization::getCurrentLocale() == 'ar' ? ($item->category ? $item->category->title_ar : __('No Added')) :( $item->category ? $item->category->title : __('No Added')),
                    'actions' => view('admin.works.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

            $response = [
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordswithFilter,
                "aaData" => $records
            ];

            return response()->json($response);

        }

        return view('admin.works.index');
    }

    public function store(Request $request)
    { 
        # code...
        // dd($request->all());
        $this->authorize('viewAny', WebsiteSetting::class);
        $request->validate([
            'image' => 'required|mimes:png,jpg,jpeg',
            'title' => 'nullable|string|max:255',
            'title_ar' => 'nullable|string|max:255',
            'client' => 'nullable|string|max:255', 
            'description_ar' => 'nullable|string|max:900',
            'description' => 'nullable|string|max:900',
            'category_id' => 'nullable|exists:categories,id', 
            'link' => 'nullable|url',
            'v_link' => 'nullable|url',
        ]);

        $data = $request->all();
        $image = null;

        if($request->hasFile('image') && $request->file('image')->isValid()){
            $image = $request->file('image')->store('/','works');
            $data['image'] = 'works/'. $image;
        }

       $work = Work::create([ 
        'title' => $request->title,
        'title' => $request->title,
        'title_ar' => $request->title_ar,
        'client' => $request->client,
        'description_ar' => $request->description_ar,
        'description' => $request->description,
        'category_id' => $request->category_id,
        'link' => $request->link,
        'v_link' => $request->v_link,
        'date' => $request->date,
        'image' => $image, 
    ]); 

        if($request->hasFile('work_images'))
        {
         $work_images = $request->file('work_images');
        foreach($work_images as $photo){    

                $image = $photo->store('/','works');
                Work_image::create([
                    'image' => $image,
                    'work_id' => $work->id,
                ]); 
        } 
       }

        return redirect()->route('c-panel.works.index')->with('success', __('Added Done !'));
    }

    public function update(Request $request, Work $work)
    {
        # code...
        $this->authorize('viewAny', WebsiteSetting::class);
        $request->validate([
            'image' => 'nullable|mimes:png,jpg,jpeg',
            'title' => 'nullable|string|max:255',
            'client' => 'nullable|string|max:255', 
            'description_ar' => 'nullable|string|max:900',
            'description' => 'nullable|string|max:900',
            'title_ar' => 'nullable|string|max:255',
            'category_id' => 'nullable|exists:categories,id', 
            'link' => 'nullable|url',
            'v_link' => 'nullable|url',
        ]);

        $data = $request->all();
        $image = $work->image;

        if($request->hasFile('image') && $request->file('image')->isValid()){
            if($work->image)
                Storage::disk('public')->delete($work->image);
            $image = $request->file('image')->store('/','works');
            $data['image'] = 'works/'. $image;
        }

        $work->update([ 
            'title' => $request->title,
            'title' => $request->title,
            'title_ar' => $request->title_ar,
            'client' => $request->client,
            'date' => $request->date,
            'description_ar' => $request->description_ar,
            'description' => $request->description,
            'category_id' => $request->category_id,
            'link' => $request->link,
            'v_link' => $request->v_link,
            'image' => $image, 
        ]);

        if($request->hasFile('work_images'))
        {
         $work_images = $request->file('work_images');
        foreach($work_images as $photo){    

                $image = $photo->store('/','works');
                Work_image::create([
                    'image' => $image,
                    'work_id' => $work->id,
                ]); 
        } 
       }

        return redirect()->route('c-panel.works.index')->with('success', __('Updated Done !'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy( Work $work)
    {
        // $this->authorize('delete', $department);
        $this->authorize('viewAny', WebsiteSetting::class);
        if($work->image)
            Storage::disk('public')->delete($work->image);
        $work->delete();
        return redirect()->route('c-panel.works.index')->with('success',__('Deleted Done !'));
    }

    public function edit( Work $work)
    {
        return view('admin.works.edit', [
            'item' => $work, 
        ]);
    }

    public function bulkDelete()
    {
        // dd(json_decode(request()->record_ids));
        $this->authorize('viewAny', WebsiteSetting::class);
        if(count(json_decode(request()->record_ids)) != 0){
            foreach (json_decode(request()->record_ids) as $recordId) {
                $work = Work::FindOrFail($recordId);
                // $this->authorize('delete', $work);
                $this->delete($work);
            }//end of for each
        }else{
            return redirect()->route('c-panel.works.index')->with('error',__('Please Select Record Before Delete'));
        }

        return redirect()->route('c-panel.works.index')->with('success',__('Selected  Deleted Done !'));
    }// end of bulkDelete

    private function delete(Work $work)
    {
        // $this->authorize('delete', $work);
        $this->authorize('viewAny', WebsiteSetting::class);
        if($work->image)
            Storage::disk('public')->delete($work->image);
        $work->delete();
    }

    public function delete_work_photo(Request $request)
    {  
        $project_photo = Work_image::find($request->id);
        Storage::disk('works')->delete($project_photo->image); 
        $project_photo->delete(); 
        return response()->json([
            'status' => true,
            'id' => $request->id,
        ]);
    }
}
