<?php

namespace App\Http\Controllers\FCControllers\Survey;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\fcmodels\Wallet;
use App\Models\fcmodels\SurveyRequest;
use EloquentBuilder;
use Exception;

class MobiSurveyRequestController extends Controller
{
        //return view
    public function index()
    {
           if(Auth::check())
        {
            $id = Auth::user()->organization_id;
            $api_account = Auth::user()->api_account;
        }
        else{
            return abort('401');
        }
        $requests = SurveyRequest::where('organization_id',$id)->get();
        $wallet = Wallet::where('shopid',$api_account)->pluck('amount');
        return view('fcviews.mobisurvey.survey-request.index',compact('requests','wallet'));
    }
    //request to use survey
    public function request(Request $request){
             if(Auth::check())
        {
            $id = Auth::user()->organization_id;
            $api_account = Auth::user()->api_account;
        }
        else{
            return abort('401');
        }
        $check = SurveyRequest::where('organization_id',$id)->count();
              if($check > 0)
        {
            return redirect()->back()->with('failure','Request made already! Please check your status or contact admin');
        }
        $request = new SurveyRequest();
        $request->organization_id = $id;
        $request->save();
        // return $request;
        return redirect()->back()->with('success','Request made succesfully! Please wait for approval');
    }
    //admin view enable/disable
    public function view(){
        $query =SurveyRequest::with('surveyOrg');
        $requests=EloquentBuilder::to($query,request()->all())->get();
        
        return view('fcviews.mobisurvey.survey-request.view',compact('requests'));
    }
    //
    //approve
    public function surveyApprove(Request $request)
    {
        $req = SurveyRequest::findOrFail($request->id);
        $req->status = 1;
        $req->save();
        return redirect()->back()->with('success','Approved succesfully!');
    }
    //reject
    public function surveyReject(Request $request)
    {
        request()->validate([
            'reason' => 'required',
            ]);
        $req = SurveyRequest::findOrFail($request->id);
        $req->status = 2;
        $req->reason = $request->reason;
        $req->save();
        return $req;
    }
}