<?php

namespace App\Http\Controllers\FCControllers;

use Illuminate\Http\Request;
use App\Classes\SendSms;
use App\Classes\Replysms;
use App\Classes\SMSCounter;
use App\Models\fcmodels\Incoming;
use App\Models\fcmodels\Import;
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 Maatwebsite\Excel\Facades\Excel;
use App\Imports\FCImports\CustomImport;
use Maatwebsite\Excel\Exceptions\NoTypeDetectedException;
use Illuminate\Support\Facades\Schema;
use Auth;
use Log;
use DB;
use Illuminate\Database\Schema\Blueprint;

class CustomSMSController extends Controller
{
    public function index(){
          
         if(Auth::check())
        {
            $Id = Auth::user()->api_account;
        }
        else{
            return abort('401');
        }
        
        if(Auth::check())
        {
            $id = Auth::user()->organization_id;
        }
        else{
            return abort('401');
        }
       //get the organization id
       $custom_table='customtable_'.$id;
       //check if the table exists
       $tablecheck=Schema::hasTable($custom_table);
        
       if($tablecheck){
           
           $mycustomdatacount = DB::select( DB::raw("SELECT * FROM $custom_table") );
           $mycustomdata = DB::select( DB::raw("SELECT * FROM $custom_table LIMIT 1") );
           $wallet = Wallet::where('shopid',$Id)->pluck('amount');
           $mycustomdatacontacts = DB::select( DB::raw("SELECT * FROM $custom_table") );
                  
           //check for invalid phone numbers from the table
           
           $invalid_nos=[];
           
           $arr=array();
           
           foreach($mycustomdatacount as $msg)
            {
                $message = $msg->sms;
                $smscountclass = new SMSCounter();
                $smscount = $smscountclass->count($message)->messages;
                array_push($arr,$smscount);
                
                //check for invalid numbers
                $no=str_replace(" ","",$msg->number);
              
                //071222222, 25478888999
                //format the number to pick any format
                 //format the number to pick any format
                if((substr($no, 0, 4)=="+254")||(substr($no, 0, 3)=="254")||(substr($no, 0, 2)=="07")||(substr($no, 0, 2)=="01")||(substr($no, 0, 1)=="7")){
                          
                            if(substr($no, 0, 4)=="+254"){
                              if(strlen($no)!=13){
                                  array_push($invalid_nos,$no);
                              }  
                            }
                            
                            elseif(substr($no, 0, 3)=="254"){
                                if(strlen($no)!=12){
                                  array_push($invalid_nos,$no);
                              } 
                            }
                            elseif(substr($no, 0, 2)=="07"){
                                if(strlen($no)!=10){
                                  array_push($invalid_nos,$no);
                              } 
                            }
                            elseif(substr($no, 0, 2)=="01"){
                                if(strlen($no)!=10){
                                  array_push($invalid_nos,$no);
                              } 
                            }
                            elseif(substr($no, 0, 1)=="7"){
                                array_push($invalid_nos,$no); 
                            }
                        
                     }
                     else{
                          array_push($invalid_nos,$no);
                     }
                 //check if the number has 254718014207 12characters
            }
            
            $allmessages = array_sum($arr);
           
            $rates = CountryRate::where('current',1)->where('shopid',$Id)->pluck('rate');
            
            
            $totalcost = $rates[0]*$allmessages;
            $checkaccount="";
            
            if($totalcost>$wallet[0]){
                $checkaccount='Sorry! You do not have sufficient funds. Total charges are: '.$totalcost;
            }
            else{
                 
                $checkaccount='Balance sufficient.Proceed';
            
            }
           
            
           return view('fcviews.customsms.index',compact('wallet','mycustomdata','rates','allmessages','totalcost','checkaccount','mycustomdatacount','invalid_nos','mycustomdatacontacts'));
         
       }
       else{
           $invalid_nos=[];
           $mycustomdatacount =array();
           $mycustomdata = array();
           $wallet = $wallet = Wallet::where('shopid',$Id)->pluck('amount');
           
          
           
            $allmessages =0;
        
        
            $rates = CountryRate::where('current',1)->where('shopid',$Id)->pluck('rate');
            
            
            $totalcost = $rates[0]*0;
            $checkaccount="";
            
            if($totalcost>$wallet[0]){
                $checkaccount='Sorry! You do not have sufficient funds. Total charges are: '.$totalcost;
            }
            else{
                 
                $checkaccount='Balance sufficient.Proceed';
            
            }
            $mycustomdatacontacts=array();
            return view('fcviews.customsms.index',compact('wallet','mycustomdata','rates','allmessages','totalcost','checkaccount','mycustomdatacount','invalid_nos'));
       }
     
    }
    //drop table on cancel
    public function drop(Request $request)
    {
        if(Auth::check())
        {
            $id = Auth::user()->organization_id;
        }
        else{
            return abort('401');
        }
        //if the table exists,drop the table
            Schema::dropIfExists('customtable_'.$id);
            return back()->with('success','Custom sms cancelled successfully.');
    }
    
