<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Models\Admin\ContactUs;
use App\Models\Admin\EmailHost;
use App\Mail\SingleMail;
use Config;
use App\Traits\Permissions_trait;
use Spatie\Activitylog\Models\Activity;
use Mail;

class ContactUstController 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(Request $request)
    {
        if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, 'Permission denied..');
        endif;
        if ($request->ajax()) {
          $record = ContactUs::select('*')->orderBy('id', 'desc');
          return Datatables::of($record)
          ->addIndexColumn()
          ->setRowId(function ($row) { return $row->id; })
          ->addColumn('created_at', function ($row) {
                return Carbon::parse($row->created_at) -> format('d F, Y');
          })
          ->addColumn('is_viewed', function($row){
            switch ($row->is_viewed) {
                case 0:
                    return '
                        <span class="rounded-pill bg-warning rounded text-center p-2">
                            '.trans('admin.no').'
                        </span>
                    ';
                    break;
                case 1:
                    return '
                        <span class="rounded-pill bg-success rounded text-center p-2">
                            '.trans('admin.yes').'
                        </span>
                    ';
                    break;
            }
          })
          ->addColumn('reply_count', function($row){
            return '
                <span class="rounded-pill bg-warning rounded text-center p-1">
                    '.$row->reply_count.'
                </span>'.trans('admin.time(s)').'
            ';
          })
          ->addColumn('action', function($row){
              $btn = '
              <div class="float-center">
                <span class="px-2">
                    <a class="text-decoration-none px-1" href="'.url("/contact_us_list/viewed/".$row->id).'">
                        <span class="edit_icon">
                            <i class="bi bi-eye" style="font-size: 16px;"></i>
                        </span>
                        <span class="px-1 e-text">'.trans('admin.veiw').'</span>
                    </a>
                </span>
                </div>
              ';
              return $btn;
          })
          ->filter(function ($record) use ($request) {
              /*search*/
              $input="";
              if ($request->has('search_new') && $request->search_new != "") {
                $input=$request->get("search_new");
                $record->where('name', 'like', '%'. $input .'%');
              }
              /*status*/
              if ($request->has('status_filter') && $request->status_filter != "") {
                $record->where('is_viewed', '=', $request->get('status_filter'));
              }
          })
          ->rawColumns(['action','is_viewed', 'reply_count'])
          ->make(true);
        }
        activity('Contact Us list Page Browsed')
           ->causedBy(Auth::user())
            ->performedOn(new ContactUs())
            // ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Contact us list Page visited by ' . Auth::user()->name);
        return view('admin.contact_us_list.contact_us_index');
    }

    /*public function status_change($id, $status)
    {
        ContactUs::where('id',$id)->update([
            'status' => $status
        ]);
        return ['status' => 'success','message' => 'Modified'];
    }*/

    public function viewed($id)
    {
        if (!$this->Permissions_trait('view', 'contact_us_list')) :
            abort(403, 'Permission denied..');
        endif;
        $post = ContactUs::find($id)->first();
        $update = ContactUs::where('id',$id)->update([
        	'is_viewed'=>1,
        ]);
        activity('Message viewed')
           ->causedBy(Auth::user())
            ->performedOn(new ContactUs())
            // ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Message viewed by ' . Auth::user()->name);
        return view('admin.contact_us_list.contact_us_view', compact('post'));
    }

    public function reply(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'subject' => 'required|max:255',
            'message' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
        	if(isset($request->email) && !empty($request->email)){
		      if (isset($request->hosts) && !empty($request->hosts)) {
		        $host = EmailHost::where('id', $request->hosts)->first();
		      } else{
		        $host = EmailHost::where('is_default', '1')->first();
		      }
		      /* checking cc and bcc email status */
		      $cc_email=$bcc_email="";
		      if ($host->cc_status == 1) {
		        $cc_email = $host->cc_email;
		      }

		      if ($host->bcc_status == 1) {
		        $bcc_email = $host->bcc_email;
		      }
		      /*set env*/
		      Config::set('MAIL_HOST', $host->name);
		      Config::set('MAIL_PORT', $host->port);
		      Config::set('MAIL_USERNAME', $host->username);
		      Config::set('MAIL_PASSWORD', $host->secret);
		      Config::set('MAIL_ENCRYPTION', $host->security);
		      Config::set('MAIL_FROM_ADDRESS', $host->from_email);
		      Config::set('MAIL_FROM_NAME', $host->from_name);

		      $email = $request->email;
		      $username = $request->name;

		      if (!empty($request->subject) && !empty($request->message)) {
		        $subject = trim($request->subject);
		        $msg = trim($request->message);
		    	try{
				    $msg = str_replace('{{name}}', $username, $msg);
		            $data2 = [
		              'email' => $email,
		              'username' => $username,
		              'subject' => $subject,
		              'content' => $msg,
		              'from_name' => $host->from_name,
		              'from_email' => $host->from_email,
		            ];
		            Mail::to($email, $username)
		            ->cc($cc_email)
		            ->bcc($bcc_email)
		            ->send(new SingleMail($data2));
		            $message = trans('admin.Mail_has_been_send');
		            $cls = 'success';

                    /*replay counter*/
                    $post = ContactUs::find($request->id)->first();
                    $replyCount=$post->reply_count+1;
                    $update = ContactUs::where('id',$request->id)->update([
                        'reply_count'=>$replyCount,
                    ]);
				}catch(Exception $ex){
					$message = trans('admin.Connection_Fail');
					$cls = 'error';
				}

		        activity('Email Send')
		        ->causedBy(Auth::user())
		        ->tap(function (Activity $activity) {
		            $activity->route_link = $this->url;
		        })
		        ->log('Email Send by ' . Auth::user()->name.' to '.$data2['email']);
		    	return redirect()->back()->with($cls,$message)->withInput();
		      } else{
		        return redirect()->back()->with('error',trans('admin.write_somethings'))->withInput();
		      }
		  	} else{
		  		return redirect()->back()->with('error',trans('admin.email_not_found'))->withInput();
		  	}
        }
        activity('Email send')
        ->causedBy(Auth::user())
        ->performedOn(new ContactUs())
        // ->withProperties(['old'  => [], 'modified'=>$data])
        ->tap(function (Activity $activity) {
            $activity->route_link = $this->url;
        })
        ->log('Email send by ' . Auth::user()->name);
    }
}
