<?php

namespace App\Http\Controllers\api\v1;

use App\Http\Controllers\Controller;
use App\Models\Chat;
use App\Models\ChatMessage;
use App\Models\Question;
use App\Models\Answer;
use App\Models\ChatCategory;
use Kreait\Firebase\Contract\Database;
use App\Models\User;
use App\Models\NotificationSetting;
use App\Models\UserConnection;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ChatController extends Controller
{
    public $database;
    public function __construct(Database $database, Request $request)
    {
        $this->database = $database;
        if (isset($request->lang)) {
            \App::setLocale($request->lang);
        }
        $this->lang = \App::getLocale();
    }
    /**
     * Check if two users are connected (handles double-sided entries)
     */
    private function areUsersConnected($userId1, $userId2)
    {
        return UserConnection::where(function ($query) use ($userId1, $userId2) {
            $query->where('user_id', $userId1)
                ->where('connected_user_id', $userId2);
        })->orWhere(function ($query) use ($userId1, $userId2) {
            $query->where('user_id', $userId2)
                ->where('connected_user_id', $userId1);
        })
            ->exists();
    }

    /**
     * Initialize a new chat between two users
     */
    public function initializeChat(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'user_id_1' => 'required|exists:users,id',
                'user_id_2' => 'required|exists:users,id',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                // Verify users are connected and get connection_id (handles double-sided entries)
                $connection = UserConnection::where(function ($query) use ($request) {
                    $query->where('user_id', $request->user_id_1)
                        ->where('connected_user_id', $request->user_id_2);
                })->orWhere(function ($query) use ($request) {
                    $query->where('user_id', $request->user_id_2)
                        ->where('connected_user_id', $request->user_id_1);
                })->first();

                if (!$connection) {
                    $message = 'Users are not connected. Connection must exist before starting a chat.';
                } else {
                    // Check if chat already exists
                    $existingChat = Chat::where(function ($query) use ($request) {
                        $query->where('user_id_1', $request->user_id_1)
                            ->where('user_id_2', $request->user_id_2);
                    })->orWhere(function ($query) use ($request) {
                        $query->where('user_id_1', $request->user_id_2)
                            ->where('user_id_2', $request->user_id_1);
                    })->whereIn('status', ['active', 'pending_decision', 'need_more_time', 'completed'])->first();

                    if ($existingChat) {
                        $status = "1";
                        $message = 'Chat already exists';
                        $o_data = convert_all_elements_to_string([
                            'chat_id' => $existingChat->id,
                            'status' => $existingChat->status,
                            'questions_exchanged' => $existingChat->questions_exchanged,
                            'connection_id' => $existingChat->connection_request_id
                        ], true);
                    } else {
                        // Create new chat with automatically fetched connection_id
                        $chat = Chat::create([
                            'user_id_1' => $request->user_id_1,
                            'user_id_2' => $request->user_id_2,
                            'connection_request_id' => $connection->id,
                            'status' => 'active'
                        ]);

                        $status = "1";
                        $message = 'Chat initialized successfully';
                        $o_data = convert_all_elements_to_string([
                            'chat_id' => $chat->id,
                            'status' => $chat->status,
                            'questions_exchanged' => $chat->questions_exchanged,
                            'connection_id' => $connection->id
                        ], true);
                    }
                }
            }
        } catch (Exception $e) {
            $message = 'Failed to initialize chat';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Get available question categories for chat
     */
    public function getQuestionCategories(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $categories = ChatCategory::where('status', 1)
                ->select('id', 'name', 'name_ar')
                ->withCount([
                    'questions' => function ($query) {
                        $query->where('status', 1);
                    }
                ])
                ->whereHas('questions', function ($q) {
                    $q->where('status', 1);
                })
                ->get();

            if ($categories->count() > 0) {
                $status = "1";
                $message = "Categories fetched successfully";
                $o_data['list'] = convert_all_elements_to_string($categories->toArray(), true);
            } else {
                $message = "No categories available";
            }
        } catch (Exception $e) {
            $message = 'Failed to fetch categories';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Get questions by category (optimized for fast loading)
     */
    public function getQuestionsByCategory(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'chat_category_id' => 'required|exists:chat_categories,id',
                'chat_id' => 'required|exists:chats,id'
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                // Get questions not yet asked in this chat
                // $askedQuestionIds = ChatMessage::where('chat_id', $request->chat_id)
                //     ->pluck('question_id')
                //     ->toArray();

                $questions = Question::where('chat_category_id', $request->chat_category_id)
                    ->where('status', 1)
                    //->whereNotIn('id', $askedQuestionIds)
                    ->select('id', 'name', 'name_ar', 'chat_category_id')
                    ->with([
                        'answers' => function ($query) {
                            $query->where('status', 1)
                                ->select('id', 'question_id', 'name', 'name_ar');
                        }
                    ])
                    ->get();

                if ($questions->count() > 0) {
                    $status = "1";
                    $message = "Questions fetched successfully";
                    $o_data['list'] = convert_all_elements_to_string($questions->toArray(), true);
                } else {
                    $message = "No questions available for this category";
                }
            }
        } catch (Exception $e) {
            $message = 'Failed to fetch questions';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Send a question in chat
     */
    public function sendQuestion(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'chat_id' => 'required|exists:chats,id',
                'question_id' => 'required|exists:questions,id',
                'sender_id' => 'required|exists:users,id'
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                DB::beginTransaction();

                $chat = Chat::findOrFail($request->chat_id);

                // Validate sender is part of the chat
                if ($chat->user_id_1 != $request->sender_id && $chat->user_id_2 != $request->sender_id) {
                    $message = 'You are not part of this chat';
                } else {
                    // Check if question already asked
                    // $alreadyAsked = ChatMessage::where('chat_id', $request->chat_id)
                    //     ->where('question_id', $request->question_id)
                    //     ->exists();

                    // if ($alreadyAsked) {
                    //     $message = 'This question has already been asked in this chat';
                    // } else {
                    $receiverId = $chat->getOtherUserId($request->sender_id);

                    // Create message
                    $chatMessage = ChatMessage::create([
                        'chat_id' => $request->chat_id,
                        'sender_id' => $request->sender_id,
                        'receiver_id' => $receiverId,
                        'question_id' => $request->question_id,
                        'message_type' => 'question'
                    ]);

                    DB::commit();

                    // Load relationships for response
                    $chatMessage->load([
                        'question.answers' => function ($query) {
                            $query->where('status', 1)->select('id', 'question_id', 'name', 'name_ar');
                        }
                    ]);

                    $status = "1";
                    $message = 'Question sent successfully';
                    $user = User::find($receiverId);
                    $sender = User::find($request->sender_id);
                    $connection = DB::table('user_connections')->where('user_id', $sender->id)
                        ->where('connected_user_id', $user->id)
                        ->first();

                    $hideImage = $connection ? (int) $connection->hide_image : 0;
                    $jsonData = [
                        'chat_id' => (string) $chat->id,
                        'sender_id' => (string) $request->sender_id,
                        'receiver_id' => (string) $receiverId,
                        'message_id' => (string) $chatMessage->id,
                        "imageBlur" => (string) $hideImage
                    ];
                    $title = "New Question Received";
                    $description = "You have received a new question
تم استلام سؤال جديد: لقد استلمت سؤالاً جديداً";
                    // $res = send_single_notification(
                    //     $user->user_device_token,
                    //     [
                    //         "title" => $title ,
                    //         "body" => $description,
                    //         "icon" => 'myicon',
                    //         "sound" => 'default',
                    //         "click_action" => "EcomNotification"
                    //     ],
                    //     $jsonData
                    // );
                    send_notification_to_user(
                        $this->database,
                        $user,
                        $jsonData,
                        NotificationSetting::REQUEST,
                        'chat_push',
                        time(),
                        $title,
                        $description,
                        $user->profile_image_url
                    );
                    $o_data = convert_all_elements_to_string($chatMessage->toArray(), true);
                    //}
                }
            }
        } catch (Exception $e) {
            DB::rollBack();
            $message = 'Failed to send question';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Send an answer to a question
     */
    public function sendAnswer(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'message_id' => 'required|exists:chat_messages,id',
                'answer_id' => 'required|exists:answers,id',
                'sender_id' => 'required|exists:users,id'
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                DB::beginTransaction();

                $questionMessage = ChatMessage::with('chat')->findOrFail($request->message_id);

                // Validate sender is the receiver of the question
                if ($questionMessage->receiver_id != $request->sender_id) {
                    $message = 'You are not authorized to answer this question';
                } else {
                    // Check if already answered
                    // $alreadyAnswered = ChatMessage::where('chat_id', $questionMessage->chat_id)
                    //     ->where('question_id', $questionMessage->question_id)
                    //     ->where('message_type', 'answer')
                    //     ->exists();

                    // if ($alreadyAnswered) {
                    //     $message = 'This question has already been answered';
                    // } else {
                    // Validate answer belongs to the question
                    $answer = Answer::where('id', $request->answer_id)
                        ->where('question_id', $questionMessage->question_id)
                        ->first();

                    if (!$answer) {
                        $message = 'Invalid answer for this question';
                    } else {
                        // Create answer message
                        $answerMessage = ChatMessage::create([
                            'chat_id' => $questionMessage->chat_id,
                            'sender_id' => $request->sender_id,
                            'receiver_id' => $questionMessage->sender_id,
                            'question_id' => $questionMessage->question_id,
                            'answer_id' => $request->answer_id,
                            'message_type' => 'answer'
                        ]);

                        // Increment questions exchanged
                        $chat = $questionMessage->chat;
                        $chat->questions_exchanged += 1;
                        $chat->save();

                        // Check if decision prompt should be shown
                        $showDecisionPrompt = $chat->shouldShowDecisionPrompt();

                        if (($chat->questions_exchanged % 5) == 0) {
                            $chat->status = 'pending_decision';
                            $chat->decision_deadline = Carbon::now()->addDays(7);
                            $chat->save();
                        }

                        DB::commit();

                        $answerMessage->load(['question', 'answer']);

                        $status = "1";
                        $message = 'Answer sent successfully';
                        $sender = User::find($request->sender_id);
                        $user = User::find($questionMessage->sender_id);
                        $connection = DB::table('user_connections')->where('user_id', $sender->id)
                            ->where('connected_user_id', $user->id)
                            ->first();

                        $hideImage = $connection ? (int) $connection->hide_image : 0;
                        $jsonData = [
                            'chat_id' => (string) $chat->id,
                            'sender_id' => (string) $request->sender_id,
                            'receiver_id' => (string) $questionMessage->sender_id,
                            'message_id' => (string) $answerMessage->id,
                            "imageBlur" => (string) $hideImage
                        ];
                        $title = "New Answer Received";
                        $description = "You have received a new answer to your question
تم استلام إجابة جديدة: لقد استلمت إجابة جديدة على سؤالك";
                        // $res = send_single_notification(
                        //     $user->user_device_token,
                        //     [
                        //         "title" => $title ,
                        //         "body" => $description,
                        //         "icon" => 'myicon',
                        //         "sound" => 'default',
                        //         "click_action" => "EcomNotification"
                        //     ],
                        //     $jsonData
                        // );
                        send_notification_to_user(
                            $this->database,
                            $user,
                            $jsonData,
                            NotificationSetting::REQUEST,
                            'chat_push',
                            time(),
                            $title,
                            $description,
                            $user->profile_image_url
                        );
                        $o_data = convert_all_elements_to_string([
                            'message' => $answerMessage->toArray(),
                            'questions_exchanged' => $chat->questions_exchanged,
                            'show_decision_prompt' => $showDecisionPrompt ? "1" : "0"
                        ], true);
                    }
                    //}
                }
            }
        } catch (Exception $e) {
            DB::rollBack();
            $message = 'Failed to send answer';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Get chat messages with pagination (optimized)
     */
    public function getChatMessages(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'chat_id' => 'required|exists:chats,id',
                'user_id' => 'required|exists:users,id',
                'page' => 'nullable|integer|min:1',
                'per_page' => 'nullable|integer|min:10|max:50'
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                $chat = Chat::findOrFail($request->chat_id);
                $userId = $request->user_id;
                // Validate user is part of the chat
                if ($chat->user_id_1 != $request->user_id && $chat->user_id_2 != $request->user_id) {
                    $message = 'You are not part of this chat';
                } else {
                    $perPage = $request->per_page ?? 20;

                    $messages = ChatMessage::where('chat_id', $request->chat_id)
                        ->with([
                            'question:id,name,name_ar',
                            'answer' => function ($q) {
                                $q->select('id', 'name', 'name_ar')->withDefault(['id' => "", 'name' => '', 'name_ar' => '']);
                            },
                            'sender' => function ($q) use ($request, $userId) {
                                $q->leftJoin('user_requests as ur_sent', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_sent.receiver_id')
                                        ->where('ur_sent.sender_id', '=', $userId);
                                })->leftJoin('user_requests as ur_received', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_received.sender_id')
                                        ->where('ur_received.receiver_id', '=', $userId);
                                })
                                    ->leftJoin('user_blocks as ub_me', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ub_me.blocked_user_id')
                                            ->where('ub_me.user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_blocks as ub_other', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ub_other.user_id')
                                            ->where('ub_other.blocked_user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_reports as ur_me', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ur_me.reported_user_id')
                                            ->where('ur_me.reporter_id', '=', $userId);
                                    })
                                    ->leftJoin('user_reports as ur_other', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ur_other.reporter_id')
                                            ->where('ur_other.reported_user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_connections as uc1', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'uc1.connected_user_id')
                                            ->where('uc1.user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_connections as uc2', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'uc2.user_id')
                                            ->where('uc2.connected_user_id', '=', $userId);
                                    })
                                    ->leftJoin('profile_picture_requests as ppr', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ppr.receiver_id')
                                            ->where('ppr.sender_id', '=', $userId);
                                    })
                                    ->whereNull('users.deleted_at')
                                    ->where('users.deleted', 0)

                                    // Exclude blocked or reported users entirely
                                    ->whereNull('ub_me.id')
                                    ->whereNull('ub_other.id')
                                    ->whereNull('ur_me.id')
                                    ->whereNull('ur_other.id');
                                $q->select('users.*');
                                $q->selectRaw('
                                    CASE WHEN uc1.id IS NOT NULL OR uc2.id IS NOT NULL THEN 1 ELSE 0 END as is_connected,
                            
                                    CASE 
                                        WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                             AND ur_sent.id IS NOT NULL 
                                        THEN 1 ELSE 0 
                                    END as is_sent,
                            
                                    CASE 
                                        WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                             AND ur_received.id IS NOT NULL 
                                        THEN 1 ELSE 0 
                                    END as is_received,
                            
                                    0 as is_blocked, -- always zero since blocked users excluded
                                    0 as am_i_blocked, -- same here
                            
                                    0 as is_reported, -- reported users excluded
                                    0 as am_i_reported,
                            
                                    CASE 
                                        WHEN (uc1.id IS NOT NULL OR uc2.id IS NOT NULL) 
                                        THEN COALESCE(uc1.hide_image, 0) ELSE 0 
                                    END as hide_image_by_current_user,
                            
                                    CASE 
                                        WHEN ppr.status = "accepted" 
                                        THEN "0" ELSE "1"
                                    END as hide_image_by_target_user
                                ');
                            },
                            'receiver' => function ($q) use ($request, $userId) {
                                $q->leftJoin('user_requests as ur_sent', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_sent.receiver_id')
                                        ->where('ur_sent.sender_id', '=', $userId);
                                })->leftJoin('user_requests as ur_received', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_received.sender_id')
                                        ->where('ur_received.receiver_id', '=', $userId);
                                })
                                    ->leftJoin('user_blocks as ub_me', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ub_me.blocked_user_id')
                                            ->where('ub_me.user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_blocks as ub_other', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ub_other.user_id')
                                            ->where('ub_other.blocked_user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_reports as ur_me', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ur_me.reported_user_id')
                                            ->where('ur_me.reporter_id', '=', $userId);
                                    })
                                    ->leftJoin('user_reports as ur_other', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ur_other.reporter_id')
                                            ->where('ur_other.reported_user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_connections as uc1', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'uc1.connected_user_id')
                                            ->where('uc1.user_id', '=', $userId);
                                    })
                                    ->leftJoin('user_connections as uc2', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'uc2.user_id')
                                            ->where('uc2.connected_user_id', '=', $userId);
                                    })
                                    ->leftJoin('profile_picture_requests as ppr', function ($join) use ($userId) {
                                        $join->on('users.id', '=', 'ppr.receiver_id')
                                            ->where('ppr.sender_id', '=', $userId);
                                    })
                                    ->whereNull('users.deleted_at')
                                    ->where('users.deleted', 0)

                                    // Exclude blocked or reported users entirely
                                    ->whereNull('ub_me.id')
                                    ->whereNull('ub_other.id')
                                    ->whereNull('ur_me.id')
                                    ->whereNull('ur_other.id');
                                $q->select('users.*');
                                $q->selectRaw('
                                    CASE WHEN uc1.id IS NOT NULL OR uc2.id IS NOT NULL THEN 1 ELSE 0 END as is_connected,
                            
                                    CASE 
                                        WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                             AND ur_sent.id IS NOT NULL 
                                        THEN 1 ELSE 0 
                                    END as is_sent,
                            
                                    CASE 
                                        WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                             AND ur_received.id IS NOT NULL 
                                        THEN 1 ELSE 0 
                                    END as is_received,
                            
                                    0 as is_blocked, -- always zero since blocked users excluded
                                    0 as am_i_blocked, -- same here
                            
                                    0 as is_reported, -- reported users excluded
                                    0 as am_i_reported,
                            
                                    CASE 
                                        WHEN (uc1.id IS NOT NULL OR uc2.id IS NOT NULL) 
                                        THEN COALESCE(uc1.hide_image, 0) ELSE 0 
                                    END as hide_image_by_current_user,
                            
                                    CASE 
                                        WHEN ppr.status = "accepted" 
                                        THEN "0" ELSE "1"
                                    END as hide_image_by_target_user
                                ');
                            }
                        ])
                        ->orderBy('created_at', 'desc')
                        ->paginate($perPage);

                    // Mark messages as read
                    ChatMessage::where('chat_id', $request->chat_id)
                        ->where('receiver_id', $request->user_id)
                        ->where('is_read', false)
                        ->update(['is_read' => true, 'read_at' => Carbon::now()]);

                    $status = "1";
                    $message = "Messages fetched successfully";
                    $o_data = convert_all_elements_to_string([
                        'chat' => [
                            'id' => $chat->id,
                            'status' => $chat->status,
                            'questions_exchanged' => $chat->questions_exchanged,
                            'show_decision_prompt' => $chat->shouldShowDecisionPrompt() ? "1" : "0"
                        ],
                        'list' => $messages->toArray()
                    ], true);
                }
            }
        } catch (Exception $e) {
            $message = 'Failed to fetch messages';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Submit decision after 5 questions
     */
    public function submitDecision(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'chat_id' => 'required|exists:chats,id',
                'user_id' => 'required|exists:users,id',
                'decision' => 'required|in:yes,no,need_more_time'
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                DB::beginTransaction();

                $chat = Chat::findOrFail($request->chat_id);

                // Validate user is part of the chat
                if ($chat->user_id_1 != $request->user_id && $chat->user_id_2 != $request->user_id) {
                    $message = 'You are not part of this chat';
                } else {
                    // Set user decision
                    if ($request->decision == 'yes') {
                        $chat->setUserDecision($request->user_id, 'yes');
                    } elseif ($request->decision == 'no') {
                        $chat->setUserDecision($request->user_id, 'no');
                    } else {
                        // need_more_time
                        $chat->setUserDecision($request->user_id, 'need_more_time');
                        $chat->status = 'need_more_time';
                        $chat->decision_deadline = Carbon::now()->addDays(7);
                        $chat->save();
                    }

                    // Check if both users have decided
                    if ($chat->bothUsersDecided()) {
                        if ($chat->bothUsersAgreed()) {
                            $chat->status = 'completed';
                            $chat->decision_deadline = null;
                            $message = trans('message.admin_will_contact');

                            $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_success_push',
                                    time(),
                                    "Congratulations!",
                                    "Admin will contact both parties to proceed with this relation.مبروك! سيتواصل معكم المشرف مع الطرفين لمتابعة إجراءات هذه العلاقة.",
                                    $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_success_push',
                                    time(),
                                    "Congratulations!",
                                    "Admin will contact both parties to proceed with this relation.	سيتواصل المسؤول مع الطرفين لاستكمال هذا الارتباط.",
                                    $user->profile_image_url
                                );
                            }
                            
                            // Create admin notification for match request
                            \App\Models\AdminMatchNotification::create([
                                'chat_id' => $chat->id,
                                'user_id_1' => $chat->user_id_1,
                                'user_id_2' => $chat->user_id_2
                            ]);
                        } elseif ($chat->anyUserDisagreed()) {
                            $chat->status = 'disconnected';
                            $chat->decision_deadline = null;
                            $message = trans('message.both_disconnected');

                            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()]
                            );

                            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=$user1 = User::find($chat->user_id_1);
                            $user2 = 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_disconnected_push',
                                    time(),
                                    "Not interested",
                                    $user2->nick_name." is not interested in continuing the connection
غير مهتم: لم يكن جميع الأطراف مهتمين بمواصلة الاتصال",
                                    $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_disconnected_push',
                                    time(),
                                    "Not interested",
                                    $user1->nick_name." is not interested in continuing the connection
غير مهتم: لم يكن جميع الأطراف مهتمين بمواصلة الاتصال",
                                    $user->profile_image_url
                                );
                            }
                        } else {
                            // Both need more time
                            $chat->status = 'need_more_time';
                            $chat->decision_deadline = Carbon::now()->addDays(7);
                            $message = 'You have 7 days to make a decision.';
                            
                            if($chat->getUserDecision($request->user_id) == 'yes' ){
                                $message = trans('message.admin_will_contact');
                            }
                        }
                        $chat->save();
                    } else {
                        // Waiting for other user's decision
                        if ($request->decision == 'need_more_time') {
                            $message = 'You have 7 days to make a decision.';
                        }else if ($request->decision == 'yes') {
                             $message = trans('message.admin_will_contact');
                        } else {
                            $message = trans('message.need_more_time');
                        }
                    }

                    DB::commit();

                    $status = "1";
                    $o_data = convert_all_elements_to_string([
                        'chat_status' => $chat->status,
                        'both_decided' => $chat->bothUsersDecided() ? "1" : "0",
                        'decision_deadline' => $chat->decision_deadline ? $chat->decision_deadline->toDateTimeString() : null
                    ], true);
                }
            }
        } catch (Exception $e) {
            DB::rollBack();
            $message = 'Failed to submit decision';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Get user's active chats
     */
    public function getUserChats(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'user_id' => 'required|exists:users,id'
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                $userId = $request->user_id;
                $chats = Chat::where(function ($query) use ($request) {
                    $query->where('user_id_1', $request->user_id)
                        ->orWhere('user_id_2', $request->user_id);
                })
                    ->whereIn('status', ['active', 'pending_decision', 'need_more_time'])
                    ->with([
                        'user1' => function ($q) use ($request, $userId) {
                            $q->leftJoin('user_requests as ur_sent', function ($join) use ($userId) {
                                $join->on('users.id', '=', 'ur_sent.receiver_id')
                                    ->where('ur_sent.sender_id', '=', $userId);
                            })->leftJoin('user_requests as ur_received', function ($join) use ($userId) {
                                $join->on('users.id', '=', 'ur_received.sender_id')
                                    ->where('ur_received.receiver_id', '=', $userId);
                            })
                                ->leftJoin('user_blocks as ub_me', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ub_me.blocked_user_id')
                                        ->where('ub_me.user_id', '=', $userId);
                                })
                                ->leftJoin('user_blocks as ub_other', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ub_other.user_id')
                                        ->where('ub_other.blocked_user_id', '=', $userId);
                                })
                                ->leftJoin('user_reports as ur_me', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_me.reported_user_id')
                                        ->where('ur_me.reporter_id', '=', $userId);
                                })
                                ->leftJoin('user_reports as ur_other', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_other.reporter_id')
                                        ->where('ur_other.reported_user_id', '=', $userId);
                                })
                                ->leftJoin('user_connections as uc1', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'uc1.connected_user_id')
                                        ->where('uc1.user_id', '=', $userId);
                                })
                                ->leftJoin('user_connections as uc2', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'uc2.user_id')
                                        ->where('uc2.connected_user_id', '=', $userId);
                                })
                                ->leftJoin('profile_picture_requests as ppr', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ppr.receiver_id')
                                        ->where('ppr.sender_id', '=', $userId);
                                })
                                ->whereNull('users.deleted_at')
                                ->where('users.deleted', 0)

                                // Exclude blocked or reported users entirely
                                ->whereNull('ub_me.id')
                                ->whereNull('ub_other.id')
                                ->whereNull('ur_me.id')
                                ->whereNull('ur_other.id');
                            $q->select('users.*');
                            $q->selectRaw('
                            CASE WHEN uc1.id IS NOT NULL OR uc2.id IS NOT NULL THEN 1 ELSE 0 END as is_connected,
                    
                            CASE 
                                WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                     AND ur_sent.id IS NOT NULL 
                                THEN 1 ELSE 0 
                            END as is_sent,
                    
                            CASE 
                                WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                     AND ur_received.id IS NOT NULL 
                                THEN 1 ELSE 0 
                            END as is_received,
                    
                            0 as is_blocked, -- always zero since blocked users excluded
                            0 as am_i_blocked, -- same here
                    
                            0 as is_reported, -- reported users excluded
                            0 as am_i_reported,
                    
                            CASE 
                                WHEN (uc1.id IS NOT NULL OR uc2.id IS NOT NULL) 
                                THEN COALESCE(uc1.hide_image, 0) ELSE 0 
                            END as hide_image_by_current_user,
                    
                            CASE 
                                WHEN ppr.status = "accepted" 
                                THEN "0" ELSE "1"
                            END as hide_image_by_target_user
                        ');
                        },
                        'user2' => function ($q) use ($request, $userId) {
                            $q->leftJoin('user_requests as ur_sent', function ($join) use ($userId) {
                                $join->on('users.id', '=', 'ur_sent.receiver_id')
                                    ->where('ur_sent.sender_id', '=', $userId);
                            })->leftJoin('user_requests as ur_received', function ($join) use ($userId) {
                                $join->on('users.id', '=', 'ur_received.sender_id')
                                    ->where('ur_received.receiver_id', '=', $userId);
                            })
                                ->leftJoin('user_blocks as ub_me', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ub_me.blocked_user_id')
                                        ->where('ub_me.user_id', '=', $userId);
                                })
                                ->leftJoin('user_blocks as ub_other', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ub_other.user_id')
                                        ->where('ub_other.blocked_user_id', '=', $userId);
                                })
                                ->leftJoin('user_reports as ur_me', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_me.reported_user_id')
                                        ->where('ur_me.reporter_id', '=', $userId);
                                })
                                ->leftJoin('user_reports as ur_other', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ur_other.reporter_id')
                                        ->where('ur_other.reported_user_id', '=', $userId);
                                })
                                ->leftJoin('user_connections as uc1', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'uc1.connected_user_id')
                                        ->where('uc1.user_id', '=', $userId);
                                })
                                ->leftJoin('user_connections as uc2', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'uc2.user_id')
                                        ->where('uc2.connected_user_id', '=', $userId);
                                })
                                ->leftJoin('profile_picture_requests as ppr', function ($join) use ($userId) {
                                    $join->on('users.id', '=', 'ppr.receiver_id')
                                        ->where('ppr.sender_id', '=', $userId);
                                })
                                ->whereNull('users.deleted_at')
                                ->where('users.deleted', 0)

                                // Exclude blocked or reported users entirely
                                ->whereNull('ub_me.id')
                                ->whereNull('ub_other.id')
                                ->whereNull('ur_me.id')
                                ->whereNull('ur_other.id');
                            $q->select('users.*');
                            $q->selectRaw('
                            CASE WHEN uc1.id IS NOT NULL OR uc2.id IS NOT NULL THEN 1 ELSE 0 END as is_connected,
                    
                            CASE 
                                WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                     AND ur_sent.id IS NOT NULL 
                                THEN 1 ELSE 0 
                            END as is_sent,
                    
                            CASE 
                                WHEN (ub_me.id IS NULL AND ub_other.id IS NULL AND ur_me.id IS NULL AND ur_other.id IS NULL) 
                                     AND ur_received.id IS NOT NULL 
                                THEN 1 ELSE 0 
                            END as is_received,
                    
                            0 as is_blocked, -- always zero since blocked users excluded
                            0 as am_i_blocked, -- same here
                    
                            0 as is_reported, -- reported users excluded
                            0 as am_i_reported,
                    
                            CASE 
                                WHEN (uc1.id IS NOT NULL OR uc2.id IS NOT NULL) 
                                THEN COALESCE(uc1.hide_image, 0) ELSE 0 
                            END as hide_image_by_current_user,
                    
                            CASE 
                                WHEN ppr.status = "accepted" 
                                THEN "0" ELSE "1"
                            END as hide_image_by_target_user
                        ');
                        },
                        'last_message'
                    ])
                    ->withCount([
                        'messages as unread_count' => function ($query) use ($request) {
                            $query->where('receiver_id', $request->user_id)
                                ->where('is_read', false);
                        }
                    ])
                    ->orderBy('updated_at', 'desc')
                    ->get()
                    ->map(function ($chat) use ($request) {
                        $otherUserId = $chat->getOtherUserId($request->user_id);
                        
                        $otherUser = ($otherUserId == $chat->user_id_1) ? $chat->user1 : $chat->user2;
                        if($request->test==1){
                        echo '<pre>';
                        print_r($otherUser);
                        }
                        $show_decision_prompt = ($chat->shouldShowDecisionPrompt() ? "1" : "0");
                        if ($show_decision_prompt) {
                            //current user decission noted or not
                            $currnet_check = $chat->getUserDecision($otherUserId);
                            if ($currnet_check) {
                                $show_decision_prompt = 0;
                            }
                        }
                        $last_message = $chat->last_message;
                        $lm = [];
                        if($last_message){
                            $lm = $last_message->toArray();
                        }

                        // If stored as json string, decode to array/object
                        foreach (['question', 'answer'] as $k) {
                            if (!array_key_exists($k, $lm) || $lm[$k] === null || $lm[$k] === '') {
                                $lm[$k] = (object) [];
                            } else {
                                // if it's a JSON string decode it
                                if (is_string($lm[$k])) {
                                    $decoded = json_decode($lm[$k], true);
                                    if (json_last_error() === JSON_ERROR_NONE) {
                                        // if decoded is empty array -> keep empty object
                                        $lm[$k] = empty($decoded) ? (object) [] : $decoded;
                                    } else {
                                        // leave string (but avoid empty string)
                                        $lm[$k] = $lm[$k] === '' ? (object) [] : $lm[$k];
                                    }
                                } elseif (is_array($lm[$k]) && empty($lm[$k])) {
                                    // empty array => convert to empty object if you want {} instead of []
                                    $lm[$k] = (object) [];
                                }
                                // if already object or non-empty array, keep it
                            }
                        }
                        return [
                            'chat_id' => $chat->id,
                            'other_user' => ($otherUser)?$otherUser->toArray():(object)[],
                            'status' => $chat->status,
                            'questions_exchanged' => $chat->questions_exchanged,
                            'unread_count' => $chat->unread_count,
                            'updated_at' => $chat->updated_at->toDateTimeString(),
                            'show_decision_prompt' => $show_decision_prompt,
                            'last_message' => $lm
                        ];
                    });

                if ($chats->count() > 0) {
                    $status = "1";
                    $message = "Chats fetched successfully";
                    $o_data['list'] = convert_all_elements_to_string_new($chats->toArray(), true, ['last_message', 'answer', 'question']);
                } else {
                    $status = "1";
                    $message = "No active chats found";
                }
            }
        } catch (Exception $e) {
            $message = 'Failed to fetch chats';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Get chat statistics
     */
    public function getChatStats(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $rules = [
                'chat_id' => 'required|exists:chats,id',
                'user_id' => 'required|exists:users,id'
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $message = "Please fill all required fields";
                $errors = $validator->messages();
            } else {
                $chat = Chat::findOrFail($request->chat_id);

                // Validate user is part of the chat
                if ($chat->user_id_1 != $request->user_id && $chat->user_id_2 != $request->user_id) {
                    $message = 'You are not part of this chat';
                } else {

                    $show_decision_prompt = ($chat->shouldShowDecisionPrompt() ? "1" : "0");
                    if ($show_decision_prompt) {
                        //current user decission noted or not
                        $currnet_check = $chat->getUserDecision($request->user_id);
                        if ($currnet_check) {
                            $show_decision_prompt = 0;
                        }
                    }
                    $stats = [
                        'questions_exchanged' => $chat->questions_exchanged,
                        'next_milestone' => ceil($chat->questions_exchanged / 5) * 5,
                        'questions_until_decision' => (ceil($chat->questions_exchanged / 5) * 5) - $chat->questions_exchanged,
                        'status' => $chat->status,
                        'show_decision_prompt' => $show_decision_prompt,
                        'decision_deadline' => $chat->decision_deadline ? $chat->decision_deadline->toDateTimeString() : null,
                        'days_remaining' => $chat->decision_deadline ? Carbon::now()->diffInDays($chat->decision_deadline, false) : null,
                        'current_user_decision'=>(string)$chat->getUserDecision($request->user_id),
                        'is_both_user_decided'=> (string)$chat->bothUsersDecided(),
                        'is_both_user_agreed'=>(string)$chat->bothUsersAgreed()
                    ];

                    $status = "1";
                    $message = "Stats fetched successfully";
                    $o_data = convert_all_elements_to_string($stats, true);
                }
            }
        } catch (Exception $e) {
            $message = 'Failed to fetch chat stats';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Send reminder for pending decisions (to be called by cron job)
     */
    public function sendDecisionReminders(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $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) {
                    // Send reminder to both users
                    // TODO: Implement notification system
                    // sendNotification($chat->user_id_1, "Have you made a decision for this proposal?");
                    // sendNotification($chat->user_id_2, "Have you made a decision for this proposal?");

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

                    $remindersCount++;
                }
            }

            $status = "1";
            $message = "Sent {$remindersCount} reminders";
            $o_data = convert_all_elements_to_string(['reminders_sent' => $remindersCount], true);
        } catch (Exception $e) {
            $message = 'Failed to send reminders';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }

    /**
     * Auto-disconnect expired chats (to be called by cron job)
     */
    public function autoDisconnectExpiredChats(Request $request)
    {
        $status = "0";
        $message = "";
        $errors = [];
        $o_data = [];

        try {
            $expiredChats = Chat::where('status', 'need_more_time')
                ->where('decision_deadline', '<', Carbon::now())
                ->get();

            $disconnectedCount = 0;

            foreach ($expiredChats as $chat) {
                $chat->status = 'disconnected';
                $chat->save();

                // TODO: Send notification to both users
                // sendNotification($chat->user_id_1, "The decision period has expired. Profiles have been disconnected.");
                // sendNotification($chat->user_id_2, "The decision period has expired. Profiles have been disconnected.");

                $disconnectedCount++;
            }

            $status = "1";
            $message = "Disconnected {$disconnectedCount} expired chats";
            $o_data = convert_all_elements_to_string(['chats_disconnected' => $disconnectedCount], true);
        } catch (Exception $e) {
            $message = 'Failed to disconnect expired chats';
            $errors = ['error' => [$e->getMessage()]];
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => (object) $o_data,
        ], 200);
    }
}
