<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Chat;
use Carbon\Carbon;
use Kreait\Firebase\Contract\Database;
use App\Models\User;
use App\Models\NotificationSetting;
use App\Models\UserConnection;

class ProcessChatDecisions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    
    protected $signature = 'chat:process-decisions';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send decision reminders and auto-disconnect expired chats';
    public $database;
    public function __construct(Database $database)
    {
        parent::__construct(); 
        $this->database = $database;
        $this->lang = \App::getLocale();
    }
    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Processing chat decisions...');

        // Send decision reminders
        $this->sendDecisionReminders();

        // Auto-disconnect expired chats
        $this->autoDisconnectExpiredChats();

        $this->info('Chat decisions processing completed.');
    }

    /**
     * Send reminders for pending decisions
     */
    private function sendDecisionReminders()
    {
        $sixDaysAgo = Carbon::now()->subDays(6);

        $chats = Chat::where('status', 'need_more_time')
            ->where('decision_deadline', '>', Carbon::now())
            ->where(function($query) use ($sixDaysAgo) {
                $query->whereNull('last_reminder_sent_at')
                      ->orWhere('last_reminder_sent_at', '<', $sixDaysAgo);
            })
            ->get();

        $remindersCount = 0;

        foreach ($chats as $chat) {
            $daysRemaining = Carbon::now()->diffInDays($chat->decision_deadline, false);

            if ($daysRemaining <= 1) {
                if($chat->user_1_decision == 'need_more_time' || $chat->user_2_decision == 'need_more_time'){
                    if($chat->user_1_decision == 'need_more_time'){
                        $user = User::find($chat->user_id_1);
                        if($user){
                            send_notification_to_user(
                                $this->database,
                                $user,
                                ['user_id_1' => (string)$chat->user_id_1,'user_id_2'=>(string)$chat->user_id_2,'chat_id' => (string)$chat->id],
                                NotificationSetting::ALERT,
                                'decision_reminder_push',
                                time(),
                                "Have you made a decision for this proposal?",
                                "Please review the profile and make your decision before the deadline.",
                                $user->profile_image_url
                            );
                        }
                    } 
                    if($chat->user_2_decision == 'need_more_time'){
                        $user = User::find($chat->user_id_2);
                        if($user){
                            send_notification_to_user(
                                $this->database,
                                $user,
                                ['user_id_1' => (string)$chat->user_id_1,'user_id_2'=>(string)$chat->user_id_2,'chat_id' => (string)$chat->id],
                                NotificationSetting::ALERT,
                                'decision_reminder_push',
                                time(),
                                "Have you made a decision for this proposal?",
                                "Please review the profile and make your decision before the deadline.",
                                $user->profile_image_url
                            );
                        }
                    }   
                }
                if($chat->user_1_decision == '' || $chat->user_2_decision == ''){
                    if($chat->user_1_decision == ''){
                        $user = User::find($chat->user_id_1);
                        if($user){
                            send_notification_to_user(
                                $this->database,
                                $user,
                                ['user_id_1' => (string)$chat->user_id_1,'user_id_2'=>(string)$chat->user_id_2,'chat_id' => (string)$chat->id],
                                NotificationSetting::ALERT,
                                'decision_reminder_push',
                                time(),
                                "Have you made a decision for this proposal?",
                                "Please review the profile and make your decision before the deadline.",
                                $user->profile_image_url
                            );
                        }
                    } 
                    if($chat->user_2_decision == ''){
                        $user = User::find($chat->user_id_2);
                        if($user){
                            send_notification_to_user(
                                $this->database,
                                $user,
                                ['user_id_1' => (string)$chat->user_id_1,'user_id_2'=>(string)$chat->user_id_2,'chat_id' => (string)$chat->id],
                                NotificationSetting::ALERT,
                                'decision_reminder_push',
                                time(),
                                "Have you made a decision for this proposal?",
                                "Please review the profile and make your decision before the deadline.",
                                $user->profile_image_url
                            );
                        }
                    }   
                }

                $chat->last_reminder_sent_at = Carbon::now();
                $chat->save();

                $remindersCount++;
            }
        }

        $this->info("Sent {$remindersCount} reminders");
    }

    /**
     * Auto-disconnect expired chats
     */
    private function autoDisconnectExpiredChats()
    {
        $expiredChats = Chat::where('status', 'need_more_time')
            ->where('decision_deadline', '<', Carbon::now())
            ->get();

        $disconnectedCount = 0;

        foreach ($expiredChats as $chat) {
            $chat->status = 'disconnected';
            $chat->save();
            
            DB::table('user_blocks')->updateOrInsert(
                ['user_id' => $chat->user_id_2, 'blocked_user_id' => $chat->user_id_1],
                ['reason' => "Chat Decission not to continue", 'created_at' => now(), 'updated_at' => now()]
            );
            DB::table('user_blocks')->updateOrInsert(
                ['user_id' => $chat->user_id_1, 'blocked_user_id' => $chat->user_id_2],
                ['reason' => "Chat Decission not to continue", 'created_at' => now(), 'updated_at' => now()]
            );

            // Remove both connection entries from user_connections table
            UserConnection::where(function($query) use ($chat) {
                $query->where('user_id', $chat->user_id_1)
                      ->where('connected_user_id', $chat->user_id_2);
            })->orWhere(function($query) use ($chat) {
                $query->where('user_id', $chat->user_id_2)
                      ->where('connected_user_id', $chat->user_id_1);
            })->delete();

            $user = User::find($chat->user_id_1);
            if($user){
                send_notification_to_user(
                    $this->database,
                    $user,
                    ['user_id_1' => (string)$chat->user_id_1,'user_id_2'=>(string)$chat->user_id_2,'chat_id' => (string)$chat->id],
                    NotificationSetting::ALERT,
                    'decision_expired_push',
                    time(),
                    "The decision period has expired.",
                    "Profile has been disconnected.",
                    $user->profile_image_url
                );
            }
            $user = User::find($chat->user_id_2);
            if($user){
                send_notification_to_user(
                    $this->database,
                    $user,
                    ['user_id_1' => (string)$chat->user_id_1,'user_id_2'=>(string)$chat->user_id_2,'chat_id' => (string)$chat->id],
                    NotificationSetting::ALERT,
                    'decision_expired_push',
                    time(),
                    "The decision period has expired.",
                    "Profile has been disconnected.",
                    $user->profile_image_url
                );
            }


            $disconnectedCount++;
        }

        $this->info("Disconnected {$disconnectedCount} expired chats");
    }


}