<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Timezone;
use App\Models\User;
use App\Models\Ticket;
use App\Models\Comment;
use App\Models\Response;
use App\Models\Language;
use App\Models\Tag;
use App\Models\Rule;
use App\Models\CompanyMeta;
use App\Models\CompanyUser;
use Carbon\Carbon;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;

class InboxController extends Controller

{
    public function get_canned_responses(){
         $companyId = getSelectedCompany();
        return  CompanyMeta::where('company_id', $companyId)->where('key', 'canned_responses')->get();
    }
    
    
    public function inboxSetting()
    {
        $companyId = getSelectedCompany();
        $timezones = Timezone::all();
        $languages = Language::where('title', 'English (US)')->get();
        $basic_setting = CompanyMeta::where('company_id', $companyId)->where('type', 'Basic Setting')->get();
        $canned_response = $this->get_canned_responses();
        $spam_handling = CompanyMeta::where('company_id', $companyId)->where('type', 'Spam Handling')->first();
        $email_signature = CompanyMeta::where('company_id', $companyId)->where('type', 'Email Signature')->first();
        $company_users = get_company_users($companyId);
        $tags = Tag::where('company_id', $companyId)->get();
        $rule = Rule::where('company_id', $companyId)->first();
        
        
        return view('inbox-setting', ['timezones' => $timezones, 'basic_setting' => $basic_setting, 'spam_handling' => $spam_handling,
        'email_signature' => $email_signature, 'canned_response' => $canned_response, 'languages' => $languages, 'company' => get_company('id',$companyId),
        'company_users' => $company_users, 'tags' => $tags, 'rule' => $rule]);
    }

    public function basicSetting(Request $request)
    {
        $this->validate($request, [
            'kundo_email' => ['required', 'email'],
            'company_email' => ['required', 'email'],
            'inbox_name' => ['required', 'string'],
            'sender_name' => ['required', 'string'],
            'language' => ['required'],
            'timezone' => ['required'],
        ]);

        $companyId = getSelectedCompany();

        //Update Company Meta
        $basic_data = [
            'kundo_email' => $request->kundo_email,
            'inbox_name' => $request->inbox_name,
            'sender_name' => $request->sender_name,
            'language' => $request->language,
            'timezone' => $request->timezone,
        ];

        foreach($basic_data as $key => $value) {
            CompanyMeta::updateOrCreate([
                'key' => $key,
                'company_id' => $companyId,
            ],[
                
                'key' => $key,
                'value' => $value,
                'type' => 'Basic Setting'
            ]);
        }

        return redirect()->back()->with('success', 'Setting Updated Successfully');
    }

    public function emailSignature(Request $request)
    {
        $this->validate($request, [
            'email_signature' => 'required'    
        ]);

        $companyId = getSelectedCompany();
        CompanyMeta::updateOrCreate([
            'key' => 'email_signature',
             'company_id' => $companyId,
        ],[
            'value' => $request->email_signature,
            'type' => 'Email Signature'
        ]);

        return redirect()->back()->with('success', 'Setting Updated Successfully');
    }

    public function responseTime(Request $request)
    {
        $companyId = getSelectedCompany();
        //Update Company Meta
        $response_data = [
            'monday_start_time' => $request->monday_start_time,
            'monday_end_time' => $request->monday_end_time,
            'tuesday_start_time' => $request->tuesday_start_time,
            'tuesday_end_time' => $request->tuesday_end_time,
            'wednesday_start_time' => $request->wednesday_start_time,
            'wednesday_end_time' => $request->wednesday_end_time,
            'thursday_start_time' => $request->thursday_start_time,
            'thursday_end_time' => $request->thursday_end_time,
            'friday_start_time' => $request->friday_start_time,
            'friday_end_time' => $request->friday_end_time,
            'saturday_start_time' => $request->saturday_start_time,
            'saturday_end_time' => $request->saturday_end_time,
            'sunday_start_time' => $request->sunday_start_time,
            'sunday_end_time' => $request->sunday_end_time,
            'monday_closed' => $request->monday_closed,
            'tuesday_closed' => $request->tuesday_closed,
            'wednesday_closed' => $request->wednesday_closed,
            'thursday_closed' => $request->thursday_closed,
            'friday_closed' => $request->friday_closed,
            'saturday_closed' => $request->saturday_closed,
            'sunday_closed' => $request->sunday_closed,
            'expected_response' => $request->expected_response,
        ];

        foreach($response_data as $key => $value) {
            if(!is_null($value)) {
                CompanyMeta::updateOrCreate([
                    'key' => $key,
                    'company_id' => $companyId,
                ],[
                   
                    'key' => $key,
                    'value' => $value,
                    'type' => 'Response Time'
                ]);
            }else {
                CompanyMeta::where('key', $key)->where('company_id', $companyId)->where('type', 'Response Time')->delete();
            }
        }

        return redirect()->back()->with('success', 'Setting Updated Successfully');
    }

