<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use App\Models\Admin\EmailHost;
use Yajra\DataTables\DataTables;

use App\Traits\Permissions_trait;
use Spatie\Activitylog\Models\Activity;

class EmailController extends Controller
{
    use Permissions_trait;
    var $url;
    public function __construct()
    {
        $this->middleware('auth');
        $this->url = request()->path();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, 'Permission denied..');
        endif;

        activity('Email Host Page Visited')
        ->causedBy(Auth::user())
        ->performedOn(new EmailHost())
        // ->withProperties(['old'  => [], 'modified'=>$data])
        ->tap(function (Activity $activity) {
            $activity->route_link = $this->url;
        })
        ->log('Email Host Page visited by ' . Auth::user()->name);
        return view('admin.send_mail.email_hosts');
    }

    public function host_list(Request $request)
    {
        if (!$this->Permissions_trait('view', 'email_hosts')) :
            abort(403, 'Permission denied..');
        endif;
        if ($request->ajax()) :
            $record = EmailHost::select('*')->where('status', '!=', -1)->orderBy('id', 'desc');
            return Datatables::of($record)
            ->setRowId(function ($row) {
                return $row->id;
            })
            ->addColumn('is_default',function ($row) {
                $checked = "";
                  if ($row->is_default == 1) { $checked = "checked"; }
                  $swtich = '
                  <div class="ps-5">
                      <label class="switch">
                          <input class="" type="checkbox" id="togBtn" onClick="is_default('.$row->id.')" '.$checked.'>
                          <div class="slider round">
                              <span class="on">ON</span>
                              <span class="off">OFF</span>
                          </div>
                      </label>
                  </div>
                  ';
                  return $swtich;
            })
            ->addColumn('status',function ($row) {
                $checked = "";
                  if ($row->status == 1) { $checked = "checked"; }
                  $swtich = '
                  <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">ON</span>
                              <span class="off">OFF</span>
                          </div>
                      </label>
                  </div>
                  ';
                  return $swtich;
            })
            ->addColumn('actions',function($row){
                $btn =  '
                    <span class="px-2">
                        <a class="text-decoration-none px-1" href="'.url('/email_hosts/edit/'.$row->id).'">
                            <span class="edit_icon">
                                <i class="bi bi-pen"></i>
                            </span>
                            <span class="px-1 e-text">Edit</span>
                        </a>
                    </span>
                    <span>
                        <a class="text-decoration-none px-1" onClick="destroy('.$row->id.')">
                            <span class="delete_icon fw-bold"><i class="bi bi-backspace"></i></span>
                            <span class="px-1 tcancel e-text">Delete</span>
                        </a>
                    </span>
                ';
                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(['name', 'is_default', 'status','actions'])
            ->make(true);
             endif;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return View('admin.send_mail.email_hosts_add');
    }

    public function store(Request $request)
    {
        if (!$this->Permissions_trait('insert', 'email_hosts')) :
            return redirect()->back()->with('error','Permission denied..')->withInput();
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $validator = Validator::make($request->all(), [
            'host_name' => 'required|max:255',
            'host_address' => 'required|max:255',
            'username' => 'required',
            'password' => 'required|max:255',
            'port' => 'required',
            'encryption' => 'required',
            'from_name' => 'required',
            'from_email' => 'required|email',
            'cc_email' => 'required|email',
            'bcc_email' => 'required|email',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            if(isset($request->default)){ $default = '1'; }else{ $default = '0'; }
            if(isset($request->cc_status)){ $cc_status = '1'; }else{ $cc_status = '0'; }
            if(isset($request->bcc_status)){ $bcc_status = '1'; }else{ $bcc_status = '0'; }
            if(isset($request->status)){ $status = '1'; }else{ $status = '0'; }
            if ($default == 1) {
                $status = '1';
            }
            $data = [
                'name' => $request->host_name,
                'host_address' => $request->host_address,
                'username' => $request->username,
                'secret' => $request->password,
                'port' => $request->port,
                'security' => $request->encryption,
                'from_name' => $request->from_name,
                'cc' => $request->cc_email,
                'bcc' => $request->bcc_email,
                'is_default' => $default,
                'from_email' => $request->from_email,
                'cc_status' => $cc_status,
                'bcc_status' => $bcc_status,
                'status' => $status,
            ];
            $post = EmailHost::insert($data);
            $update = EmailHost::where('is_default', '1')->where('id', '!=', $post->id)->update([
                'is_default' => '0',
            ]);

            activity('Email Host Added')
               ->causedBy(Auth::user())
                ->performedOn(new EmailHost())
                // ->withProperties(['old'  => [], 'modified'=>$data])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Email Host Added by ' . Auth::user()->name);           
            if ($post) {
                return redirect()->back()->with('success','Host added successfuly')->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = EmailHost::find($id);
        return View('admin.send_mail.email_host_edit', compact('post'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        if(!$this->Permissions_trait('update','email_hosts')):
            return redirect()->back()->with('error','Permission denied..')->withInput();
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $validator = Validator::make($request->all(), [
            'host_name' => 'required|max:255',
            'host_address' => 'required|max:255',
            'username' => 'required',
            'password' => 'required|max:255',
            'port' => 'required',
            'encryption' => 'required',
            'from_name' => 'required',
            'from_name' => 'required',
            'from_email' => 'required|email',
            'cc_email' => 'required|email',
            'bcc_email' => 'required|email',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            if(isset($request->default)){ $default = '1'; }else{ $default = '0'; }
            if(isset($request->cc_status)){ $cc_status = '1'; }else{ $cc_status = '0'; }
            if(isset($request->bcc_status)){ $bcc_status = '1'; }else{ $bcc_status = '0'; }
            if(isset($request->status)){ $status = '1'; }else{ $status = '0'; }
            if ($default == 1) {
                $status = '1';
            }
            $data = [
                //'name' => $request->host_name,
                'host_address' => $request->host_address,
                'username' => $request->username,
                'secret' => $request->password,
                'port' => $request->port,
                'security' => $request->encryption,
                'from_name' => $request->from_name,
                'cc' => $request->cc_email,
                'bcc' => $request->bcc_email,
                'is_default' => $default,
                'from_email' => $request->from_email,
                'cc_status' => $cc_status,
                'bcc_status' => $bcc_status,
                'status' => $status,
            ];
            $old = EmailHost::where('id', $request->id)->first();
            $post = EmailHost::where('id', $request->id)->update($data);
            $update = EmailHost::where('is_default', '1')->where('id', '!=', $request->id)->update([
                'is_default' => '0',
            ]);

            activity('Email Host updated')
            ->causedBy(Auth::user())
                ->performedOn(new EmailHost())
                ->withProperties(['old'  => $old, 'modified' => $data])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Email Host updated by ' . Auth::user()->name);
            if ($post) {
                return redirect()->back()->with('success','Host Updated successfuly')->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        }
    }

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

        activity('Email Host status Changed')
        ->causedBy(Auth::user())
            ->performedOn(new EmailHost())
            ->withProperties(['old'  => ['status' =>$state], 'modified' => ['status' => $update_state]])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Email Host 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 is_default(Request $request)
    {
        if(!$this->Permissions_trait('update','email_hosts')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $state = getAny("is_default", "email_hosts", "id", $request->id);
        $status = getAny("status", "email_hosts", "id", $request->id);
        if ($state == 1) {
            $update_state = '0';
        }else{
            $update_state = '1';
            $status = '1';
        }
        $post = EmailHost::find($request->id);
        $post->is_default = $update_state;
        $post->status = $status;
        $msg = $post->save();

        $update = EmailHost::where('is_default', '1')->where('id', '!=', $request->id)->update([
            'is_default' => '0',
        ]);

        activity('Email Default Host Changed')
        ->causedBy(Auth::user())
            ->performedOn(new EmailHost())
            ->withProperties(['old'  => ['is_default' =>$state], 'modified' => ['is_default' => $update_state]])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Email Default Host 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'));
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        if(!$this->Permissions_trait('delete','email_hosts')):
            return ['text' => trans('Permission denied..'), 'cls' => 'error'];
            //abort(403, 'Permission denied..');
            exit;
        endif;
        //$msg = EmailHost::where('id',$request->id)->delete();
        $post = EmailHost::find($request->id);
        $post->status = '-1';
        $msg = $post->save();

        activity('Email Host Data Deleted')
            ->causedBy(Auth::user())
            ->performedOn(new EmailHost())
            ->withProperties(['old'  => ['status' =>$post->status], 'modified' => ['status' => '-1']])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Email Host data deleted by ' . Auth::user()->name);
        if ($msg) {
            return ['text' => trans('admin.Delete_successfully'), 'cls' => 'success'];
        } else {
            return ['text' => trans('admin.Somthing_went_wrong'), 'cls' => 'error'];
        }
    }
}
