<?php

namespace App\Http\Controllers;

use App\Http\Component\AppController;
use App\Http\Services\CouponService;
use App\Http\Services\GiftService;
use App\Models\Investment;
use App\Models\Raffles;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;

/**
 * Laravel/Symfony Developer
 * Name: Muongozo
 * Telegram: @muongozotrader
 * Hire me via Telegram: muongozotrader
 */
class GiftController extends AppController
{
    private $gift;
    private $activeTemplate;

    public function __construct(
        GiftService $gift
    )
    {
        $this->gift = $gift;
        $this->activeTemplate = activeTemplate();
    }

    public function redeem(Request $request){

       // Validate
       $validator = Validator::make($request->all(),[
        'code' => 'required|string'
        ]);

        // Failed to validate
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            $notify[] = ['error', implode(' ', $errors)];
            return $this->handleResponse($request, implode(' ', $errors), 401, $notify);
        }

        // User
       $user = User::find(\auth()->user()->id);

        // Redeem
       $gift = $this->gift->redeem($user, $request->code);
       
       // Exception
       if($gift instanceof \Exception) {
        // Redirect
        $notify[] = ['error', $gift->getMessage()];
        return $this->handleResponse($request, $gift->getMessage(), 401, $notify);
       }

       // Success Response
       return $this->handleResponseRedirect($request, 'Successful', 200, url(route('user.transaction')), 'user.transaction', ['type' => 'withdraw']);

    }

    public function gift()
    {
        $pageTitle = 'Gift';
        
        return view($this->activeTemplate. 'user.gift', compact(
            'pageTitle'
        ));
    }

    public function raffleDraw()
    {
        $pageTitle = 'Raffle Draw Contest';
        $user = auth()->user(); $myown = [];

		$raffles = Cache::get('selectedRaffling');

		$invests = Investment::where('user_id', $user->id)->count();
		if($invests){
			if (!$raffles) {
				$raffles = Raffles::where('status', 1)->orderByRaw('RAND()')->take(1)->first();
				if( $raffles ){
					
					/*$raffles->status = 0;
					$raffles->user_id = $user->id;
					$raffles->save();*/

					Cache::put('selectedRaffling', $raffles);
				}
			}
		}

		if( !$raffles ){
			$myown = Raffles::where('user_id', $user->id)->get();
		}
		
        return view($this->activeTemplate. 'user.raffle', compact(
            'pageTitle','user','invests','raffles','myown'
        ));
    }

    public function raffleAnswer(Request $request){

       // Validate
       $validator = Validator::make($request->all(),[
        'id' => 'required|numeric',
        'answer' => 'required|string'
        ]);

        // Failed to validate
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            $notify[] = ['error', implode(' ', $errors)];
            return $this->handleResponse($request, implode(' ', $errors), 401, $notify);
        }
		
        // User
		$user = auth()->user();

		$raffle = Raffles::where('id', $request->id)->first();
		
		if( !$raffle ){
			$error = 'Request does not exist any more';
            $notify[] = ['error', $error];
            Cache::forget('selectedRaffling');
            return $this->handleResponse($request, $error, 401, $notify);
		}

		if( $raffle->user_id || $raffle->status == 2 ){
			$error = 'Sorry this card has just been used by another user.';
            $notify[] = ['error', $error];
            Cache::forget('selectedRaffling');
            return $this->handleResponse($request, $error, 401, $notify);
		}
		
		if( strtolower($raffle->quiz->answer) != strtolower($request->answer) ){
			$error = 'Sorry your answer to the question is incorrect. Try again.';
            $notify[] = ['error', $error];
            return $this->handleResponse($request, $error, 401, $notify);
		}
		
		$raffle->status = 2;
		$raffle->user_id = $user->id;
		$raffle->save();
		Cache::forget('selectedRaffling');
		Cache::put('selectedRaffling', $raffle);

        $notify[] = ['success', 'Successfully. You can now use the card'];
        return redirect()->back()->withNotify($notify);

	}

	
}
