<?php

namespace App\Http\Controllers\Mailgun;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

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

        try {
                
            $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.');
            }
                
                $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)
                        $response = createResponse($ticket->id,$message);
                }else{}
                
               // update_setting('aw_test',json_encode($request->all()));
                
            DB::commit();
        } catch (\Exception $e) {
            update_setting('aw_test',$e->getMessage());
            DB::rollBack();
            // Handle the exception
        }
        
    }
    
    
    public function extractMailgunData($data) {
        
        // Prepare an array to hold the extracted data
        $extractedData = [
            'from_email' => $data['from'],
            'to_email'   => $data['To'],
            'from_name'  => '',  // This will be extracted from the 'from' field
            'subject'    => $data['subject'],
            'message'    => $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;
    }
}
