<?php

namespace App\Http\Controllers\API;

# Models
use App\Models\Bit;
use App\Models\Store;
use App\Models\StoreGame;
use App\Models\SingleDigitBit;

# Other Classes
use DB;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Http\Controllers\API\BaseController as BaseController;

class SingleDigitController extends BaseController
{

    #Bind Bit model
    protected $bit;

    #Bind Store model
    protected $store;

    #Bind StoreGame model
    protected $storeGame;

    #Bind SingleDigitBit model
    protected $singleDigitBit;


    /**
     * Defining the default constructor for controller
     *
     */
    public function __construct(
        Bit                        $bit,
        Store                      $store,
        StoreGame                  $storeGame,
        SingleDigitBit             $singleDigitBit
    ) {
        $this->bit                  = $bit;
        $this->store                = $store;
        $this->storeGame            = $storeGame;
        $this->singleDigitBit       = $singleDigitBit;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        DB::beginTransaction();
        try {
            $validator = Validator::make($request->all(), [
                'stores_id' => 'required',
                'game_id' => 'required',
                'type' => 'required',
                'amount' => 'required',
                'bit_place' => 'required',
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }

            $time = '';

            $storess = $this->storeGame->where('stores_id', $request->stores_id)->first();
            if ($request->type == 'OPEN') {
                $time = $storess->opent_time;
            } else {
                $time = $storess->close_time;
            }
            if (timeComapre($time)) {
                return $this->sendError('Error.', "Time Out");
            }


            $totalamount = totalAmount(auth('api')->user()->id);
            $bittotalamout = 0;

            foreach ($request->bit_place as $key => $bit_place) {
                $bittotalamout =  $bittotalamout + $bit_place;
            }


            if ($bittotalamout > $totalamount) {
                return $this->sendError('Error.', "You have not sufficient balance");
            } else {
            }

            $bitcheck = $this->bit->where('stores_id', $request->stores_id)->where('game_id', $request->game_id)->where('user_id', auth('api')->user()->id)->where('type', $request->type)->where('created_at', 'like', currentDate() . '%')->first();
            if (!empty($bitcheck)) {
                $bitcheck->amount = $bitcheck->amount + $request->amount;
                $bitcheck->save();
                $bit = $bitcheck;
            } else {
                #get the requested data in Data variable
                $data = [
                    'stores_id'     => $request->stores_id,
                    'game_id'       => $request->game_id,
                    'day_id'        => $request->day_id,
                    'open_time'     => $request->open_time,
                    'date'          => now(),
                    'type'          => $request->type,
                    'amount'        => $request->amount,
                    'user_id'       => auth('api')->user()->id,

                ];
                #store the newly creted resoures
                $bit = $this->bit->create($data);
            }

                    $app = appDetail();
            $storess = $this->store->whereId($request->stores_id)->first();
            foreach ($request->bit_place as $key => $bit_place) {
                       if ($bit_place < $app->min_bet_amount || $bit_place > $app->max_bet_amount) {
                            return $this->sendError(
                                'Error.',
                                "Bet amount must be Minimum - ₹{$app->min_bet_amount} and Maximum - ₹{$app->max_bet_amount}"
                            );
                        }
                #get the requested data in Data variable
                
                debitAmount(auth('api')->user()->id, $bit_place);
                $check = $this->singleDigitBit->where('bit_place', $key)->where('user_id', auth('api')->user()->id)->where('created_at', 'like', currentDate() . '%')->where('bit_id', $bit->id)->first();
                if (!empty($check)) {
                    $totalAmount = $check->amount + $bit_place;
                    $check->amount = $totalAmount;
                    $check->save();


                    $remark = "Played {$storess->name} {$request->type} single digit {$key} of amount {$totalAmount}";

                    $paymentremark = PaymentRemark(
                        auth('api')->user()->id,
                        $remark,
                        $bit_place,
                        $check->payment_new_history_id
                    );
                } else {


                    $remark =  'Played ' . $storess->name . ' ' . $request->type . ' single digit ' . $key . ' of amount ' . $bit_place;
                    $paymentremark = PaymentRemark(auth('api')->user()->id, $remark, $bit_place);

                    $data = [
                        'bit_id'          => $bit->id,
                        'bit_place'       => $key,
                        'amount'          => $bit_place,
                        'user_id'         => auth('api')->user()->id,
                        'payment_new_history_id'    => $paymentremark->id,
                    ];
                    #store the newly creted resoures
                     $singleDigitBit = $this->singleDigitBit->create($data);
                     PaymentRemarkBit($paymentremark->id,$bit->id);
                }

            }



            DB::commit();
            $success['singleDigitBit'] =  $request->type;

            return $this->sendResponse($success, ' successfully.');
        } catch (\Exception $ex) {
            DB::rollback();
            return $this->sendError('error.', $ex->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
