<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Mail;
use Response;
use Validator;
use App\Models\Admin\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\Admin\EmailHost;
use App\Models\Admin\Email_templates;
use App\Mail\MultiMail;
use DataTables;
use Config;

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

class MailingController 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()) {
        $data = User::select('*')->where('type','!=','admin')->where('status','1')->orderBy('id', 'desc');
        return Datatables::of($data)
        ->addIndexColumn()
        ->setRowId(function ($row) { return $row->id; })
        ->addColumn('id', function($row){
          
          $btn = '
            <label class="container1 p-0">
              <input class="chk sub-check" onchange="counter();" type="checkbox" value="'.$row->id.'" name="chk[]" id="chk[]" />
              <span class="checkmark"></span>
              <!--<label class="form-check-label m-3" for="flexCheckDefault">
                '.getUserType($row->user_type).'
              </label>-->
            </label>
          ';
          return $btn;
        })
        ->addColumn('name', function($row){
       
          $btn = '
            <sapn class="fw-bold text-dark">'.$row->name.'</sapn><br>
            <span>'.getUserType($row->user_type).'</span>
          ';
          return $btn;
        })
        ->filter(function ($record) use ($request) {
          if ($request->has('search')) {
            $record->where('name', 'like', "%" . $request->get('search')['value'] . "%");
          }

          if ($request->has('user_filter') && $request->user_filter != "") {
              $record->where('user_type', '=', $request->get('user_filter'));
          }

          if ($request->has('locale_filter') && $request->locale_filter != "") {
              $record->where('locale', '=', $request->get('locale_filter'));
          }

        })
        ->rawColumns(['id', 'name'])
        ->make(true);
      }
    activity('Send Emails Page Visited')
    ->causedBy(Auth::user())
    ->tap(function (Activity $activity) {
        $activity->route_link = $this->url;
    })
    ->log('Send Emails page Visited by ' . Auth::user()->name);
    return view('admin/send_mail.mailing');
  }

  public function send(Request $request)
  {
  	if(isset($request->uid) && !empty($request->uid)){
      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);

      if (!empty($request->subject) && !empty($request->message)) {
        $subject = trim($request->subject);
        $msg = trim($request->message);
        $files = $request->file('attach');
        $uidAry=explode(",",$request->uid);

    		for($i=0; $i<count($uidAry); $i++){
    			try{
            $username = getAny('name', 'users', 'id', $uidAry[$i]);
    				$email = getAny('email', 'users', 'id', $uidAry[$i]);
            if (isset($request->template) && !empty($request->template)) {
              $template = Email_templates::where('id', $request->template)->first();
              $params = explode(',', $template->params);
              foreach ($params as $value) {
                $msg = str_replace($value, $username, $msg);
              }
            } else{
              $msg = str_replace('{{username}}', $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 MultiMail($data2, $files));
            $message = trans('admin.Mail_has_been_send');
    			}catch(Exception $ex){
    				$message = trans('admin.Connection_Fail');
    			}
    		}

        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']);

    		echo json_encode(array('text' => $message, 'cls' => 'success'));

      } else{
        echo json_encode(array('text' => trans('admin.write_somethings'), 'cls' => 'warn'));
      }
  	} else{
  		echo json_encode(array('text' => trans('admin.Select_user'), 'cls' => 'info'));
  	}
  }

  /*get templates*/
  public function get_template($id)
  {
    $data = Email_templates::find($id);
    echo json_encode(array('subject' => $data->subject, 'params' => $data->params, 'content' => $data->content));
  }
}
