<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserMatch;
use App\Models\Chat;
use App\Models\AdminMatchNotification;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class UserMatchController extends Controller
{
    public function index($id)
    {
        $requests = [];

        return view('admin.user_matches.index', compact('requests','id'));
    }

    public function getUserMatchList(Request $request) {
        $sqlBuilder = UserMatch::select([
            'user_matches.*',
            'users.name',
            'users.nick_name',
            'users.dial_code',
            'users.phone',
            'users.email',
            'users.gender',
            'users.created_at',
            'users.profile_image',
            'users.user_number',
            'nationalities.name as nationality_name',
            'sects.name as sect_name',
            'marital_statuses.name as marital_status_name',
        ])->with('match')
        ->leftJoin('users', 'user_matches.matched_user_id', '=', 'users.id')
        ->leftJoin('nationalities', 'users.nationality_id', '=', 'nationalities.id')
        ->leftJoin('user_details', 'users.id', '=', 'user_details.user_id')
        ->leftJoin('sects', 'user_details.sect_id', '=', 'sects.id')
        ->leftJoin('marital_statuses', 'user_details.marital_status_id', '=', 'marital_statuses.id')
        ->where(['role_id' => 2]);

        $sqlBuilder->orderBy('user_matches.id', 'desc');

        return DataTables::of($sqlBuilder)
            ->filter(function ($query) use ($request) {
                if ($request->has('search') && !empty($request->search['value'])) {
                    $query->where(function ($query) use ($request) {
                        $query->where('users.name', 'ilike', "%{$request->search['value']}%")
                        ->orWhere('users.nick_name', 'ilike', "%{$request->search['value']}%")
                        ->orWhere('users.dial_code', 'ilike', "%{$request->search['value']}%")
                        ->orWhere('users.phone', 'ilike', "%{$request->search['value']}%")
                        ->orWhere('users.email', 'ilike', "%{$request->search['value']}%")
                        ->orWhere('users.user_number', 'ilike', "%{$request->search['value']}%")
                        ->orWhere('nationalities.name', 'ilike', "%{$request->search['value']}%")
                        ->orWhere('sects.name', 'ilike', "%{$request->search['value']}%");
                    });
                }

                if ($request->has('user_id') && !empty($request->user_id)) {
                    $query->where('user_matches.user_id', $request->user_id);
                }
            })
            ->editColumn('user_image', function ($data) {
                $profileImage = !empty($data->match->profile_image_url) ? $data->match->profile_image_url : asset('assets/images/camera_placeholder.png');
                return '<div style="text-align:center;"><img src="' . $profileImage . '" class="rounded-circle avatar-xs" alt="profile-image"></div>';
                
            })

            ->editColumn('phone', function ($data) {
                return $data->dial_code . ' ' . $data->phone;
            })
            ->editColumn('match_percentage', function ($data) {
                return $data->match_percentage.'%';
            })
            ->editColumn('status', function ($data) {
                switch ($data->status) {
                    case 0:
                        return '<span class="badge bg-warning">Pending</span>';
                    case 1:
                        return '<span class="badge bg-success">Accepted</span>';
                    case 2:
                        return '<span class="badge bg-danger">Rejected</span>';
                    default:
                        return '<span class="badge bg-secondary">Unknown</span>';
                }
            })
            ->editColumn('created_at', function ($data) {
            return $data->created_at->format('d/m/y H:i A');
            })
            ->addColumn('action', function ($data) {
                $detailsUrl = route('admin.user_matches.details', ['id' => $data->id]);
                $html = '<div class="dropdown">
                                        <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="ri-more-2-fill"></i>
                                        </a>

                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                                            <li><a class="dropdown-item" href="' . $detailsUrl . '">Details</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['user_image','status','action'])
            ->make(true);
    }

    public function show($id)
    {
        $match = UserMatch::findOrFail($id);
        $user = User::with('details')->findOrFail($match->user_id);
        $user1 = User::with('details')->findOrFail($match->matched_user_id);
        $back = route('admin.user_matches.index', ['id' => $match->user_id]);
        $pageTitle = 'Match Details';

        return view('admin.user_matches.details', compact('user','user1','back','pageTitle','match'));
    }

    // Match Request Notification Methods
    public function checkNewNotifications()
    {
        $unreadNotifications = AdminMatchNotification::where('is_read', false)
            ->with(['user1:id,name,nick_name,gender', 'user2:id,name,nick_name,gender'])
            ->orderBy('created_at', 'desc')
            ->get();
        
        return response()->json([
            'status' => 'success',
            'count' => $unreadNotifications->count(),
            'notifications' => $unreadNotifications->map(function($notification) {
                $male = $notification->user1->gender == 'Male' ? $notification->user1 : $notification->user2;
                $female = $notification->user1->gender == 'Female' ? $notification->user1 : $notification->user2;
                
                return [
                    'id' => $notification->id,
                    'chat_id' => $notification->chat_id,
                    'male_name' => $male->name . ' (' . $male->nick_name . ')',
                    'female_name' => $female->name . ' (' . $female->nick_name . ')',
                    'created_at' => $notification->created_at->diffForHumans(),
                    'detail_url' => route('admin.match.requests.show', $notification->chat_id)
                ];
            })
        ]);
    }

    public function markAsRead($id)
    {
        $notification = AdminMatchNotification::findOrFail($id);
        $notification->update([
            'is_read' => true,
            'read_at' => now()
        ]);
        
        return response()->json([
            'status' => 'success',
            'message' => 'Notification marked as read'
        ]);
    }

    // Match Request Pages
    public function matchRequestsIndex()
    {
        return view('admin.match_requests.index');
    }

    public function getMatchRequestsData(Request $request)
    {
        $chats = Chat::where('status', 'completed')
            ->where('user_1_decision', 'yes')
            ->where('user_2_decision', 'yes')
            ->with(['user1', 'user2'])
            ->select(['id', 'user_id_1', 'user_id_2', 'questions_exchanged', 'created_at', 'updated_at']);
        
        return DataTables::of($chats)
            ->addColumn('male_user', function($chat) {
                $male = $chat->user1->gender == 'Male' ? $chat->user1 : $chat->user2;
                return $male->name . ' (' . $male->nick_name . ')';
            })
            ->addColumn('female_user', function($chat) {
                $female = $chat->user1->gender == 'Female' ? $chat->user1 : $chat->user2;
                return $female->name . ' (' . $female->nick_name . ')';
            })
            ->editColumn('created_at', function($chat) {
                return $chat->created_at->format('d/m/Y h:i A');
            })
            ->addColumn('action', function($chat) {
                return '<a href="' . route('admin.match.requests.show', $chat->id) . '" class="btn btn-sm btn-primary">View Details</a>';
            })
            ->rawColumns(['action'])
            ->make(true);
    }

    public function showMatchRequest($id)
    {
        $chat = Chat::with([
            'user1.details.sect',
            'user1.details.education',
            'user1.details.profession',
            'user1.details.maritalStatus',
            'user1.details.dressCode',
            'user1.nationality',
            'user1.emirate',
            'user1.activities.activity',
            'user1.sports.sport',
            'user1.known_languages.language',
            'user1.geneticDiseases.geneticDisease',
            'user1.children',
            'user1.maritalStatuses.maritalStatus',
            'user1.dressCodes.dressCode',
            'user1.preference.sect',
            'user1.preference.education',
            'user1.preference.profession',
            'user1.plan',
            'user2.details.sect',
            'user2.details.education',
            'user2.details.profession',
            'user2.details.maritalStatus',
            'user2.details.dressCode',
            'user2.nationality',
            'user2.emirate',
            'user2.activities.activity',
            'user2.sports.sport',
            'user2.known_languages.language',
            'user2.geneticDiseases.geneticDisease',
            'user2.children',
            'user2.maritalStatuses.maritalStatus',
            'user2.dressCodes.dressCode',
            'user2.preference.sect',
            'user2.preference.education',
            'user2.preference.profession',
            'user2.plan',
            'messages.question',
            'messages.answer'
        ])->findOrFail($id);
        
        // Determine male and female users
        $maleUser = $chat->user1->gender == 'Male' ? $chat->user1 : $chat->user2;
        $femaleUser = $chat->user1->gender == 'Female' ? $chat->user1 : $chat->user2;
        
        // Mark notification as read when viewing
        AdminMatchNotification::where('chat_id', $id)
            ->where('is_read', false)
            ->update(['is_read' => true, 'read_at' => now()]);
        
        return view('admin.match_requests.show', compact('chat', 'maleUser', 'femaleUser'));
    }

    public function downloadPdf($id)
    {
        $chat = Chat::with([
            'user1.details.sect',
            'user1.details.education',
            'user1.details.profession',
            'user1.details.maritalStatus',
            'user1.details.dressCode',
            'user1.nationality',
            'user1.emirate',
            'user1.activities.activity',
            'user1.sports.sport',
            'user1.known_languages.language',
            'user1.geneticDiseases.geneticDisease',
            'user1.children',
            'user1.maritalStatuses.maritalStatus',
            'user1.dressCodes.dressCode',
            'user1.preference.sect',
            'user1.preference.education',
            'user1.preference.profession',
            'user1.plan',
            'user2.details.sect',
            'user2.details.education',
            'user2.details.profession',
            'user2.details.maritalStatus',
            'user2.details.dressCode',
            'user2.nationality',
            'user2.emirate',
            'user2.activities.activity',
            'user2.sports.sport',
            'user2.known_languages.language',
            'user2.geneticDiseases.geneticDisease',
            'user2.children',
            'user2.maritalStatuses.maritalStatus',
            'user2.dressCodes.dressCode',
            'user2.preference.sect',
            'user2.preference.education',
            'user2.preference.profession',
            'user2.plan',
            'messages.question',
            'messages.answer'
        ])->findOrFail($id);
        
        // Determine male and female users
        $maleUser = $chat->user1->gender == 'Male' ? $chat->user1 : $chat->user2;
        $femaleUser = $chat->user1->gender == 'Female' ? $chat->user1 : $chat->user2;
        
        $pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('admin.match_requests.pdf', compact('chat', 'maleUser', 'femaleUser'));
        return $pdf->download("Match_Request_" . $maleUser->nick_name . "_" . $femaleUser->nick_name . "_" . date('Y_m_d') . ".pdf");
    }

}
