<?php

use App\Models\CompanyMeta;
use App\Models\Settings;
use App\Models\Ticket;
use App\Models\TicketMeta;
use App\Models\Response;
use App\Models\TicketNote;
use Illuminate\Support\Facades\Session;
use Mailgun\Mailgun;
use App\Models\Company;
use App\Models\ChatGroup;
use App\Models\Message;
use App\Models\Tag;
use App\Models\Rule;
use App\Models\CompanyUser;
use App\Models\Notification;

function get_company_users($company_id){
    
    return CompanyUser::where('company_id', $company_id)->with('user')->get();
    
}

function getCompanyTags($companyId) {
    $tags = Tag::where('company_id', $companyId)->get();
    return $tags;
}


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,$user_assigned = 0,$status = 'waiting',$force = false) {
        
        $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)
                      ->orWhere('subject2', 'Re: ' . $cleanSubject)
                      ->orWhere('subject2', $cleanSubject); // Consider both with and without 'Re:'
            })
            ->first();

        
        
        if(!$check || $force){
        
            $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 = $status;
            $ticket->parent_id = 0;
            $ticket->user_assigned = $user_assigned;
            $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;
    }
}


/**
 * Create a new chat group.
 *
 * @param int $companyId The ID of the company associated with the chat.
 * @param int $userId The ID of the user creating the chat group.
 * @param string $customerId Identifier for the customer involved in the chat.
 * @param string $name Name or title of the chat group.
 * @param string $email Email address associated with the chat group.
 * @param string $subject Subject or initial topic of the chat group.
 * @param string $status Current status of the chat group (e.g., 'active', 'closed').
 * @return ChatGroup The newly created chat group object.
 */
 function createChatGroup($companyId, $userId, $customerId, $name, $email, $subject, $status)
{
    return ChatGroup::create([
        'company_id' => $companyId,
        'user_id' => $userId,
        'customer_id' => $customerId,
        'name' => $name,
        'email' => $email,
        'subject' => $subject,
        'status' => $status
    ]);
}


/**
 * Store a new message in a specified chat group.
 *
 * @param int $chatId The ID of the chat group.
 * @param string $from Sender identifier.
 * @param string $to Receiver identifier.
 * @param string $message Content of the message.
 * @param string $type Type of the message.
 * @return Message The newly created message object.
 */
 function storeMessage($chatId, $from, $to, $message, $type)
{
    return Message::create([
        'chat_id' => $chatId,
        'from' => $from,
        'to' => $to,
        'message' => $message,
        'type' => $type
    ]);
}


/**
 * Retrieve all messages from a specified chat group.
 *
 * @param int $chatId The ID of the chat group.
 * @return \Illuminate\Database\Eloquent\Collection A collection of messages.
 */
 function getMessagesByChatId($chatId)
{
    return Message::where('chat_id', $chatId)->orderBy('created_at', 'asc')->get();
}


function setTicketMeta(int $ticketId, string $key, $value, string $type = 'string')
{
    $ticket_metas = [];
    return TicketMeta::updateOrCreate(
        ['ticket_id' => $ticketId, 'key' => $key],
        ['value' => json_encode($value), 'type' => $type]
    );
    
    // foreach($value as $tag)
    // {
    //     $ticket_meta = TicketMeta::updateOrCreate([
    //         'ticket_id' => $ticketId,
    //         'key' => $key
    //     ],[
    //         'value' => $tag,
    //         'type' => $type
    //     ]);
        
    //     $ticket_metas[] = $ticket_meta;
    // }
    
    // return $ticket_metas;
}

/**
 * Get a meta value for a ticket.
 *
 * @param int $ticketId
 * @param string $key
 * @return string|null
 */
function getTicketMeta(int $ticketId, string $key)
{
    $meta = TicketMeta::where('ticket_id', $ticketId)->where('key', $key)->first();
    return $meta ? json_decode($meta->value) : null;
}

function getCompanyMeta(int $companyId, string $key)
{
    $meta = CompanyMeta::where('company_id', $companyId)->where('key', $key)->first();
    return $meta ? $meta->value : null;
}

function getChatSetting($key, $company_id = null)
{
    $companyId = $company_id??getSelectedCompany();
    $get_chat_setting = CompanyMeta::where('company_id', $companyId)->where('key', $key)->where('type', 'Chat Setting')->first();
    return $get_chat_setting;
}

function getChatSettings($key, $company_id = null)
{
    $companyId = $company_id??getSelectedCompany();
    $get_chat_setting = CompanyMeta::where('company_id', $companyId)->where('key', $key)->where('type', 'Chat Setting')->get();
    return $get_chat_setting;
}

function getCompanyRules()
{
    $companyId = getSelectedCompany();
    $rules = Rule::where('company_id', $companyId)->get();
    return $rules;
}


function extractEmail($fromField) {
    // Regular expression to extract email address within angle brackets or standalone
    if (preg_match('/<?([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>?/', $fromField, $matches)) {
        return $matches[1];  // Return the email address
    }
    return null;  // Return null if no email is found
}

function send_notification($user_id,$text,$type,$status='default')
{
    $notify = new Notification;
    $notify->user_id = $user_id;
    $notify->text = $text;
    $notify->status = $status;
    $notify->type = $type;
    $notify->save();
    
    return $notify;
}




