<?php

namespace App\Http\Controllers\API;

# Models
use App\Models\WithdrawHistory;
use App\Models\WithdrawStatus;
use App\Models\Withdraw;
use App\Models\AppDetail;
use App\Models\WithdrawTiming;

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

class WithdrwController extends BaseController
{

    #Bind WithdrawHistory model
    protected $withdrawHistory;

    #Bind WithdrawStatus model
    protected $withdrawStatus;

    #Bind Withdraw model
    protected $withdraw;

    #Bind AppDetail model
    protected $appDetail;


    #Bind WithdrawTiming model
    protected $withdrawTiming;


    /**
     * Defining the default constructor for controller
     *
     */
    public function __construct(
        AppDetail $appDetail,
        Withdraw $withdraw,
        WithdrawStatus $withdrawStatus,
        WithdrawTiming            $withdrawTiming,
        WithdrawHistory $withdrawHistory
    ) {
        $this->appDetail              = $appDetail;
        $this->withdraw              = $withdraw;
        $this->withdrawStatus        = $withdrawStatus;
        $this->withdrawHistory       = $withdrawHistory;
        $this->withdrawTiming          = $withdrawTiming;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        DB::beginTransaction();
        try {

            $realtion = ['withdrawStatus'];
            $withdrwar = $this->withdraw->with($realtion)->where('user_id', auth('api')->user()->id)->get();
            $data = array();
            $i = 0;
            foreach ($withdrwar as $key => $value) {
                $data[$i]['sno'] = $i + 1;
                $data[$i]['amount'] = $value->amount;
                $data[$i]['date'] =  dateShow($value->created_at);
                $data[$i]['time'] = timeShow($value->created_at);
                $data[$i]['status'] = $value->withdrawStatus->name;
                $data[$i]['remark'] = $value->remark;
                $i++;
            }

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

    /**
     * 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(), [
                'amount' => 'required',
                'remark' => 'required',
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            
            
            $todayDayId = Carbon::now()->isoWeekday();

            $withdrawTiming = $this->withdrawTiming
                ->where('day_id', $todayDayId)
                ->first();
            
            if (!$withdrawTiming) {
                return $this->sendError(
                    'Error.',
                    'Withdraw timing not configured for today.'
                );
            }
            
            // Check day status
            if (!$withdrawTiming->status) {
                return $this->sendError(
                    'Error.',
                    'Withdraw service is currently unavailable today.'
                );
            }
            
            // Check minimum withdraw amount
            if ($request->amount < $withdrawTiming->minimum_withdraw) {
                return $this->sendError(
                    'Error.',
                    'Minimum Withdraw Amount is ₹' . $withdrawTiming->minimum_withdraw
                );
            }
            
            $currentTime = Carbon::now()->format('H:i');
            
            $startTime = $withdrawTiming->start_time;
            $endTime   = $withdrawTiming->end_time;
            
            if ($currentTime < $startTime || $currentTime > $endTime) {
                return $this->sendError(
                    'Error.',
                    "Withdraw allowed only between {$startTime} and {$endTime}"
                );
            }

            $totalamount = totalAmount(auth('api')->user()->id);
            if ($request->amount > $totalamount) {
                return $this->sendError('Error.', "You have not sufficient balance");
            } else {
                debitAmount(auth('api')->user()->id, $request->amount);
            }

            $data = [

                'amount'                   => $request->amount,
                'user_id'                  => auth('api')->user()->id,
                'withdraw_status_id'       => 1,
                'remark'                   => $request->remark,

            ];
            $withdrwar = $this->withdraw->create($data);

            $data1 = [

                'amount'                   => $request->amount,
                'user_id'                  => auth('api')->user()->id,
                'withdraw_status_id'       => 1,
                'remark'                   => $request->remark,
                'withdraw_id'              =>  $withdrwar->id,

            ];
            $this->withdrawHistory->create($data1);
            $remarksss = 'Withdraw request amount ' . $request->amount;

            PaymentNewRemark(auth('api')->user()->id, $remarksss, $request->amount);
            DB::commit();
            $success['withdraw'] =  "withdraw request";
            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)
    {
        //
    }
}
