<?php
/*
Author: Jaypee M. Sanchez
Project: G.D.P.R
Date: July 2018
*/

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Config;
use Carbon\Carbon;
use Exception;
use Mail;
use App\Login;

class CrmMailController extends BaseController
{

    private $m = '';
    private $s = '';
    private $r = '';
    private $f = array();
    private $headers = '';
    private $hash = '';
    private $domain = '';
    private $ReadableLabel = array();

    public function __construct($param = array()){

      $this->ReadableLabel = array(
        'fname' => 'First Name', 'lname' => 'Last Name', 'fullname' => 'Full Name',
        'company' => 'Full Company', 'prefix' => 'Prefix', 'email' => 'Email',
        'general_number' => 'General Number', 'direct_number' => 'Direct Number',
        'mobile_number' => 'Mobile Number', 'fax' => 'Fax', 'address_type' => 'Address Type',
        'street1' => 'Street 1', 'street2' => 'Street 2', 'city' => 'City', 'state' => 'State',
        'zip' => 'Zip', 'country' => 'Country', 'language' => 'Language',
      );

      $this->domain = config('custom.app_domain');
      $this->hash = isset($param['hash']) ? $param['hash'] : '';
      $this->m = isset($param['message'])  ? $param['message'] : "Greetings Admin. <br><br> A user wants to delete an account. Below are the details: <br><br>";
      $this->s = isset($param['subject'])  ? $param['subject'] : '[GDPR] Delete Account Approval';
      $this->r = isset($param['receiver']) ? $param['receiver'] : config('custom.admin_email');
      $this->f = isset($param['from'])     ? $param['from'] : config('mail.from');
      $this->return['code'] = 500;
      $this->return['msg'] = 'Error. Please try again. If error persist please contact system admin';
    }

    public function send($type, Request $request = NULL){

      if ($type == 'delete_approval'){
        try {
          if (!$this->_checkTokenValidity($request->header('Authorization'))) {
            throw new Exception('Token Sent has Expired');
          }
          $this->s = '[ERNI Privacy Center] Delete Account Approval';
          $this->m .= "First Name: " . $request->fname ."<br>";
          $this->m .= "Last Name: " . $request->lname . "<br>";
          $this->m .= "Email Name: " . $request->email . "<br>";
          $this->m .= "<br><br> Regards<br>Admin";        
            if (Mail::send([], [], function($msg) {
              $msg->setBody($this->m, 'text/html');
              $msg->replyTo('no_reply.privacy@erni.ch', $this->f['name']);
              $msg->subject($this->s); 
              $msg->to($this->r);
            })) {
            return response()->json( ['message' => 'Request for deleting account has been sent. We will process your request.'] );
          } else {
            return response()->json( ['message' => 'Unsuccessful send to client. Please try again'], 500 );
          }
        } catch (Exception $e) {
          if ($e->getMessage() == "Invalid Login String") return response()->json(['message' => $e->getMessage()], 404);
          return response()->json(['message' => $e->getMessage()], 500);
        }  
      
      } else if($type == 'update_approval'){

        try {
          if (!$this->_checkTokenValidity($request->header('Authorization'))) {
            throw new Exception('Token Sent has Expired');
          }
          $this->s = '[ERNI Privacy Center] Update Profile Approval';
          $this->m = "Greetings Admin. <br><br> A user wants to update his/her account. Below are the details: <br><br>";
          $this->m .= "<br><b>Original User:</b><br>";
          $this->m .= "First Name: " . $request->old['fname'] ."<br>";
          $this->m .= "Last Name: " . $request->old['lname'] . "<br>";
          $this->m .= "Email: " . $request->old['email'] . "<br>";
          $this->m .= "<hr/>";
          $this->m .= "<br><b>Fields to Update:</b><br>";
          $this->m .= "<table><tbody>";
          
          $this->m .= $this->format_tr('fname', $request);
          $this->m .= $this->format_tr('lname', $request);
          $this->m .= $this->format_tr('fullname', $request);
          $this->m .= $this->format_tr('email', $request);
          $this->m .= $this->format_tr('company', $request);
          $this->m .= $this->format_tr('prefix', $request);
          $this->m .= "<tr><td>Alumni:</td><td>" . ($request->new['alumni'] ? 'Yes' : 'No') ."</td><tr>";
          $this->m .= "<tr><td>Contractor:</td><td>" . ($request->new['contractor'] ? 'Yes' : 'No') ."</td><tr>";
          
          $this->m .= $this->format_tr('general_number', $request);
          $this->m .= $this->format_tr('direct_number', $request);
          $this->m .= $this->format_tr('mobile_number', $request);
          $this->m .= $this->format_tr('fax', $request);
          $this->m .= $this->format_tr('address_type', $request);

          $this->m .= $this->format_tr('street1', $request);
          $this->m .= $this->format_tr('street2', $request);

          
          $this->m .= $this->format_tr('city', $request);
          
          $this->m .= $this->format_tr('state', $request);
          $this->m .= $this->format_tr('zip', $request);
          
          $this->m .= $this->format_tr('country', $request);
          $this->m .= $this->format_tr('language', $request);
          $this->m .= "</tbody></table>";
          $this->m .= "<br><br> Regards<br>Admin";
          
          if (Mail::send([], [], function($msg) {
              $msg->setBody($this->m, 'text/html');
              $msg->replyTo('no_reply.privacy@erni.ch', $this->f['name']);
              $msg->addFrom('no_reply.privacy@erni.ch', $this->f['name']);
              $msg->subject($this->s); 
              $msg->to($this->r);
            })) {
            return response()->json( ['message' =>'Success sending of update approval to Admin'] );
          } else return response()->json( ['message' => 'Error in sending Update aproval. Please try again'], 500 );

        } catch (Exception $e) {
          if ($e->getMessage() == "Invalid Login String") return response()->json(['message' => $e->getMessage()], 404);
          return response()->json(['message' => $e->getMessage()], 500);
        }  

      } else if ($type == 'login_attempt'){
        $this->m = "Dear User
                    <br><br> Please click 
                    <a href = '$this->domain/login/".$this->hash."'>here</a> to access your GDPR Privacy Center Account. 
                    <br><br>
                    Regards
                    <br>
                    Your ERNI Data Privacy Team
                    ";
        if (Mail::send([], [], function($msg) {
            $msg->setBody($this->m, 'text/html');
            $msg->replyTo('no-reply.privacy@erni.ch', $this->f['name']);
            $msg->subject($this->s); 
            $msg->to($this->r);
          })) {
          return response()->json( 'Successfully sent a login link in to your Email' );
        } else return response()->json( ['message' => 'Email not sent! Please try again'], 500 );
      } else if ($type == 'testemail' && $request->email){

        $this->r = $request->email;
        $this->s = "[GDPR] Test Email";
        $this->m = "Greetings User. <br><br> Please click <a href = '$this->domain/login/".'test'."'>here</a> to access your GDPR Privacy Center Account. <br><br> Regards";
        if (Mail::send([], ['title' => 'thisis the title'], function($msg) {
          $msg->setBody($this->m, 'text/html');
          $msg->subject($this->s); 
          $msg->to($this->r);
        })) {
          return response()->json( ['message' => 'Successfully Test Email'] );
        } else return response()->json( ['message' => 'Unsuccess Test Email'], 500 );
      }

      return response()->json( ['message' => 'Unknown Request'], 400 );
    }

