<?php

namespace App\Http\Controllers\FCControllers;

use Illuminate\Http\Request;
Use Maatwebsite\Excel\Facades\Excel;
use App\Models\fcmodels\APIUser;
use App\Models\fcmodels\Bulksms;
use App\Models\fcmodels\Contact;
use App\Models\fcmodels\Group;
use App\Models\fcmodels\Organization;
use App\Models\fcmodels\Wallet;
use App\Models\fcmodels\CountryRate;
use App\Classes\FCClasses\SendSms;
use App\Classes\FCClasses\Replysms;
use App\Classes\FCClasses\SMSCounter;
use App\Imports\FCClasses\ScheduleImport;
use Carbon\Carbon;
use Auth;
use Log;

class ScheduleSms extends Controller
{
    //
    public function index()
    {
        if(Auth::check())
        {
            $id = Auth::user()->organization_id;
            $api_account = Auth::user()->api_account;
            $name = Auth::user()->name;
        }
        $schedules = Bulksms::where('site',$name)->where('cont_group',NULL)->where('scheduleSMS_status','Pending')->get();
        $wallet = Wallet::where('shopid',$api_account)->pluck('amount');
        $mycountries = CountryRate::where('shopId',$api_account)->with('rateCountry')->get();
        return view('fcviews.schedule.index',compact('wallet','mycountries','schedules'));
        //return $schedules;
    }
    //schedule import
    public function scheduleImport(Request $request)
    {
        if(Auth::check())
        {
            $id = Auth::user()->organization_id;
            $api_account = Auth::user()->api_account;
            $name = Auth::user()->name;
        }
       else{
            return abort('401');
        }


         request()->validate([
            'file' => 'required|max:2000'
         ],
         [
             'file.required' => 'Please select a file first',
             'file.max' => 'Please select a file with size under 2MBs',
             'file.mimes' => 'Accepted file types are Excel with extensions [*.xlsx,*.xls,*.csv]',
         ]
    );
        $path = $request->file;
        $extensions = array("xls","xlsx","xlm","xla","xlc","xlt","xlw","csv");

        $result = array($request->file('file')->getClientOriginalExtension());
        $time = Carbon::create($request->date ." ". $request->time);
        
        if(in_array($result[0],$extensions)){
            Excel::import(new ScheduleImport($id,$time,$api_account), $path);
       
            return redirect()->back()->with('success', 'Scheduled succesfully!'); 
            
        }else{
           return redirect()->back()->with('failure', 'Please select excel file!');
        }
    }
    public function schedule(Request $request)
    {
        request()->validate([
            'contact' => 'required',
            'message' => 'required',
            'time' => 'required'
        ]);
        if(Auth::check())
        {
            $id = Auth::user()->organization_id;
            $Id = Auth::user()->api_account;
            $name = Auth::user()->name;
        }
        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;
               ///////check balance and sum texts costs////
       $wallet = Wallet::where('shopid',$Id)->pluck('amount');
       $arr = [];
       foreach($contacts as $phone)
        {
            $message = $request->message;
            $smscountclass = new SMSCounter();
            $smscount = $smscountclass->count($message)->messages;
            array_push($arr,$smscount);
        }
        $allmessages = array_sum($arr);
        $rates = CountryRate::where('current',1)->where('shopid',$Id)->pluck('rate');
        
        $totalcost = $rates[0]*$allmessages;
        
        if($totalcost>$wallet[0]){
            return response()->json(['errors'=>['message'=>['Sorry! You do not have sufficient funds. Total charges are: '.$totalcost]]],422);
        }
        ///////////
       
        
    }
    
}
