<?php

namespace App\Http\Controllers\Mailgun;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Models\Ticket;
use App\Models\Response;

class EmailController extends Controller
{
    public function saveEmail(Request $request){
         
        // DB::beginTransaction();

        // try {
            
            $file_urls = [];
            $token = $request->input('token');
            $timestamp = $request->input('timestamp');
            $signature = $request->input('signature');
        
            if (!verifyMailgunSignature($token, $timestamp, $signature)) {
                update_setting('aw_test','Invalid signature.');
                abort(403, 'Invalid signature.');
            }
             update_setting('aw_test',json_encode($request->all()));
                
                $data = $this->extractMailgunData($request->all());
                
                
                
                $to_email = $data['to_email'];
                $message = $data['message'];

                //update_setting('aw_test',$to_email);
                
                $company = get_company('email',$to_email);
                
                if($company){
                    $ticket = insertTicket($data['from_email'], $company->email, $data['subject'], $message,'inbox',$data['from_name'] );
                    if($ticket){
                        
                        //Check Email if it is spam
                        $get_spam_handlings = getResponse($company->id,'spam_handling', 'Spam Handling');
                        if(!is_null($get_spam_handlings)) {
                            //pluck spam emails
                            $values = json_decode($get_spam_handlings->value, true);
                            $spam_emails = array_map(function ($item) {
                                return $item['spam_email'];
                            }, $values);
                            if(in_array($data['from_email'], $spam_emails)) {
                                //update status
                                $ticket->status = 'spam';
                                $ticket->save();
                            }
                        }
                        
                        $this->sendEmail($company,$ticket->id);
                        
                        $response = createResponse($ticket->id,$message);
                        
                        $attachmentCount = $request->input('attachment-count', 0);
                        

                        for ($i = 1; $i <= $attachmentCount; $i++) {
                            $attachment = $request->file("attachment-$i");
                           // update_setting('aw_test',$attachment->getClientOriginalName());
                            if ($attachment && $attachment->isValid()) {
                                // Define a unique filename, possibly using the original filename and appending a timestamp or a unique id
                                $filename = time() . '_' . $attachment->getClientOriginalName();
                
                                // Save the attachment to the local or specific disk
                                $filePath = $attachment->storeAs('tickets/' . $ticket->id, $filename, 'public');
                                $fileUrl = Storage::url($filePath);
                                $file_urls[] = $fileUrl;
                                
                            }
                        }
                        
                        //Update Responses Table with Attachments
                        if(count($file_urls) > 0) {
                            $response->attachments = json_encode($file_urls);
                            $response->save();
                        }
                        
                    }
                }else{}
                
                //update_setting('aw_test',json_encode($request->all()));
                
        //     DB::commit();
        // } catch (\Exception $e) {
            
        //     DB::rollBack();
        //     update_setting('aw_test',json_encode($e->getMessage()));
        //      sendEmailViaMailgun( 'ai.rapidev.tech', 'support@ai.rapidev.tech', '16bsse18212@gmail.com', 'error', json_encode($e->getMessage()));
        //     // Handle the exception
        // }
        
    }
    
    private function sendEmail($company,$ticketId)
    {
        $ticket = Ticket::find($ticketId);
        $responses = Response::where('ticket_id', $ticket->id)->get();
        $activate_delivery_confirmation = getCompanyMeta($company->id,'activate_delivery_confirmation');
        $subject = getCompanyMeta($company->id,'automatic_reply_subject');
        $subject = str_replace(['{title}', '{ticket}'], [$ticket->subject, $ticket->id], $subject);
        $message = getCompanyMeta($company->id,'automatic_reply_text');
        $message = str_replace(['{title}', '{text}', '{ticket}', '{name}'], [$ticket->subject, $ticket->content, $ticket->id, $ticket->sender_name], $message);
        if ($ticket && count($responses) == 0 && !is_null($subject) && !is_null($message) && $activate_delivery_confirmation == 'on') {
            
            $company_name = $company->getMeta('sender_name')??$company->name;
            $from = "$company_name <$company->email>";
            
            sendEmailViaMailgun($company->domain, $from, $ticket->from_email, $subject, $message);
        }
        //Update Ticket With Subject2
        $ticket->subject2 = $subject;
        $ticket->save();
    }
    
    
    public function extractMailgunData($data) {
        
        // Prepare an array to hold the extracted data
        
        $from = extractEmail($data['from']);
        $to = extractEmail($data['To']);
        
        $extractedData = [
            'from_email' => $from,
            'to_email'   => $to,
            'from_name'  => '',  // This will be extracted from the 'from' field
            'subject'    => $data['subject'],
            'message'    => isset($data['body-html'])?$data['body-html']:$data['body-plain'],
            'mime_version' => $data['Mime-Version'],
            'dkim_signature' => $data['Dkim-Signature']
        ];
    
        // Extract the sender's name from the 'from' field
        if (preg_match('/^(.*?) <(.*?)>$/', $data['from'], $matches)) {
            $extractedData['from_name'] = $matches[1];
            $extractedData['from_email'] = $matches[2];
        }
  
        return $extractedData;
    }
}