    public function sendMail(){

       
      if (Mail::raw('Raw string email Then then then', function($msg) { 
            $msg->to(['jaypee.sanchez@erni.ph']);
            $msg->replyTo('no_reply.privacy@erni.ch', 'ReplyTitle'); // works when user clicks reply
            $msg->subject('Gipipoy Subject');
            // $msg->setFrom('no_reply.privacy@erni.ch', 'from title');
            // $msg->addFrom('no_reply.privacy@erni.ch', 'SEndername'); //working
            // $msg->setFrom('no_reply.privacy@erni.ch', 'SEndername'); //this also working
      })) {
        return response()->json( ['message' => 'success'] );
      }
      // return response()->json( [$this->domain] );

    }

    private function format_tr($property = '', $request = NULL) {

      if ( !isset($request->new[$property]) && !isset($request->old[$property]) ){
        return "";
      } else if ( !isset($request->new[$property]) && isset($request->old[$property]) ) {
        return "<tr><td>".$this->ReadableLabel[$property].":</td><td><br> [USER-WANTS-EMPTY] </br></td><tr>";
      } else if (!isset($request->old[$property]) &&  isset($request->new[$property])) {
        return "<tr><td>".$this->ReadableLabel[$property].":</td><td><br>" . $request->new[$property] ."</br></td><tr>";
      } else if ($request->old[$property] == $request->new[$property]) {
        return "<tr><td>".$this->ReadableLabel[$property].":</td><td>" . $request->old[$property] ."</td><tr>";
      } else {
        $newProperty = $request->new[$property] != '' ? $request->new[$property] : '[USER-WANTS-THIS-FIELD-EMPTY]' ;
        return "<tr><td>".$this->ReadableLabel[$property].":</td><td> <b>FROM:</b> " . $request->old[$property] . ' <b>CHANGE TO: </b>'. $newProperty ."</td><tr>";
      }
    }

    private function _checkTokenValidity($token = '') {
      $token = explode(' ', $token);
      $newModel = new Login();
      if ($r = $newModel->where('hash_key', '=', $token[1])->where('status', '=', 'A')->orderBy('id', 'desc')->first()){
        if ($r->created_at < Carbon::now()->subMinutes(60)->toDateTimeString()) {
          return false;
        }
      };
      return true;
    }

}