    public function cannedResponse(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'text' => 'required'
        ]);
    
        $companyId = getSelectedCompany();
        
        // Collect data into an array
        $canned_data = 
            [
                'name' => $request->name,
                'text' => $request->text,
            ];
        
        // Retrieve existing canned responses
        // $existingMeta = CompanyMeta::where('company_id', $companyId)
        //     ->where('key', 'canned_responses')
        //     ->where('type', 'Canned Response')
        //     ->first();
        
        // // Decode existing JSON data if it exists
        // if ($existingMeta) {
        //     $existingData = json_decode($existingMeta->value, true);
        //     $canned_data = array_merge($existingData, $canned_data);
        // }
    
        // // Encode the data array as JSON
        $jsonData = json_encode($canned_data);
    
        // Update or create the CompanyMeta entry
        
        
        CompanyMeta::create([
            'company_id' => $companyId,
            'key' => 'canned_responses',
            'value' => $jsonData,
            'type' => 'Canned Response'
        ]);

        return redirect()->back()->with('success', 'Setting Updated Successfully');
    }
    
    public function deleteCannedResponse($index)
    {
         $companyId = getSelectedCompany();
    
         CompanyMeta::where('company_id', $companyId)
            ->where('key', 'canned_responses')
            ->where('id', $index)
            ->delete();
    
        // if ($cannedMeta) {
        //     $canned_data = json_decode($cannedMeta->value, true);

        //     if (isset($canned_data[$index])) {
        //         unset($canned_data[$index]);

        //         $canned_data = array_values($canned_data);
        //         $jsonData = json_encode($canned_data);

        //         $cannedMeta->value = $jsonData;
        //         $cannedMeta->save();
        //     }
        // }
    
        return redirect()->back()->with('success', 'Canned response deleted successfully.');

    }

    public function acknowledgementReceipt(Request $request)
    {
        $companyId = getSelectedCompany();
        //Update Company Meta
        $acknowledgement_data = [
            'automatic_reply_subject' => $request->automatic_reply_subject,
            'automatic_reply_text' => $request->automatic_reply_text,
            'exception_email_addresses' => $request->exception_email_addresses,
            'activate_ticket_number' => $request->activate_ticket_number,
            'confirmation_receipt' => $request->confirmation_receipt,
            'activate_delivery_confirmation' => $request->activate_delivery_confirmation,
        ];
        foreach($acknowledgement_data as $key => $value) {
            if(!is_null($value)) {
                CompanyMeta::updateOrCreate([
                    'key' => $key,
                    'company_id' => $companyId,
                ],[
                    
                    
                    'value' => $value,
                    'type' => 'Acknowledgement of Receipt'
                ]);
            }else {
                CompanyMeta::where('key', $key)->where('company_id', $companyId)->where('type', 'Acknowledgement of Receipt')->delete();
            }
        }

        return redirect()->back()->with('success', 'Setting Updated Successfully');
    }
    
    public function spamHandling(Request $request)
    {
        $this->validate($request, [
            'spam_email' => 'required|email'
        ]);
    
        $companyId = getSelectedCompany();
        
        // Collect data into an array
        $canned_data = [
            [
                'spam_email' => $request->spam_email,
                'marking_radio' => $request->marking_radio,
            ]
        ];
        
        // Retrieve existing canned responses
        $existingMeta = CompanyMeta::where('company_id', $companyId)
            ->where('key', 'spam_handling')
            ->where('type', 'Spam Handling')
            ->first();
        
        // Decode existing JSON data if it exists
        if ($existingMeta) {
            $existingData = json_decode($existingMeta->value, true);
            $canned_data = array_merge($existingData, $canned_data);
        }
    
        // Encode the data array as JSON
        $jsonData = json_encode($canned_data);
    
        // Update or create the CompanyMeta entry
        CompanyMeta::updateOrCreate([
            'company_id' => $companyId,
            'key' => 'spam_handling',
        ], [
            'company_id' => $companyId,
            'key' => 'spam_handling',
            'value' => $jsonData,
            'type' => 'Spam Handling'
        ]);

        return redirect()->back()->with('success', 'Setting Updated Successfully');
    }
    
    public function deleteSpamHandling($index)
    {
        $companyId = getSelectedCompany();
    
        // Retrieve the existing canned responses
        $spamMeta = CompanyMeta::where('company_id', $companyId)
            ->where('key', 'spam_handling')
            ->where('type', 'Spam Handling')
            ->first();
    
        if ($spamMeta) {
            $spam_data = json_decode($spamMeta->value, true);
    
            if (isset($spam_data[$index])) {
                unset($spam_data[$index]);
    
                $spam_data = array_values($spam_data);
                $jsonData = json_encode($spam_data);

                $spamMeta->value = $jsonData;
                $spamMeta->save();
            }
        }
    
        return redirect()->back()->with('success', 'Spam Handler deleted successfully.');
    }
    
    public function inbox()
    {
        $tickets = get_current_company_tickets([
            
                'type' => 'inbox',
                'orderby' => 'id',
                'order' => 'desc',
                'with' => 'lastResponse'
                
                ]);
                
                
        $messages = [];
        $canned_response = $this->get_canned_responses();
        
        return view('inbox', ['tickets' => $tickets, 'messages' => $messages, 'canned_response' => $canned_response]);
    }
    
    public function fetchChatMessages($ticketId)
    {
        $ticket = Ticket::find($ticketId);
        $messages = $ticket->responses;
        
        return view('partials.chat-messages', compact('messages'))->render();
    }
    
    public function fetchActionBox($ticketId)
    {
        $selectedCompany = getSelectedCompany();
        $ticket = Ticket::where('id', $ticketId)->with('comments')->first();
        $companyUsers = get_company_users($selectedCompany);//CompanyUser::where('company_id', $selectedCompany)->with('user')->get();
        
        return view('partials.action-box', compact('ticket','companyUsers'))->render();
    }
    
    public function storeResponse(Request $request)
    {
        $this->validate($request, [
            'message' => 'required',
            'ticket_id' => 'required',
        ]);
        
        // Handle both single and multiple ticket IDs
        $ticket_ids = explode(',', $request->ticket_id);
        
        $messageWithClasses = $request->message;
        
        foreach ($ticket_ids as $ticket_id) {
            $response = createResponse($ticket_id, $messageWithClasses, 1);
        
            $ticket = Ticket::find($ticket_id);
            
            if (!$ticket) continue;
        
            $companyId = Session::get('selected_company');
            $company = get_company('id', $companyId);
            
            // Send mail to mailgun
            $domain = $company->domain;
            $company_name = $company->getMeta('sender_name') ?? $company->name;
            $from = "$company_name <$company->email>";
            $to = $ticket->from_email;
            $subject = $ticket->subject;
            $html = $request->message;
        
            // Call the function to send the email
            sendEmailViaMailgun($domain, $from, $to, $subject, $html);
        }
        
        return response()->json([
            'message' => strip_tags($response->message),
            'created_at' => $response->created_at->format('h:i A')
        ]);

    }
    
    public function storeComment(Request $request)
    {
        $request->validate([
            'ticket_id' => 'required|exists:tickets,id',
            'comment' => 'required|string',
        ]);
    
        // Assuming authenticated user
        $user_id = auth()->id();
    
        $comment = new Comment();
        $comment->author = $user_id;
        $comment->ticket_id = $request->ticket_id;
        $comment->comment = $request->comment;
        $comment->save();
        
        return $comment;
    }
    
    public function deleteComment($commentId)
    {
        $comment = Comment::findOrFail($commentId);
        $comment->delete();
    
        return response()->json(['message' => 'Comment Deleted Successfully']);
    }
    
    public function updateRule(Request $request)
    {
        $companyId = getSelectedCompany();
        
        //Update Rule
        Rule::updateOrCreate([
            'company_id' => $companyId,
        ],[
            'company_id' => $companyId,
            'from' => $request->from,
            'to' => $request->to,
            'subject_contains' => $request->subject_contains,
            'text_contains' => $request->text_contains,
            'subject1_contains' => $request->subject1_contains,
            'tag_id' => $request->tag_id,
            'name' => $request->name,
            'assign_to' => $request->assign_to,
            'status' => isset($request->status) ? $request->status : 'set as done',
            'priority' => isset($request->priority) ? $request->priority : 'Set highest priority',
            'message_to_assigned_editor' => $request->message_to_assigned_editor,
            'all_emails_automatically_mark_as_spam' => $request->all_emails_automatically_mark_as_spam,
        ]);
        
        return redirect()->back()->with('success', 'Setting Updated successfully.');
    }
}
