<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\Email;
use App\Models\EmailsToken;
use App\Models\EmailsTemplate;
use App\Models\RecipientsGroup;
use App\Models\EmailsRecipient;


use App\Models\UsersRole;
use App\Models\User;
use Carbon\Carbon;

use App\Libraries\Generic;


class EmailsController extends Controller
{
    
    protected $generic;
    
    public function __construct(){
        
        $this->generic = new Generic();
        
    }
    
    public function getEmailTokens(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        // if(!User::checkPermission('get-email-tokens')){
        //     return response()->json(config('constants.messages.permission_denied'), 400);
        //     exit();
        // }
        
        $tokens = EmailsToken::all();
        $tokens = (!empty($tokens)) ? $tokens->toArray() : [];
        
        return response()->json(['tokens' => $tokens]);
        
    }
    
    
    public function getRecipientsGroups(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        // if(!User::checkPermission('get-email-tokens')){
        //     return response()->json(config('constants.messages.permission_denied'), 400);
        //     exit();
        // }
        
        $recipients_groups = RecipientsGroup::all();
        $recipients_groups = (!empty($recipients_groups)) ? $recipients_groups->toArray() : [];
        
        return response()->json(['recipients_groups' => $recipients_groups]);
        
    }
    
    
    public function getMyEmailsTemplatesList(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        if(!User::checkPermission('get-my-emails-templates-list')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $templates = EmailsTemplate::where(['owner_id'=>$owner_id])->orWhere(['creator_id'=>$user_id])->distinct()->get();
        $templates = (!empty($templates)) ? $templates->toArray() : [];
        
        return response()->json(['templates' => $templates]);
        
    }
    
    public function getMyEmailTemplate(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        if(!User::checkPermission('get-my-email-template')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $email_template_id = $request->query('email_template_id');
        $email_template = EmailsTemplate::find($email_template_id);
        
        // check if email template exists
        if(empty($email_template)){
            return response()->json(['message' => 'No template found']);
        }
        
        // check if have access to use
        if($email_template->owner_id != $owner_id && $email_template->creator_id != $user_id){
            return response()->json(config('constants.messages.invalid_access'), 400);
            exit();
        }
        
        return response()->json(['template' => $email_template]);
        
    }
    
    
    public function saveEmailTemplate(Request $request){
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('save-email-template')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'body' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $update_criteria = [];
        if(!empty($request->id)){
            $update_criteria['id'] = $request->id;
        }
        else{
            $update_criteria['id'] = 0;
        }
        
        $email_template = EmailsTemplate::updateOrCreate(
            $update_criteria, 
            [
                'name' => $request->name,
                'subject' => $request->subject ?? '',
                'body' => $request->body,
                'creator_id' => $user_id,
                'owner_id' => $owner_id,
            ]
        );
        
        $email_template_id = $email_template->id;
        
        return response()->json(['message' => 'Added Successfully', 'data'=> $email_template_id ]);
        
    }
    
    public function saveEmailAsDraft(Request $request){
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('save-email-as-draft')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }

        $validator = Validator::make($request->all(), [
            'body' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $update_criteria = [];
        if(!empty($request->id)){
            $update_criteria['id'] = $request->id;
        }
        else{
            $update_criteria['id'] = 0;
        }
        
        $email = Email::updateOrCreate(
            $update_criteria, 
            [
                'subject' => $request->subject ?? '',
                'body' => $request->body,
                'is_draft' => 1,
                'creator_id' => $user_id
            ]
        );
        
        $email_id = $email->id;
        
        // save files
        $files = $request->files ?? [];

        foreach($files as $f){
            
            $update_criteria = [];
            if(!empty($f['id'])){
                $update_criteria['id'] = $f['id'];
            }
            else{
                $update_criteria['id'] = 0;
            }
            
            EmailsFile::updateOrCreate($update_criteria, [
                'file' => $f['file'],
                'email_id' => $email_id,
            ]);
        }
        
        // save recipients
        $recipients = $request->recipients;
        $this->saveRecipients($email_id, $recipients);
        
        return response()->json(['message' => 'Added Successfully']);
        
    }
    
    private function saveRecipients($email_id, $recipients){
        
        // $recipients = [
        //     'group_ids' => [3, 4],
        //     'user_ids' => [87],
        //     'unit_ids' => [189]
        // ];
        
        // delete pervious recipients
        EmailsRecipient::where(['email_id'=>$email_id])->delete();
        
        // groups
        foreach($recipients['group_ids'] as $g){
            EmailsRecipient::create([
                'email_id' => $email_id,
                'user_id' => null,
                'recipient_group_id' => $g,
                'unit_id' => null
            ]);
        }
        
        // users
        foreach($recipients['user_ids'] as $u){
            EmailsRecipient::create([
                'email_id' => $email_id,
                'user_id' => $u,
                'recipient_group_id' => null,
                'unit_id' => null
            ]);
        }
        
        // units
        foreach($recipients['unit_ids'] as $u){
            EmailsRecipient::create([
                'email_id' => $email_id,
                'user_id' => null,
                'recipient_group_id' => null,
                'unit_id' => $u
            ]);
        }
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

}