<?php

namespace App\Http\Controllers\Admin;

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

class PartnersController 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 = Partner::select('count(*) as allcount')->count();
            $totalRecordswithFilter = Partner::select('count(*) as allcount')
                ->where('name', 'like', '%' . $searchValue . '%')
                ->orWhere('name_ar', 'like', '%' . $searchValue . '%')
                ->count();

            $partners = Partner::select('partners.*')
                ->where('name', 'like', '%' . $searchValue . '%')
                ->orWhere('name_ar', 'like', '%' . $searchValue . '%')
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('partners.id', 'desc')
                ->get();


            $records = [];

            foreach($partners as $item)
            {
                $records[] = [
                    'record_select' =>view('admin.partners.datatable.record',[ 'item' => $item ])->render(),
                    'id' => $item->id,
                    'image' => $item->image ? '<img src="'. asset('storage/works/'.$item->image) .'" width="70" style="background-color: #0006; padding: 5px; border-radius: 10px;">' : __('No image uploaded'),
                    'name' => \LaravelLocalization::getCurrentLocale() == 'ar' ? $item->name_ar : $item->name,
                    'actions' => view('admin.partners.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

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

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

        }

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


    public function store(Request $request)
    {
        # code...
        $this->authorize('viewAny', WebsiteSetting::class);
        $request->validate([
            'image' => 'required|mimes:png,jpg,jpeg',
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
        ]);

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

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

        Partner::create($data);

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

    public function update(Request $request, Partner $partner)
    {
        # code...
        $this->authorize('viewAny', WebsiteSetting::class);
        $request->validate([
            'image' => 'nullable|mimes:png,jpg,jpeg',
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
        ]);

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

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

        $partner->update($data);
        return redirect()->route('c-panel.partners.index')->with('success', __('Updated Done !'));
    }

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

    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) {
                $partner = Partner::FindOrFail($recordId);
                // $this->authorize('delete', $partner);
                $this->delete($partner);
            }//end of for each
        }else{
            return redirect()->route('c-panel.partners.index')->with('error',__('Please Select Record Before Delete'));
        }

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

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

