<?php

namespace App\Http\Controllers\api\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\NotificationSetting;
use App\Models\ProfilePictureRequest;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Kreait\Firebase\Contract\Database;

class ProfilePictureRequestController 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();
    }

    private function validateAccesToken($access_token)
    {
        $user = User::where(['user_access_token' => $access_token])->first();
        if (!$user) {
            http_response_code(401);
            echo json_encode([
                'status' => (string) 0,
                'message' => 'Invalid access token',
                'oData' => (object) [],
                'errors' => (object) [],
            ]);
            exit();
        }
        if ($user->status != 1) {
            http_response_code(401);
            echo json_encode([
                'status' => (string) 0,
                'message' => 'User is not active',
                'oData' => (object) [],
                'errors' => (object) [],
            ]);
            exit();
        }
        return $user;
    }

    public function requestProfilePicture(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];

        $validator = Validator::make($request->all(), [
            'receiver_id' => 'required|exists:users,id',
            'access_token' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'message' => 'Validation error occurred',
                'errors' => $validator->errors(),
                'oData' => $o_data,
            ]);
        }

        $user = $this->validateAccesToken($request->access_token);
        $sender_id = $user->id;
        $receiver_id = $request->receiver_id;

        if ($sender_id == $receiver_id) {
            return response()->json([
                'status' => '0',
                'message' => trans('validation.invalid_connection_request'),
                'error' => (object)[],
            ]);
        }

        $existingRequest = ProfilePictureRequest::where('sender_id', $sender_id)
            ->where('receiver_id', $receiver_id)
            ->first();

        if ($existingRequest) {
            return response()->json([
                'status' => '0',
                'message' => trans('validation.already_requested'),
                'oData' => (object)[],
            ]);
        }

        ProfilePictureRequest::create([
            'sender_id' => $sender_id,
            'receiver_id' => $receiver_id,
            'status' => 'requested',
        ]);

        $rUser = User::find($receiver_id);
        
        send_notification_to_user(
            $this->database,
            $rUser,
            ['userId' => (string)$user->id],
            NotificationSetting::REQUEST,
            'profile_picture_request',
            time(),
            trans('notification.profile_picture_request_title', [], 'en') . "\n" . trans('notification.profile_picture_request_title', [], 'ar'),
            $user->name . ' ' . trans('notification.profile_picture_request_message', [], 'en') . "\n" . $user->name . ' ' . trans('notification.profile_picture_request_message', [], 'ar'),
            $user->profile_image_url
        );

        return response()->json([
            'status' => '1',
            'message' => trans('validation.profile_picture_request_sent'),
            'oData' => (object)[],
        ]);
    }

    public function acceptProfilePictureRequest(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];

        $validator = Validator::make($request->all(), [
            'sender_id' => 'required|exists:users,id',
            'access_token' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'message' => 'Validation error occurred',
                'errors' => $validator->errors(),
                'oData' => $o_data,
            ]);
        }

        $user = $this->validateAccesToken($request->access_token);
        $receiver_id = $user->id;
        $sender_id = $request->sender_id;

        $ppRequest = ProfilePictureRequest::where('sender_id', $sender_id)
            ->where('receiver_id', $receiver_id)
            ->where('status', 'requested')
            ->first();

        if (!$ppRequest) {
            return response()->json([
                'status' => '0',
                'message' => trans('validation.can_not_change_request_status'),
                'oData' => (object)[],
            ]);
        }

        $ppRequest->update(['status' => 'accepted']);

        $sUser = User::find($sender_id);

        send_notification_to_user(
            $this->database,
            $sUser,
            ['userId' => (string)$user->id],
            NotificationSetting::REQUEST,
            'profile_picture_request_accepted',
            time(),
            trans('notification.profile_picture_request_accepted_title', [], 'en') . "\n" . trans('notification.profile_picture_request_accepted_title', [], 'ar'),
            $user->name . ' ' . trans('notification.profile_picture_request_accepted_message', [], 'en') . "\n" . $user->name . ' ' . trans('notification.profile_picture_request_accepted_message', [], 'ar'),
            $user->profile_image_url
        );

        return response()->json([
            'status' => '1',
            'message' => trans('validation.profile_picture_request_accepted'),
            'oData' => (object)[],
        ]);
    }

    public function rejectProfilePictureRequest(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];

        $validator = Validator::make($request->all(), [
            'sender_id' => 'required|exists:users,id',
            'access_token' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'message' => 'Validation error occurred',
                'errors' => $validator->errors(),
                'oData' => $o_data,
            ]);
        }

        $user = $this->validateAccesToken($request->access_token);
        $receiver_id = $user->id;
        $sender_id = $request->sender_id;

        $ppRequest = ProfilePictureRequest::where('sender_id', $sender_id)
            ->where('receiver_id', $receiver_id)
            ->where('status', 'requested')
            ->first();

        if (!$ppRequest) {
            return response()->json([
                'status' => '0',
                'message' => trans('validation.can_not_change_request_status'),
                'oData' => (object)[],
            ]);
        }

        $ppRequest->update(['status' => 'rejected']);

        $sUser = User::find($sender_id);

        send_notification_to_user(
            $this->database,
            $sUser,
            ['userId' => (string)$user->id],
            NotificationSetting::REQUEST,
            'profile_picture_request_rejected',
            time(),
            trans('notification.profile_picture_request_rejected_title', [], 'en') . "\n" . trans('notification.profile_picture_request_rejected_title', [], 'ar'),
            $user->name . ' ' . trans('notification.profile_picture_request_rejected_message', [], 'en') . "\n" . $user->name . ' ' . trans('notification.profile_picture_request_rejected_message', [], 'ar'),
            $user->profile_image_url
        );

        return response()->json([
            'status' => '1',
            'message' => trans('validation.profile_picture_request_rejected'),
            'oData' => (object)[],
        ]);
    }
}
