<?php 
namespace App\Traits;

use App\Models\Chat;
use App\Models\Company;
use App\Models\Message;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

trait ChatTrait{

    public function getChatList($search=null){
        try{
            $id = Auth::user()->company->id;
            $chats = DB::table('chats')
            ->leftJoin('messages', function ($join) {
                $join->on('chats.id', '=', 'messages.chat_id')
                    ->whereRaw('messages.id = (select max(id) from messages where chat_id = chats.id)');
            })
            ->leftJoin('companies as sender', 'sender.id', '=', 'chats.user_one')
            ->leftJoin('companies as receiver', 'receiver.id', '=', 'chats.user_two')
            // ->leftJoin('companies as receiver_company', 'receiver_company.user_id', '=', 'receiver.id')
            // ->leftJoin('companies as sender_company', 'sender_company.user_id', '=', 'sender.id')
            ->select('chats.*', 'messages.message as last_message', 'messages.file_path', 'messages.file_ext',
                'messages.sender_model', 'messages.receiver_model', 'messages.sender_id', 'messages.receiver_id', 
                'messages.chat_id', 'messages.type', 'messages.is_seen', 'messages.created_at', 
                'sender.name as sender_name', 'sender.logo as sender_image', 
                'receiver.name as receiver_name', 'receiver.logo as receiver_image',
            )
            ->where('chats.deleted_at', null)
            ->where('messages.chat_id', '!=', null)
            ->where(function ($query) use($id) {
                $query->where('user_one', $id)
                    ->orWhere('user_two', $id);
            });
            if ($search != null) {
                $chats->where(function ($query) use ($search) {
                    $query->where('sender.name', 'LIKE', '%' . $search . '%')
                            ->orWhere('receiver.name', 'LIKE', '%' . $search . '%');
                });
            }

            $chats = $chats->orderByDESC('messages.id')->get();
            $chatUsers = [];
            foreach ($chats as $k => $chat) {
                $unReadCount = 0;
                if($chat->id){
                    $unReadCount = Message::where('chat_id', $chat->id)->where('is_seen', 0)->count();
                }
                $isSender = $chat->sender_id == Auth::user()->company->id;
                $company = Company::with('user')->find($isSender ? $chat->receiver_id : $chat->sender_id);
                if($company){
                    $chatUsers[] = [
                        'id'           => $chat->id,
                        "unread_count" => $unReadCount,
                        "chat_id"      => $chat->chat_id,
                        'sender_id'    => $chat->sender_id,
                        'receiver_id'  => $chat->receiver_id,
                        'type'         => $chat->type,
                        'message'      => $chat->last_message,
                        'file_path'    => $chat->file_path,
                        'file_ext'     => $chat->file_ext,
                        'is_seen'      => $chat->is_seen,
                        'created_at'   => $chat->created_at,
                        'company_id'   => $company->id,
                        'company_name' => $company->name,
                        'is_active' => $company->user->is_active ?? 0,
                        'company_logo' => $company->logo ?? asset('images/placeholder.png'),
                    ];
                }
                
                   
            }
            return $chatUsers;

        }catch(Exception $ex){
            Log::error("getChats Error", array('error' => $ex->getMessage(), 'Line#' => $ex->getLine()));
            return array();
        }
    }

    public function getMessagesList($toUserId){
        try{
            $userId = Auth::user()->company->id;
            
            $chat = Chat::where(function ($q) use($userId, $toUserId) {
                $q->where(['user_one' => $userId,'user_two' => $toUserId]);
            })->orWhere(function($q) use($userId, $toUserId){
                $q->where(['user_one' => $toUserId, 'user_two' => $userId]);
            })->first();
            
            if($chat == null) {

                $chat = Chat::create([
                    "user_one"       => $userId,
                    'user_two'       => $toUserId,
                ]);  
            } 

            $messages = Message::where('chat_id', $chat->id)->where('receiver_id',$userId)->update(['is_seen' => 1]);
            $messages = Message::where('chat_id', $chat->id)->orderBy('id','asc')->get();

            return array(
                'chat_id' => $chat->id,
                'messages'=> $messages
            );

        }catch(Exception $ex){
            Log::error("getChatMessages Error", array('error' => $ex->getMessage(), 'Line#' => $ex->getLine()));
            return array();
        }
    }

    public function getAvailableUsersList(){
        $users = User::with('company')->where('role_id', '!=', 1)
            ->where('status', 1)
            ->where('has_company', 1)
            ->get();
        $data = array();

        if(count($users) > 0) {
            foreach ($users as $user) {
                $data[] = [
                    "id"            => $user->id,
                    "company_id"    => $user->company->id ?? null,
                    "company_name"  => $user->company->name ?? null,
                    "company_logo"  => $user->company->logo ?? asset('images/placeholder.png'),
                    "name"          => $user->name,
                    "image"         => $user->profile_image
                ];
            }
        } 

        return $data;
    }

    public function storeFileUpload($toUserId, $chatId=0, $filePath=[]){
        try{

            $userId = Auth::user()->company->id;
            $toUserId = $toUserId;

            if($chatId == 0){
                $chat = Chat::create([
                    "user_one"  => $userId,
                    'user_two'  => $toUserId,
                ]);

                $chatId = $chat->id;
            }

            $message = Message::create([
                'chat_id'       => (int)$chatId,
                'sender_id'     => (int)$userId,
                'receiver_id'   => (int)$toUserId,
                'sender_model'  => 'SENDER',
                'receiver_model'=> 'RECEIVER',
                'file_path'     => $filePath['path'] ?? '',
                'file_ext'      => $filePath['ext'] ?? '',
                'type'          => 'MEDIA',
            ]);

            return $message;

        }catch(Exception $ex){
            Log::error("chatFileUpload Error", array('error' => $ex->getMessage(), 'Line#' => $ex->getLine()));
            return array();
        }
    }

    public function deleteChatItem($chatId){
        Message::where('chat_id', $chatId)->delete();
        Chat::where('id', $chatId)->delete();
    }
}