<?php

namespace App\Http\Controllers\Chat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Company;
use App\Models\ChatGroup;
use App\Models\Message;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class ChatController extends Controller
{
    
    public function chatDemo(Request $request){
        return view('chat.demo');
    }
    
    public function CloseChat(Request $request){
        $chat_id = $request->chat_id;
        
        $chat = ChatGroup::find($chat_id);
        
        if($chat){
            $chat->status = 'closed';
            $chat->save();
            return true;
        }else{
            return false;
        }
    }
    
    public function getChat(Request $request){
        $chat_id = $request->chat_id;
        
        return ChatGroup::find($chat_id);
    }
    
    
     public function getMessages(Request $request){
        $chat_id = $request->chat_id;
        
        return Message::where('chat_id',$chat_id)->get();
    }
    
    
    /**
     * Start a new chat by creating a chat group.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function startChat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'company_id' => 'required|integer|exists:companies,id',
            //'user_id' => 'required|integer|exists:users,id',
            'customer_id' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'subject' => 'required|string|max:1000',
            //'status' => 'required|string|max:255'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }
        
        $company_id = $request->company_id;
        
        $user = $this->select_user($company_id);
        
        if($user){
           
        $data = [
            'company_id' => $company_id,
            'user_id' => $user->user_id,
            'customer_id' => $request->customer_id,
            'name' => $request->name,
            'email' => $request->email,
            'subject' => $request->subject,
            'status' => 'open',
            
            ];

        $chatGroup = ChatGroup::create($data);

        return response()->json(['chat' => $chatGroup], 200);
        
        }else{
            return response()->json(['message' => 'user not found'], 400);
        }
    }
    
    
    
    public function sendMessage(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'chat_id' => 'required|integer|exists:chat_group,id',
            'from' => 'required|string|max:255',
            //'to' => 'required|string|max:255',
            //'message' => 'required|string',
            'type' => 'required|string|max:255'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }
        $fileUrl = '';
        
         if ($request->hasFile('file')) {
            $file = $request->file('file');
            $filePath = $file->store('chat', 'public'); // Store in the 'public/uploads' directory
            $fileUrl = url(Storage::url($filePath)); // Generate the file URL
        }
        
         $data = [
            'chat_id' => $request->chat_id,
           
            'from' => $request->from,
            'to' => $request->from == 'user'?'company':'user',
            'message' => $request->hasFile('file')? $fileUrl: $request->message,
            'type' => $request->type,
          
            
            ];
      

        $message = Message::create($data);

        return response()->json(['message' => 'Message sent successfully', 'data' => $message], 200);
    }
    
    public function select_user($company_id){
        $companyUsers = get_company_users($company_id);
        
        $selected = false;
        
        foreach($companyUsers as $user){
            $access = json_decode($user->access);
            
            if(in_array('chat',$access)){
                $selected = $user;
                break;
            }
        }
        
        return $selected;
        
    }
    
      public function getChatGroupsByCompany(Request $request)
    {
        $companyId = getSelectedCompany();
    
        $chatGroups = ChatGroup::where('company_id', $companyId)
                        ->where(function($query) {
                            $query->where('status', '!=', 'ticket_created')
                                  ->where('status', '!=', 'closed');
                        })
                        ->get();

        return response()->json($chatGroups);
    }
    
    public function checkChat(Request $request){
        $company_id = $request->company_id;
        $domain = $request->domain;
        
        $company = get_company('id',$company_id);
        $ip = $_SERVER['REMOTE_ADDR'];
        
      //  return response()->json(['status' => 'error', 'message' => $ip]);
        
        if($company){
            // Str::contains('This is my name', 'my')
            if( $company->domain == $domain ){
                
                $start_message = getChatSetting('start_message',$company_id)?getChatSetting('start_message',$company_id)->value:"What can we help you with?"; //welcome message 
                $message_when_chat_is_closed = getChatSetting('message_when_chat_is_closed',$company_id)?getChatSetting('message_when_chat_is_closed',$company_id)->value:"No user is availble right now! Try later.";
                $wellcome_text = getChatSetting('wellcome_text',$company_id)?getChatSetting('wellcome_text',$company_id)->value:"Hi, welcome how i can help you today?";
                
                //Get Style
                $styles = [
                    'text_theme_color' => getChatSetting('text_theme_color', $company_id) ? getChatSetting('text_theme_color', $company_id)->value : null,
                    'background_theme_color' => getChatSetting('background_theme_color', $company_id) ? getChatSetting('background_theme_color', $company_id)->value : null,
                    'text_color_for_sent_message' => getChatSetting('text_color_for_sent_message', $company_id) ? getChatSetting('text_color_for_sent_message', $company_id)->value : null,
                    'background_color_of_sent_message' => getChatSetting('background_color_of_sent_message', $company_id) ? getChatSetting('background_color_of_sent_message', $company_id)->value : null,
                    'background_color_of_received_message' => getChatSetting('background_color_of_received_message', $company_id) ? getChatSetting('background_color_of_received_message', $company_id)->value : null,
                    'text_color_of_received_message' => getChatSetting('text_color_of_received_message', $company_id) ? getChatSetting('text_color_of_received_message', $company_id)->value : null,
                    'text_color_of_notification' => getChatSetting('text_color_of_notification', $company_id) ? getChatSetting('text_color_of_notification', $company_id)->value : null,
                    'text_color_of_error_message' => getChatSetting('text_color_of_error_message', $company_id) ? getChatSetting('text_color_of_error_message', $company_id)->value : null,
                    'background_color_of_error_message' => getChatSetting('background_color_of_error_message', $company_id) ? getChatSetting('background_color_of_error_message', $company_id)->value : null,
                    'link_color' => getChatSetting('link_color', $company_id) ? getChatSetting('link_color', $company_id)->value : null,
                ];
                
                //Get Display
                $settings = getChatSettings('Display Chat', $company_id);
                $display_chats = $settings ? $settings->pluck('value')->map(function($value) {
                    return json_decode($value);
                }) : null;
                $hide_chats = getChatSetting('Hide Chat', $company_id) ? getChatSetting('Hide Chat', $company_id)->value : null;
                $displays = [
                    'display_chats' => $display_chats,
                    'hide_chat' => $hide_chats,
                ];
                
                //Get Canned Responses
                $canned_responses = getChatSettings('Chat Canned Responses', $company_id);
                $canned_responses = $canned_responses ? $canned_responses->pluck('value')->map(function($value) {
                    return json_decode($value);
                }) : null;
                
                //Terms And Conditions
                $link_text = getChatSetting('link_text', $company_id) ? getChatSetting('link_text', $company_id)->value : null;
                
                
                $user = $this->select_user($company_id);
        
                if($user){
                     return response()->json(['status' => 'success','data' => ['welcome' => $wellcome_text, 'start_message' => $start_message, 'user' => $user->user->name, 'styles' => $styles,
                     'displays' => $displays, 'canned_responses' => $canned_responses, 'link_text' => $link_text] ]);
                }else{
                     return response()->json(['status' => 'error', 'message' => $message_when_chat_is_closed]);
                }
                
                
            }else{
                 return response()->json(['status' => 'error', 'message' => "You are not authorized!"]);
            }
        }
        
         return response()->json(['status' => 'error', 'message' => "You are not authorized!"]);
        
    }
}