    public function customImport(Request $request){
        
        if(Auth::check())
        {
            $id = Auth::user()->organization_id;
        }
        else{
            return abort('401');
        }


         request()->validate([
            'file' => 'required|max:2000',
            'message' => 'required',
         ],
         [
             'file.required' => 'Please select an Excel or CSV File',
             '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;
        $message = $request->message;
        try{
            
                   $path = $request->file;
        $extensions = array("xls","xlsx","xlm","xla","xlc","xlt","xlw","csv");

        $result = array($request->file('file')->getClientOriginalExtension());
        
        if(in_array($result[0],$extensions)){
             Excel::import(new CustomImport($id,$message), $path);
       
            return redirect()->back(); 
            
        }else{
           return redirect()->back()->with('failure', 'Please select excel file!');
        }
  
            return back();
        }
        catch(Exception $e){
            
       
        //catch (NoTypeDetectedException $e) {
          //  return redirect()->back()->with('failure', 'Wrong File format Uploaded!'); 
            if(get_class($e)=="Illuminate\Database\QueryException"){
               
               Schema::dropIfExists('customtable_'.$id);
               
               return redirect()->back()->with('failure', substr($e->getMessage(), 54,31).' found in document.Remove duplicate(s) and retry!'); 
            }
            else{
               //return redirect()->back()->with('failure', 'Wrong File format Uploaded!');  
               return $e->getMessage();
            }
            
            return $e;//;
        }
        
        
    }
    
    public function submitCustomMessage(Request $request){
        
        if(Auth::check())
        {
            $id = Auth::user()->organization_id;
            $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'];
        
        //get the organization id
       $custom_table='customtable_'.$id;
       $mycustomdata = DB::select( DB::raw("SELECT * FROM $custom_table") );
       
       $contact_arr=[];
       $successstatus=[];
       $failedtatus=[];
      
       foreach($mycustomdata as $mymessage){
          
            $message = $mymessage->sms;
            $phone=$mymessage->number;
            $smsobject=new SendSms($username,$password);
    
            $textstatus=$smsobject->sendMessage($phone,$message);
            $recordid=$mymessage->id;
            //if the text status=sent/success remove it from the list on the table
            if(($textstatus=="Success")||($textstatus=="Sent")){
                
                
                $state="Success";
                array_push($successstatus,$state);
                
                $deleterecord = DB::select( DB::raw("DELETE FROM $custom_table WHERE id='$recordid'") );
                
            }
            elseif(($textstatus!="Success")||($textstatus!="Sent")){
                
                $statefailed="Failed";
                
                $updaterecord = DB::select( DB::raw("UPDATE $custom_table SET reason = '$textstatus' WHERE id='$recordid'") );
                
                array_push($failedtatus,$statefailed);
                
            }
          
       }
       
       $message="Success:".count($successstatus)." Failed: ".count($failedtatus);
       return response()->json($message,200);
    //   return redirect()->back()->with('success', $message);
  
        
    }
  
}