<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Traits\Permissions_trait;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Models\Activity;
use App\Models\Admin\Pages;
use DataTables;

class PagesController extends Controller
{
    var $url;
    use Permissions_trait;
    public function __construct()
    {
        $this->middleware('auth');
        $this->url = request()->path();
    }

    public function index(Request $request)
    {
        if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, trans('admin.You_have_no_permission'));
        endif;

        if ($request->ajax()) {
            $data = Pages::query();
            return Datatables::eloquent($data)
            ->addIndexColumn()
            ->setRowId(function ($row) { return $row->id; })
            ->addColumn('page_name', function($row){
                if (Auth::user()->locale == 'en') {
                    $content = $row->name_en;
                }else{
                    $content = $row->name_ar;
                }
                return $content;
            })
            ->addColumn('content', function ($row) {
                if (Auth::user()->locale == 'en') {
                    $content = $row->content_en;
                } else {
                    $content = $row->content_ar;
                }
                return $content;
            })
            ->addColumn('status', function($row){
                $checked = "";
                if ( $row->status == 1) { $checked = "checked"; }
                $swtich = '
                    <label class="switch" for="checkbox'.$row->id.'">
                        <input class="state_switch" type="checkbox" id="checkbox'.$row->id.'" value="'.$row->id.'" '.$checked.' />
                        <div class="slider round"></div>
                    </label>
                ';
                if($this->Permissions_trait('view',$this->url)):
                    return $swtich;
                else:
                    return "";
                endif;
            })
            ->addColumn('action', function($row){
                if ($this->Permissions_trait('update', $this->url)) :
                $btn = '
                  <div class="float-middle">
                    <span class="px-2">
                        <a class="text-decoration-none px-1" href="'.url("/pages/edit/".$row->id).'">
                            <span class="edit_icon">
                                <i class="bi bi-pen"></i>
                            </span>
                            <span class="px-1 e-text">'.trans('admin.edit').'</span>
                        </a>
                    </span>
                  </div>
                ';
                endif;
                return $btn;
            })
            ->filter(function ($record) use ($request) {
              $input="";
              if ($request->has('search_new') && $request->search_new != "") {
                  $input=$request->get("search_new");
                  $record->where('name_en', 'like', '%' . $input . '%')->orwhere('name_ar', 'like', '%' . $input . '%');
              }

              if ($request->has('status_filter') && $request->status_filter != "") {
                  $record->where('status',$request->get('status_filter'));
              }
            })
            ->rawColumns(['action','status','content'])
            ->make(true);
        }

        activity('Manage Pages Visited')
        ->causedBy(Auth::user())
            ->performedOn(new Pages())
            // ->withProperties(['old'  => [$post], 'modified' => []])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Manage Pages Visited by ' . Auth::user()->name);
        return view('admin/manage_pages.manage');
    }

    function add()
    {
        if (!$this->Permissions_trait('insert', 'pages')) :
            abort(403, trans('admin.You_have_no_permission'));
        endif;

            activity('Edit Page visited')
            ->causedBy(Auth::user())
                ->performedOn(new Pages())
                // ->withProperties(['old'  => $post, 'modified' => []])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Edit Page visited by ' . Auth::user()->name);
        return view('admin/manage_pages.add');
    }

    public function save(Request $request)
    {
        if (!$this->Permissions_trait('insert', 'pages')) :
            return ['text' => trans('admin.You_have_no_permission'), 'cls' => 'error'];
            exit;
        endif;
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            $data = [
                'name_en' => $request->name,
                'name_ar' => $request->name,
                'slug' => $request->slug,
                'title_en' => $request->title_en,
                'title_ar' => $request->title_ar,
                'content_ar' => $request->text_ar,
                'content_en' => $request->text_en,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $post = Pages::insert($data);

            activity('Page Created')
            ->causedBy(Auth::user())
                ->performedOn(new Pages())
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Created Page by ' . Auth::user()->name);
            if ($post) {
                return redirect()->back()->with('success',trans('admin.Saved_successfully'))->withInput();
            } else{
                return redirect()->back()->with('error',trans('admin.not_save'))->withInput();
            }
        }
    }

  function edit($id)
  {
    if (!$this->Permissions_trait('update', 'pages')) :
        abort(403, trans('admin.You_have_no_permission'));
    endif;
    $post = Pages::find($id);

        activity('Edit Page visited')
        ->causedBy(Auth::user())
            ->performedOn(new Pages())
            // ->withProperties(['old'  => $post, 'modified' => []])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Edit Page visited by ' . Auth::user()->name);
    return view('admin/manage_pages.edit', compact('post'));
  }

  function update(Request $request)
  {
    if(!$this->Permissions_trait('update','pages')):
            return redirect()->back()->with('error','Permission denied..')->withInput();
            //abort(403, 'Permission denied..');
            exit;
        endif;
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);
    // ddd($request->all());
    if ($validator->fails()) {
        //ddd($request->all());
        return redirect()->back()->withErrors($validator)->withInput();
    } else {
        if(isset($request->status)){ $status = '1'; }else{ $status = '0'; }
        $data = [
            'name_en' => $request->name,
            'name_ar' => $request->name,
            'slug' => $request->slug,
            'title_en' => $request->title_en,
            'title_ar' => $request->title_ar,
            'content_ar' => $request->text_ar,
            'content_en' => $request->text_en,
            'created_at' => date('Y-m-d H:i:s'),
        ];
        $old = Pages::find($request->id);
        $post = Pages::where('id',$request->id)->update($data);
        /*activity*/
        activity('Page updated visited')
        ->causedBy(Auth::user())
            ->performedOn(new Pages())
            ->withProperties(['old'  => $old, 'modified' => $data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Page updated visited by ' . Auth::user()->name);
        if ($post) {
            return redirect()->back()->with('success','Updated successfuly')->withInput();
        } else {
            return redirect()->back()->with('error','Somthing went wrong')->withInput();
        }
    }
  }

  function status(Request $request)
  {
    if(!$this->Permissions_trait('update','pages')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
    $state = getAny("status", "pages", "id", $request->id);
    if ($state == 1) {
        $update_state = '0';
    }else{
        $update_state = '1';
    }
    $post = Pages::find($request->id);
    $post->status = $update_state;
    $msg = $post->save();

        activity('status updated visited')
        ->causedBy(Auth::user())
            ->performedOn(new Pages())
            ->withProperties(['old'  => ['status' => $state], 'modified' => $update_state])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Page status updated visited by ' . Auth::user()->name);
    if ($msg) {
      echo  json_encode(array('text' => trans('admin.Status_Changed'), 'cls' => 'success'));
    } else {
      echo  json_encode(array('text' => trans('admin.Error'), 'cls' => 'error'));
    }
  }

  function destroy(Request $request)
  {
    if (!$this->Permissions_trait('update', 'pages')) :
        abort(403, trans('admin.You_have_no_permission'));
    endif;
    Pages::where('id',$request->id)->delete();

        activity('Page Data Deleted')
        ->causedBy(Auth::user())
            ->performedOn(new Pages())
            // ->withProperties(['old'  => [$old], 'modified' => $data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Page deleted by ' . Auth::user()->name);
    return['text' => trans('admin.Delete_successfully'), 'cls' => 'warning'];
  }
}
