<?php

namespace App\Http\Controllers;

use App\Traits\ChimpTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class MailApiController extends Controller
{
    use ChimpTrait;

    public function sendApiEmail(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'username'    => "required|exists:users",
            'password'    => "required",
            'subject'     => "required",
            'from_name'   => "required",
            'from_email'  => "required|email",
            'name'        => "required",
            'date'        => 'required',
            'destination' => "required|email",
        ]);


        if ($validator->fails()) {
            return response()->json(['code'=>401,'msg'=>$validator->errors()->all()]);
        }


        $credentials = $request->only('username','password');

        if(Auth::attempt($credentials))
        {
            $values = (object)$request->all();
            return response()->json($this->apiAudience($values));
        }


        return response()->json(['code'=>401,'msg'=>'Invalid username or password']);



    }


//    public function prepareEmail($values)
//    {
//
//
//        $subaccount = 'npontuapp';
//
//        $message = array(
//            'html' => "<p>$values->message</p>",
//            'subject' => $values->subject,
//            'from_email' => 'oboateng@npontu.com',
//            'from_name' => 'npontu',
//            'to' => array(
//                array(
//                    'email' => $values->destination,
//                    'type' => 'to'
//                )
//            ),
//            'headers' => array('Reply-To' => 'message.reply@example.com'),
//            'important' => true,
//            'inline_css' => true,
//            'tags' => array('transactional-sms'),
//            'subaccount' => $subaccount,
//        );
//
//        $values->message = $message;
//        $values->async = true;
//        return $this->triggerRequest($values);
//
//    }

    public function triggerRequest($params)
    {
        $response = null;
        try {
        $mandrill = $this->initApi();
        $response = $mandrill->messages->send($params->message, $params->async);
        }catch (\Exception $ex)
        {
            return response()->json(['code'=>401,'msg'=>$ex->getMessage()]);
        }

        return $response;
    }

    /** @noinspection PhpPossiblePolymorphicInvocationInspection */
    public function apiAudience($params)
    {
//        return $this->init()->get('lists');
        try {

            $_campaignContent = null;
            $params->message = $params->name;

            $list = (object)[

                'name' => $this->_unique($params),
                'from_name' => $params->from_name,
                'from_email' => $params->from_email,
                'language' => 'en',
                'permission_reminder' => 'You are signed up for updates from Stanbic Bank Ghana.',
                'subject' => $params->subject,
                'company' => 'Stanbic Bank Ghana Limited',
                'address1' => 'Stanbic Heights, 215 South Liberation Road',
                'address2' => 'Airport City',
                'city' => 'Accra',
                'state' => 'Greater Accra Region',
                'country' => 'Ghana',
                'zip' => '233',
                'phone' => '302815789',
            ];


            if (!empty($params->attachment))
            {

                $image = $this->convertImage($params);
                $params->resource = $image;
                $params->attachment = null;

            }


            $this->log("MESSAGE {$ex->getMessage()} || ".json_encode($params));


            $user = Auth::user();
            DB::beginTransaction();

            $transaction = $user->mail_api()->create((array)$params);
            $listQuery = $user->mail_api()->where('destination', $params->destination)->whereNotNull('list_id')->first();  //get list id
            !empty($listQuery) ? $transaction->update(['list_id' => $listQuery->list_id])
                : $transaction->update(['list_id' => $this->ApiList($list)->id ?? null]); //update or else create api list

            //add the email address to the audience group
            $subscriber_hash = $this->init()::subscriberHash("{$params->destination}");
            $this->init()->put("lists/{$transaction->list_id}/members/{$subscriber_hash}", [
                'email_address' => $params->destination, 'status' => 'subscribed', 'status_if_new' => 'subscribed',]);

            DB::commit();

            $params->list_id = $transaction->list_id;

            $_postCampaign = (object)$this->apiCampaign($params);

            if (isset($_postCampaign->id))
                $_campaignContent = $this->apiCampaignContent($_postCampaign->id, $params);


            $isSent = null;
            if ($_campaignContent)
                $isSent = $this->init()->post("campaigns/{$_postCampaign->id}/actions/send");


            if ($isSent) {
                $transaction->update(['is_sent' => true]);
                return response()->json(['code' => 200, 'msg' => '1 email sent']);
            } else {
                return response()->json(['code' => 200, 'msg' => 'received']);
            }
        }catch (\Exception $ex){
            $this->log("ERROR {$ex->getMessage()} || ".json_encode($params));
            return response()->json(['code' => 200, 'msg' => 'failure']);
        }


    }

    public function _unique($params)
    {
       return strtolower(Str::random(3)).explode('@',$params->destination)[0];
    }

    public function ApiList($list)
    {
        try {
            $chimp = $this->init();
            return (object) $chimp->post('lists',[
                'name'=>$list->name,
                'contact'=>[
                    'company'=>$list->company,
                    'address1'=>$list->address1,
                    'address2'=>$list->address2,
                    'city'=>$list->city,
                    'state'=>$list->state,
                    'zip'=>$list->zip,
                    'country'=>$list->country,
                    'phone'=>$list->phone,
                ],
                'permission_reminder'=>$list->permission_reminder,
                'email_type_option'=>false,
                'campaign_defaults'=>[
                    'from_name'=>$list->from_name,
                    'from_email'=>$list->from_email,
                    'subject'=>$list->subject,
                    'language'=>$list->language,
                ]
            ]);

        } catch (\Exception $e){
            return $e->getMessage();
        }
    }

    public function apiCampaign($params)
    {
        return $this->init()->post('campaigns', [
            'type' => 'regular',
            'recipients' => [
                'list_id' => $params->list_id,
            ],
            'settings' => [
                'from_name' =>    $params->from_name,
                'reply_to' =>     $params->from_email,
                'subject_line' => $params->subject,
                'preview_text' => $params->subject,
                'title' =>        $params->subject,
                'template_id' =>  $this->api_template,
            ],
        ]);
    }

    public function apiCampaignContent($campaignId,$params)
    {
        $app = env('APP_URL');
        $path =  "$app/storage/attachment/".@$params->resource;
        $body_imageContent = [
            'name'     => '<span style="font-size:20px;">'.$params->name ?? null.'</span>',
            'date'     => $params->date,
            'attached' => "<a style='color: black' href='$path'>Click to download the PDF attached to this email.</a>"
        ];
        return $this->init()->put("campaigns/{$campaignId}/content", [
            'template' => [
                'id' => $this->api_template,
                'sections' => $body_imageContent
            ]
        ]);
    }

    public function convertImage($params)
    {
        $img  = $params->attachment;   //base64 code
        $name = $params->name;

        $name = $name.date('h:i:s').'.pdf';
        $_name = str_replace(' ', '_', $name);
        $img =  str_replace(' ', '+', $img);

        /*** End of Base64 Conversion ***/
        $img = base64_decode($img);
        File::put(storage_path(). '/app/public/attachment/' .$_name, $img);
        return $_name;
    }

}
