<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Timezone;
use App\Models\User;
use App\Models\Ticket;
use App\Models\Language;
use App\Models\CompanyMeta;
use Illuminate\Support\Facades\Auth;

class InboxController extends Controller
{
    public function inboxSetting()
    {
        $companyId = Auth::user()->company->id;
        $timezones = Timezone::all();
        $languages = Language::all();
        $basic_setting = CompanyMeta::where('company_id', $companyId)->where('type', 'Basic Setting')->get();
        $canned_response = CompanyMeta::where('company_id', $companyId)->where('type', 'Canned Response')->first();
        $spam_handling = CompanyMeta::where('company_id', $companyId)->where('type', 'Spam Handling')->first();
        $email_signature = CompanyMeta::where('company_id', $companyId)->where('type', 'Email Signature')->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]);
    }

    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 = Auth::user()->company->id;

        //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,
                'value' => $value
            ],[
                '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 = Auth::user()->company->id;
        CompanyMeta::updateOrCreate([
            'key' => 'email_signature',
            'value' => $request->email_signature
        ],[
            'company_id' => $companyId,
            'key' => 'email_signature',
            'value' => $request->email_signature,
            'type' => 'Email Signature'
        ]);

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

    public function responseTime(Request $request)
    {
        $companyId = Auth::user()->company->id;
        //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,
                    'value' => $value
                ],[
                    '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 = Auth::user()->company->id;
        
        // 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::updateOrCreate([
            'company_id' => $companyId,
            'key' => 'canned_responses',
        ], [
            'company_id' => $companyId,
            'key' => 'canned_responses',
            'value' => $jsonData,
            'type' => 'Canned Response'
        ]);

        return redirect()->back()->with('success', 'Setting Updated Successfully');
    }
    
    public function deleteCannedResponse($index)
    {
         $companyId = Auth::user()->company->id;
    
        // Retrieve the existing canned responses
        $cannedMeta = CompanyMeta::where('company_id', $companyId)
            ->where('key', 'canned_responses')
            ->where('type', 'Canned Response')
            ->first();
    
        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 = Auth::user()->company->id;
        //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,
                    'value' => $value
                ],[
                    'company_id' => $companyId,
                    'key' => $key,
                    '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 = Auth::user()->company->id;
        
        // 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 = Auth::user()->company->id;
    
        // 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 = Ticket::orderBy('id', 'desc')->with('lastResponse')->get();
        $messages = [];
        return view('inbox', ['tickets' => $tickets, 'messages' => $messages]);
    }
    
    public function fetchChatMessages($ticketId)
    {
        $ticket = Ticket::find($ticketId);
        $messages = $ticket->responses;
        
        return view('partials.chat-messages', compact('messages'))->render();
    }
    
    public function fetchActionBox($ticketId)
    {
        $ticket = Ticket::where('id', $ticketId)->with('comments')->first();
        
        return view('partials.action-box', compact('ticket'))->render();
    }
}
