<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserRequest;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class UserRequestController extends Controller
{
    public function receivedIndex($id)
    {
        $requests = [];

        return view('admin.user_requests.indexreceived', compact('requests','id'));
    }

    public function sentIndex($id)
    {
        $requests = [];

        return view('admin.user_requests.indexsent', compact('requests','id'));
    }

    public function getReceivedUserRequestList(Request $request) {
        $sqlBuilder = UserRequest::select([
            'user_requests.*',
            '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('sender')
        ->join('users', 'user_requests.sender_id', '=', 'users.id')
        ->join('nationalities', 'users.nationality_id', '=', 'nationalities.id')
        ->join('user_details', 'users.id', '=', 'user_details.user_id')
        ->join('sects', 'user_details.sect_id', '=', 'sects.id')
        ->join('marital_statuses', 'user_details.marital_status_id', '=', 'marital_statuses.id')
        ->where(['role_id' => 2]);

        $sqlBuilder->orderBy('user_requests.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('receiver_id') && !empty($request->receiver_id)) {
                    $query->where('user_requests.receiver_id', $request->receiver_id);
                }
            })
            ->editColumn('user_image', function ($data) {
                $profileImage = !empty($data->sender->profile_image_url) ? $data->sender->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 '0%';
            })
            ->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_requests.receiveddetails', ['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>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.user_requests.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['user_image','status','action'])
            ->make(true);
    }

    public function getSentUserRequestList(Request $request) {
        $sqlBuilder = UserRequest::select([
            'user_requests.*',
            '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('receiver')
        ->join('users', 'user_requests.receiver_id', '=', 'users.id')
        ->join('nationalities', 'users.nationality_id', '=', 'nationalities.id')
        ->join('user_details', 'users.id', '=', 'user_details.user_id')
        ->join('sects', 'user_details.sect_id', '=', 'sects.id')
        ->join('marital_statuses', 'user_details.marital_status_id', '=', 'marital_statuses.id')
        ->where(['role_id' => 2]);

        $sqlBuilder->orderBy('user_requests.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('sender_id') && !empty($request->sender_id)) {
                    $query->where('user_requests.sender_id', $request->sender_id);
                }
            })
            ->editColumn('user_image', function ($data) {
                $profileImage = !empty($data->receiver->profile_image_url) ? $data->receiver->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 '0%';
            })
            ->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_requests.sentdetails', ['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>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.user_requests.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['user_image','status','action'])
            ->make(true);
    }

    public function create()
    {
        $activity = "";

        return view('admin.user_requests.create', compact('activity'));
    }

    public function sentShow($id)
    {
        $userRequest = UserRequest::findOrFail($id);
        $user = User::with('details')->findOrFail($userRequest->receiver_id);
        $back = route('admin.user_requests.sent', ['id' => $userRequest->sender_id]);
        $pageTitle = 'Sent Request Details';

        return view('admin.user_requests.details', compact('user','back','pageTitle'));
    }

    public function receivedShow($id)
    {
        $userRequest = UserRequest::findOrFail($id);
        $user = User::with('details')->findOrFail($userRequest->sender_id);
        $back = route('admin.user_requests.sent', ['id' => $userRequest->receiver_id]);
        $pageTitle = 'Received Request Details';

        return view('admin.user_requests.details', compact('user','back','pageTitle'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $activity = UserRequest::findOrFail($id);
            $activity->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Activity deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Activity not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the activity.'
            ], 500);
        }
    }

}
