<?php

use App\Models\CompanyMeta;
use App\Models\Settings;
use App\Models\Ticket;
use App\Models\Response;
use App\Models\TicketNote;
use Illuminate\Support\Facades\Session;
use Mailgun\Mailgun;
use App\Models\Company;


function get_company($key,$value){
    return Company::where($key,$value)->first();
}

function get_current_company_tickets($args = []){
    
        $companyId = getSelectedCompany();
       
        if(!$companyId){
            return false;
        }
    
        $company = get_company('id',$companyId);
        
         if(!$company){
            return false;
        }
        
        $tickets = Ticket::where('to_email', $company->email);
        
        $tickets->orderBy('created_at','desc');
        
        if(isset($args['type'])){
            $tickets->where('type',$args['type']);
        }
        
        if(isset($args['status'])){
            $tickets->where('status',$args['status']);
        }
        
        if(isset($args['orderby'])){
            $tickets->orderBy($args['orderby'],$args['order']??'asc');
        }
        
        if(isset($args['with'])){
            $tickets->with($args['with']);
        }
        
        $tickets = $tickets->get();
        
        return $tickets;
}

function getResponse($company_id, $key, $type) {
    $meta = CompanyMeta::where('company_id', $company_id)->where('key', $key)->where('type', $type)->first();
    return $meta;
}

function update_setting($key,$value){
    return Settings::updateOrCreate(['key' => $key], ['value' => $value]);
}

function get_setting($key){
    return Settings::where('key',$key)->first()??false;
}

function delete_setting($key){
    return Settings::where('key',$key)->delete();
}

function verifyMailgunSignature($token, $timestamp, $signature)
{
    // Retrieve your Mailgun webhook signing key from your .env file
    $signingKey = env('MAILGUN_WEBHOOK_SIGNING_KEY');
    
    // Recreate the signature
    $expectedSignature = hash_hmac('sha256', $timestamp . $token, $signingKey);

    // Compare the Mailgun-provided signature with the expected signature
    return hash_equals($expectedSignature, $signature);
}
//Insert Ticket 
if (!function_exists('insertTicket')) {
    function insertTicket($from_email, $to_email, $subject, $content, $type, $sender_name) {
        
        $check = Ticket::where(function ($query) use ($from_email, $to_email) {
                $query->where('from_email', $from_email)
                      ->where('to_email', $to_email);
            })
            ->where(function ($query) use ($subject) {
                $cleanSubject = trim(str_ireplace('Re:', '', $subject)); // Remove 'Re:' prefix and trim whitespace
                $query->where('subject', $cleanSubject)
                      ->orWhere('subject', 'Re: ' . $cleanSubject); // Consider both with and without 'Re:'
            })
            ->first();

        
        
        if(!$check){
        
            $ticket = new Ticket;
            $ticket->from_email = $from_email;
            $ticket->to_email = $to_email;
            $ticket->type = $type;
            $ticket->sender_name = $sender_name;
            $ticket->subject = $subject;
            $ticket->content = $content;
            $ticket->priority = 'low';
            $ticket->status = 'waiting';
            $ticket->parent_id = 0;
            $ticket->user_assigned = 0;
            $ticket->save();
        
        }else{
            $ticket = $check;
        }
        
        return $ticket;
    }
}
//Get Selected Company
if (!function_exists('getSelectedCompany')) {
    function getSelectedCompany() {
        $company = Session::get('selected_company');
        if (!$company) {
            return false;
        }
        return $company;
    }
}
//Get Ticket
if (!function_exists('getTicket')) {
    function getTicket($id) {
        $ticket = Ticket::find($id); 
        if (!$ticket) {
            return response()->json(['message' => 'Ticket not found'], 404);
        }
        return $ticket;
    }
}
//Get Response
if (!function_exists('getTicketResponse')) {
    function getTicketResponse($id) {
        $response = Response::find($id); 
        if (!$response) {
            return response()->json(['message' => 'Response not found'], 404);
        }
        return $response;
    }
}
//Get Ticket Note
if (!function_exists('getTicketNote')) {
    function getTicketNote($id) {
        $ticket_note = TicketNote::find($id);
        if (!$ticket_note) {
            return response()->json(['message' => 'Ticket Note not found'], 404);
        }
        return $ticket_note;
    }
}
if (!function_exists('containsHtml')) {
    function containsHtml($string) {
        return $string != strip_tags($string);
    }
}

if (!function_exists('sendEmailViaMailgun')) {
    function sendEmailViaMailgun( $domain, $from, $to, $subject, $html) {
        
        $apiKey = env('MAILGUN_SECRET');
        
        // Create a new Mailgun instance with API credentials
        $mg = Mailgun::create($apiKey);
    
        // Prepare the message parameters
        $params = [
            'from'    => $from,
            'to'      => $to,
            'subject' => $subject,
            'html'    => $html
        ];
    
        // Send the email
        $response = $mg->messages()->send($domain, $params);
    
        // Return the response from Mailgun
        return $response;
    }
    
    function createResponse($ticket_id, $message, $user_id = 0)
    {
        // Create a new Response instance
        $response = new Response;
    
        // Set the properties of the Response
        $response->message = $message;
        $response->ticket_id = $ticket_id;
        $response->user_id = $user_id; // You may want to dynamically set the user_id based on the authenticated user
    
        // Save the response to the database
        $response->save();
    
        // Return the created response
        return $response;
    }
}
