<?php

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

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

  public function index(Request $request)
  {
    if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, 'Permission denied..');
        endif;
    if ($request->ajax()) {
      $record = Email_templates::select('*')->where('status', '!=', '-1')->orderBy('id', 'desc');
      return Datatables::of($record)
      ->addIndexColumn()
      ->setRowId(function ($row) { return $row->id; })
      ->addColumn('status', function($row){
          $checked = "";
          if ($row->status == 1) { $checked = "checked"; }
          $swtich = '
            <div class="d-flex float-end ms-5">
              <div class="ps-5">
                  <label class="switch">
                      <input class="" type="checkbox" id="togBtn" onClick="state_switch('.$row->id.')" '.$checked.'>
                      <div class="slider round">
                          <span class="on">'.trans('admin.on').'</span>
                          <span class="off">'.trans('admin.off').'</span>
                      </div>
                  </label>
              </div>
            </div>
          ';
          return $swtich;
      })
      ->addColumn('action', function($row){
          $btn = '
          <div class="float-end">
            <span class="px-2">
                <a class="text-decoration-none px-1" href="'.url("/email_templates/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>
            <span>
                <a class="text-decoration-none px-1 btn-delete" onClick="destroy('.$row->id.')">
                  <span class="delete_icon fw-bold"><i class="bi bi-backspace"></i></span>
                  <span class="px-1 tcancel e-text">'.trans('admin.delete').'</span>
                </a>
            </span>
          </div>
          ';
          return $btn;
      })
      ->filter(function ($record) use ($request) {
          $input="";
          if ($request->has('search_new') && $request->search_new != "") {
              $input=$request->get("search_new");
              $record->where('name', 'like', '%'. $input .'%');
          }

          if ($request->has('status_filter') && $request->status_filter != "") {
              $record->where('status', '=', $request->get('status_filter'));
          }
      })
      ->rawColumns(['action','status'])
      ->make(true);
    }
    activity('Email templates Page Visited')
           ->causedBy(Auth::user())
            ->performedOn(new Email_templates())
            // ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Email templates Page visited by ' . Auth::user()->name);
    return view('admin/templates.manage');
  }

  function add()
  {
    return view('admin/templates.add_template');
  }

  function save(Request $request)
  {
    if (!$this->Permissions_trait('insert', 'email_templates')) :
      return  json_encode(array('text' => 'Permission denied', 'cls' => 'error'));
      //abort(403, 'Permission denied..');
      exit;
    endif;
    if (empty($request->name)) {
      return  json_encode(array('text' => 'The Name is required', 'cls' => 'info'));
    }
    elseif (empty($request->subject)) {
      return  json_encode(array('text' => 'The Subject is required', 'cls' => 'info'));
    }
    elseif (empty($request->message)) {
      return  json_encode(array('text' => 'Write your message', 'cls' => 'info'));
    }
    elseif (Email_templates::where('name', $request->name)->exists()) {
      return  json_encode(array('text' => trans('admin.already_exist')));
    }
    else{
      $post = new Email_templates;
      $post->name = $request->name;
      $post->subject = $request->subject;
      $post->content = $request->message;
      $post->btn_text = "";
      $post->btn_url = "";
      $msg = $post->save();
      activity('Email templates Host Added')
               ->causedBy(Auth::user())
                ->performedOn(new Email_templates())
                // ->withProperties(['old'  => [], 'modified'=>$data])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Email templates Host Added by ' . Auth::user()->name);
      if ($msg) {
        return  json_encode(array('text' => trans('admin.Added_successfully'), 'cls' => 'success'));
      } else {
        return  json_encode(array('text' => trans('admin.Not_Updated'), 'cls' => 'error'));
      }
    }
  }

  function edit($id)
  {
    $template = Email_templates::find($id);
    return view('admin/templates.edit_template', compact('template'));
  }

  function update(Request $request)
  {
    if(!$this->Permissions_trait('update','email_templates')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
    if (empty($request->name)) {
      return  json_encode(array('text' => 'The Name is required', 'cls' => 'info'));
    }
    elseif (empty($request->subject)) {
      return  json_encode(array('text' => 'The Subject is required', 'cls' => 'info'));
    }
    elseif (empty($request->message)) {
      return  json_encode(array('text' => 'Write your message', 'cls' => 'info'));
    }
    else{
      $post = Email_templates::find($request->id);
      //$post->name = $request->name;
      $post->subject = $request->subject;
      $post->content = $request->message;
      $post->btn_text = "";
      $post->btn_url = "";
      $msg = $post->save();
      activity('Email templates updated')
            ->causedBy(Auth::user())
                ->performedOn(new Email_templates())
                ->withProperties(['old'  => $post, 'modified' => $msg])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Email templates updated by ' . Auth::user()->name);
      if ($msg) {
        echo  json_encode(array('text' => trans('admin.Updated_successfully'), 'cls' => 'success'));
      } else {
        echo  json_encode(array('text' => trans('admin.Not_Updated'), 'cls' => 'error'));
      }
    }
  }

  function status(Request $request)
  {
    if(!$this->Permissions_trait('update','email_templates')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
    $state = getAny("status", "email_templates", "id", $request->id);
    if ($state == 1) {
        $update_state = 0;
    }else{
        $update_state = 1;
    }
    $post = Email_templates::find($request->id);
    $post->status = $update_state;
    $msg = $post->save();
    activity('Email templates status Changed')
        ->causedBy(Auth::user())
            ->performedOn(new Email_templates())
            ->withProperties(['old'  => ['status' =>$state], 'modified' => ['status' => $update_state]])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Email templates status changed 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('delete','email_templates')):
        return ['text' => trans('Permission denied..'), 'cls' => 'error'];
        //abort(403, 'Permission denied..');
        exit;
    endif;
    //$msg = Category::where('id', $request->id)->delete();
    $post = Email_templates::find($request->id);
    $post->status = -1;
    $msg = $post->save();
    activity('Email Data Deleted')
            ->causedBy(Auth::user())
            ->performedOn(new Email_templates())
            ->withProperties(['old'  => ['status' =>$post->status], 'modified' => ['status' => '-1']])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Email Deleted Created by ' . Auth::user()->name);
    if ($msg) {
      echo  json_encode(array('text' => trans('admin.Delete_successfully'), 'cls' => 'warning'));
    } else {
      echo  json_encode(array('text' => trans('admin.Error'), 'cls' => 'error'));
    }
  }
}
