<?php

namespace App\Http\Controllers\FCControllers;

use Illuminate\Http\Request;
use Auth;
use Exception;
use Hash;
use App\Models\fcmodels\IvrRequest;
use App\Models\fcmodels\Organization;
use App\Models\fcmodels\Wallet;
use App\Models\fcmodels\Shop;
use App\Models\fcmodels\Ivr;
use App\Models\fcmodels\Contact;
use App\Models\fcmodels\Group;
use App\Models\fcmodels\APIUser;
use App\Classes\fcmodels\IvrCall;
use EloquentBuilder;
use Config;

class IvrController extends Controller
{
    //
    public function index(){
        if(Auth::check())
        {
            $id = Auth::user()->cust_id;
            $name = Auth::user()->name;
            $api_account = Auth::user()->api_account;
        }
        
        else{
            return abort('401');
        }
        $requests = IvrRequest::where('organization_id',$id)->get();
        $wallet = Wallet::where('shopid',$api_account)->pluck('amount');
        return view('fcviews.ivr-request.index',compact('requests','wallet'));
    }

    public function view(){
        //$requests = IvrRequest::with('ivrOrg')->get();
        
        $query =IvrRequest::with('ivrOrg');
        $requests=EloquentBuilder::to($query,request()->all())->get();
        
        return view('fcviews.ivr-request.view',compact('requests'));
    }
    /////Sending IVR blade
    public function sending(){
        if(Auth::check())
        {
            $id = Auth::user()->cust_id;
            $name = Auth::user()->name;
            $api_account = Auth::user()->api_account;
        }
        else{
            return abort('401');
        }
                //get my contacts
        $contacts = Contact::where('organization_id',$id)->get();
        $groups = Group::where('organization_id',$id)->get();

        $ivr = Ivr::where('organization_id',$id)->get();
        $wallet = Wallet::where('shopid',$api_account)->pluck('amount');
        return view('fcviews.ivr.index',compact('ivr','wallet','contacts','groups'));
    }

    public function request(Request $request){
        if(Auth::check())
        {
            $id = Auth::user()->cust_id;
            $name = Auth::user()->name;
            $api_account = Auth::user()->api_account;
        }
        else{
            return abort('401');
        }
        $check = IvrRequest::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 IvrRequest();
        $request->organization_id = $id;
        $request->save();
        // return $request;
        return redirect()->back()->with('success','Request made succesfully! Please wait for approval');
    }
    //approve
    public function ivrApprove(Request $request)
    {
        $req = IvrRequest::findOrFail($request->id);
        $req->status = 1;
        $req->save();
        return redirect()->back()->with('success','Approved succesfully!');
    }
    //reject
    public function ivrReject(Request $request)
    {
        request()->validate([
            'reason' => 'required',
            ]);
        $req = IvrRequest::findOrFail($request->id);
        $req->status = 2;
        $req->reason = $request->reason;
        $req->save();
        return $req;
    }
    
    
    //ivr call to saved contacts
    public function ivrContact(Request $request){
        request()->validate([
            'contact' => 'required',
            // 'message' => 'required',
        ]);
        if(Auth::check())
        {
            $orgid = Auth::user()->cust_id;
            $name = Auth::user()->name;
            $Id = Auth::user()->api_account;
        }
        else{
            return abort('401');
        }
        //get user creds
        $api = APIUser::where('shop_id',$Id)->first();
        //send sms
        $username = $api['username'];
        $password = $api['password'];
        $contact_arr=[];
        $contacts = $request->contact;
        $organization=$orgid;
        
        // foreach($contacts as $phone)
        // {
        //     return $phone;
            $ivr = new Ivr();
            $ivr->contact=$contacts;
            $file=NULL;
            //upload file
            if($request->file('file'))
            {
                $files = $request->file('file');
                $destinationPath = 'ivrs/'; // upload path
                $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
                $files->move($destinationPath, $profileImage);
                $file =  Config::get('app.url').'/'.$destinationPath.$profileImage;
            }
        
            $ivr->message=$request->message;
            $ivr->file=$file;
            $ivr->status=0;//0->pending,1-completed,2-started
            $ivr->organization_id=$orgid;
            $ivr->save();
            //start call
            $call = new IvrCall($username,$password);
            $status = $call->sendVoice($contacts,$request->message,$organization);
            return redirect()->back()->with('success','IVR Call made successfully');
            // array_push($contact_arr,$ivr);
        // }
        // return $ivr;
    }
    //send to group
    public function ivrGroup(Request $request){
        request()->validate([
            'group' => 'required',
            // 'message' => 'required',
        ]);
        if(Auth::user()->user_type == 'organization')
        {
            $orgid = Auth::user()->cust_id;
            $name = Auth::user()->name;
            $Id = Auth::user()->api_account;
        }
        else{
            return abort('401');
        }
        //get grouped contacts
        $contacts = Contact::where('group_id',$request->group/*[0]['group_id']*/)->pluck('phone');
        
        //get user creds
        $api = APIUser::where('shop_id',$Id)->first();
        //send sms
        $username = $api['username'];
        $password = $api['password'];
        
        $contact_arr=[];
        $file=NULL;
            //upload file
            if($request->file('file'))
            {
                $files = $request->file('file');
                $destinationPath = 'ivrs/'; // upload path
                $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
                $files->move($destinationPath, $profileImage);
                $file =  Config::get('app.url').'/'.$destinationPath.$profileImage;
            }
        
            
        foreach($contacts as $phone)
        {
            $ivr = new Ivr();
            $ivr->contact=$phone;
            $ivr->message=$request->message;
            $ivr->file=$file;
            $ivr->status=0;//0->pending,1-completed,2-started
            $ivr->organization_id=$orgid;
            $ivr->save();
            $call = new IvrCall($username,$password);
            $status = $call->sendVoice($phone,$request->message,$orgid);
            
            array_push($contact_arr,$ivr);
        }
         return redirect()->back()->with('success','IVR Call made successfully');
        // return $ivr;
    }
}
