<?php

namespace App\Http\Controllers\Web;

use Inertia\Inertia;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\RequestResource;
use App\Models\Request as RequestModel;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use TimeHunter\LaravelGoogleReCaptchaV3\Validations\GoogleReCaptchaV3ValidationRule;

class RequestController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $requests = RequestModel::query()
            ->orderByDesc('created_at')
            ->get();

        return Inertia::render('Requests', [
            'requests' => RequestResource::collection($requests),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        $rules = [
            'phone' => ['required'],
            'password' => ['required'],
            'first_name' => ['required'],
            'last_name' => ['required'],
            'email' => ['required', 'email'],
            'org_type' => ['required'],
            'items' => ['required', 'array'],
            'items.*.id' => ['required'],
            'totalPrice' => ['required', 'numeric'],
            'currency' => ['required', 'in:TMT,USD']
        ];
        $validator = Validator::make($input, $rules);
        if($validator->fails()) {
            return response()->json([
                'status' => 400,
                'validationErrors' => $validator->errors()
            ], 400);
        }

        $loginResponse = Http::post('http://127.0.0.1:8000/api/auth-for-make-requests', [
            'username' => $input['phone'],
            'password' => $input['password'],
        ]);

        $loginResponseStatus = $loginResponse->status();

        switch ($loginResponseStatus) {
            case 401:
                return response()->json([
                    'status' => $loginResponseStatus, // 401
                    'message' => 'Unauthorized',
                    'response' => $loginResponse
                ], $loginResponseStatus);
                break;

            case 200:
                // check user balance
                $fee = $input['totalPrice'];
                // if($input['currency'] == 'USD') {
                //     $fee = $fee * settings('local_price') / settings('int_price'); // fee - converted to TMT price
                // }
                if($loginResponse['user']['user_balance'] - $fee < 0) {
                    return response()->json([
                        'status' => 300, // 300
                        'message' => 'Fill up your balance',
                        'response' => $loginResponse
                    ], 300);
                }

                // try to withdraw fee from the balance for creating a request
                $balanceResponse = Http::post('http://127.0.0.1:8000/api/v1/withdraw-from-balance?token=' . $loginResponse['token'], [
                    // 'token' => $loginResponse['token'],
                    'total_price' => $input['totalPrice'], // USD or TMT
                    'currency' => $input['currency'],
                    'fee' => $fee,
                    'items' => $input['items'],
                    'first_name' => $input['first_name'],
                    'last_name' => $input['last_name'],
                    'org_type' => $input['org_type'],
                    'email' => $input['email']
                ]);
                
                $balanceResponseStatus = $balanceResponse->status();
                
                if($balanceResponseStatus == 201) {
                    RequestModel::create(array_merge($request->only(['first_name', 'last_name', 'email', 'org_type', 'items']), [
                        'phone' => $input['phone']
                    ]));
                }

                if($balanceResponseStatus == 500) {
                    return response()->json([
                        'status' => $balanceResponseStatus, // 500
                        'message' => 'Internal Server Error',
                        'response' => $balanceResponse
                    ], $balanceResponseStatus);
                    break;
                }

                return response()->json([
                    'status' => $balanceResponseStatus, // 201 (ok)
                    'message' => $balanceResponse['message'],
                    'response' => $balanceResponse
                ], $balanceResponseStatus);
                break;
            
            case 500:
                return response()->json([
                    'status' => $loginResponseStatus, // 500
                    'message' => 'Internal Server Error',
                    'response' => $loginResponse
                ], $loginResponseStatus);
                break;

            default:
                return response()->json([
                    'status' => $loginResponseStatus,
                    'message' => 'Unknown Server Error',
                    'response' => $loginResponse
                ], $loginResponseStatus);
                break;
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function destroy(RequestModel $request)
    {
        $request->delete();

        return redirect()->back();
    }
}
