<?php

namespace App\Http\Controllers\Mailgun;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class EmailController extends Controller
{
    public function saveEmail(Request $request){
        
    $token = $request->input('token');
    $timestamp = $request->input('timestamp');
    $signature = $request->input('signature');

    // if (!verifyMailgunSignature($token, $timestamp, $signature)) {
    //     abort(403, 'Invalid signature.');
    // }
        
        $data = $this->extractMailgunData($request->all());
        
        insertTicket($data['from_email'], $data['to_email'], $data['subject'], $data['message'] );
        
        update_setting('aw_test',json_encode($request->all()));
        
    }
    
    
    public function extractMailgunData($data) {
        // Decode the JSON payload into an associative array
       // $data = json_decode($jsonPayload, true);
    
        // 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;
    }
}
