<?php
 
namespace App\Http\Controllers\FCControllers;
use Auth;
use Hash;
use Exception;
use App\Charts\FCCharts\SMSChart;
use EloquentBuilder;
use App\Models\fcmodels\Organization;
use App\Models\fcmodels\AuditLog;
use App\Models\fcmodels\Wallet;
use App\Models\fcmodels\Shop;
use App\Models\fcmodels\Ivr;
use App\Models\fcmodels\Incoming;
use App\Models\User;
use  App\Charts\NewChart;
use DB;
use Log;
use App\Models\fcmodels\ApiTopup;
use App\Models\fcmodels\Currency_Expenditure;


use Illuminate\Http\Request;

class OrganizationController extends Controller
{
  
    public function dashboard()
    {
        
    //   if($user=='organization'){
    //       $users = DB::connection('mysql_fc')->table('organizations')->where('api_account',$orgid)->where('username',$username)->get();
    //       /*if($users){
    //           return redirect()->route('organization-dashboard');
    //       }*/
    //   }
    //   elseif($user=='organization_user'){
    //       $users = DB::connection('mysql_fc')->table('organization_users')->where('api_account',$orgid)->where('username',$username)->get();
    //   }

       
       /*if(Auth::guard('organization')->check())
        {
            $id = Auth::guard('organization')->user()->organization_id;
            $api_account = Auth::guard('organization')->user()->api_account;
        }
        else if(Auth::guard('web')->check())
        {
            $id = Auth::guard('web')->user()->organization_id;
            $api_account = Auth::guard('web')->user()->api_account;
        }*/
        $id = Auth::user()->organization_id;
        $api_account = Auth::user()->api_account;
        
        

       //return $users;
       
        $today = date('Y-m-d');
            
        $query =Currency_Expenditure::where('shopid',$api_account)->whereDate('date_time', '>=', date('2020-09-01'));
        $smscount=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time', '>=', date('2020-09-01'));
        $smscountsent=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time', '>=', date('2020-09-01'));
        $smscountSuccess=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time', '>=', date('2020-09-01'));
        $smscountfailed=EloquentBuilder::to($query,request()->all())->count();
                
        $ivrcount = Ivr::count('organization_id');
        $total = $smscount+$ivrcount;

        $sms =  Currency_Expenditure::where('shopid',$api_account)->count();

        $query =Ivr::where('organization_id',$id);
        $ivr=EloquentBuilder::to($query,request()->all())->count();
                
        $borderColors = [ "#30ba35", "#f25961" ];
        $fillColors = ["#fdaf4b","#59d05d" ];
        $chart1 = new SMSChart;
        // $chart1->minimalist(true);
        $chart1->labels(['Sent','Success','Failed']);
        $sentsmscountSuccess=$smscountSuccess+$smscountsent;
        $chart1->dataset('SMS and IVR stats', 'doughnut',[$smscountsent,$sentsmscountSuccess,$smscountfailed])
        // ->color($borderColors)
        ->backgroundcolor($fillColors);
                            
        $query =Organization::where('organization_id',$id)->where('status','1');
        $shortcode=EloquentBuilder::to($query,request()->all())->count();

        $query =Organization::where('organization_id',$id)->where('status','0');
        $shortcodefailed=EloquentBuilder::to($query,request()->all())->count();
        
        $borderColors = [ "#30ba35", "#f25961" ];
        $fillColors = ["#59d05d","#f57a81" ];
        $chart2 = new SMSChart;
        $chart2->labels(['Sent','Failed']);
        $chart2->dataset('SHORTCODE stats', 'doughnut',[$shortcode,$shortcodefailed])
        ->backgroundcolor($fillColors);
                            
                            
                            
        $borderColors = [ "#30ba35", "#f25961" ];
        $fillColors = ["#59d05d","#f57a81" ];
        $chart3 = new SMSChart;
        // $chart->minimalist(true);
        $chart3->labels(['Sent','Failed']);
        $chart3->dataset('SMS and IVR stats', 'doughnut',[$ivr,$smscountfailed])
        // ->color($borderColors)
        ->backgroundcolor($fillColors);
                            
        $i_sms = Currency_Expenditure::where('sms_size',0)->count();
                    

        $today_sms = Currency_Expenditure::where('date_time','LIKE',$today."%")->count('shopid');
        
        $sms='SMS';
        
        
                    
        $account=Shop::where('ShopID',$api_account)->pluck('mpesa_account_name');
        $query =Currency_Expenditure::where('shopid',$api_account)->where('description','like',"%". $sms ."%")->where('sms','!=',"")->take(10);
        $trans=EloquentBuilder::to($query,request()->all())->get();
                
        $wallet = Wallet::where('shopid',$api_account)->pluck('amount');
                
   
    

                
       return view('fcviews.organization-dashboard',compact('wallet','smscount','smscountsent','smscountSuccess','smscountfailed','trans','chart1','chart2','chart3')); 
    }
    
    public function getdata()
    {
         $id = Auth::user()->organization_id;
        $api_account = Auth::user()->api_account;
        $barsmscount = Currency_Expenditure::where('shopid',$api_account)->count();
        $barsmscountsent = Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->count();
        $barsmscountSuccess = Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->count();
        $barsmscountfailed = Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->count();

        $janbarsmscountSuccess= Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereBetween('date_time',['2020-1-1','2020-1-31'])->count();
        $janbarsmscountfailed= Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereBetween('date_time',['2020-1-1','2020-1-31'])->count();
        $janbarsmscountSent= Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereBetween('date_time',['2020-1-1','2020-1-31'])->count();

        $febbarsmscountSuccess= Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereBetween('date_time',['2020-2-1','2020-2-31'])->count();
        $febbarsmscountSent= Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereBetween('date_time',['2020-2-1','2020-2-31'])->count();


        $successarray=array("jan"=>$janbarsmscountSuccess,"feb"=>$febbarsmscountSuccess,"mar"=>$marbarsmscountSuccess,"apr"=>$aprbarsmscountSuccess,"may"=>$maybarsmscountSuccess,"jun"=>$junbarsmscountSuccess,
        "jul"=>$julbarsmscountSuccess,"aug"=>$agubarsmscountSuccess,"sep"=>$sepbarsmscountSuccess,"oct"=>$otcbarsmscountSuccess,"nov"=>$novbarsmscountSuccess,"dec"=>$decbarsmscountSuccess);

        $failedarray=array("jan"=>$janbarsmscountfailed,"feb"=>$febbarsmscountfailed,"mar"=>$marbarsmscountfailed,"apr"=>$aprbarsmscountfailed,"may"=>$maybarsmscountfailed,"jun"=>$junbarsmscountfailed,
        "jul"=>$julbarsmscountfailed,"aug"=>$agubarsmscountfailed,"sep"=>$sepbarsmscountfailed,"oct"=>$otcbarsmscountfailed,"nov"=>$novbarsmscountfailed,"dec"=>$decbarsmscountfailed);

        $sentarray=array("jan"=>$janbarsmscountSent,"feb"=>$febbarsmscountSent,"mar"=>$marbarsmscountSent,"apr"=>$aprbarsmscountSent,"may"=>$maybarsmscountSent,"jun"=>$junbarsmscountSent,
        "jul"=>$julbarsmscountSent,"aug"=>$agubarsmscountSent,"sep"=>$sepbarsmscountSent,"oct"=>$otcbarsmscountSent,"nov"=>$novbarsmscountSent,"dec"=>$decbarsmscountSent);

        $alldata=array();
        $alldata['success']=$successarray;
        $alldata['failed']=$failedarray;
        $alldata['sent']=$sentarray;
        return response()->json($alldata);

    }
    
    //get all data
    public function getalldata()
    {
        $id = Auth::user()->organization_id;
        $api_account = Auth::user()->api_account;
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time',now()->subDays(6)->toDateString());
        $day1barsmscountSuccess=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time',now()->subDays(6)->toDateString());
        $day1barsmscountfailed=EloquentBuilder::to($query,request()->all())->count();

        $day1barsmscountSent= Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time',now()->subDays(6)->toDateString())->count();
                

        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time',now()->subDays(5)->toDateString());
        $day2barsmscountSuccess=EloquentBuilder::to($query,request()->all())->count();
            
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time',now()->subDays(5)->toDateString());
        $day2barsmscountSent=EloquentBuilder::to($query,request()->all())->count();
            
            
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time',now()->subDays(5)->toDateString());
        $day2barsmscountfailed=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time',now()->subDays(4)->toDateString());
        $day3barsmscountSuccess=EloquentBuilder::to($query,request()->all())->count();

                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time',now()->subDays(4)->toDateString());
        $day3barsmscountSent=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time',now()->subDays(4)->toDateString());
        $day3barsmscountfailed=EloquentBuilder::to($query,request()->all())->count();
            
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time',now()->subDays(3)->toDateString());
        $day4barsmscountSuccess=EloquentBuilder::to($query,request()->all())->count();
            
            
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time',now()->subDays(3)->toDateString());
        $day4barsmscountSent=EloquentBuilder::to($query,request()->all())->count();
            

        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time',now()->subDays(3)->toDateString());
        $day4barsmscountfailed=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time',now()->subDays(2)->toDateString());
        $day5barsmscountSuccess=EloquentBuilder::to($query,request()->all())->count();
                
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time',now()->subDays(2)->toDateString());
        $day5barsmscountSent=EloquentBuilder::to($query,request()->all())->count();

        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time',now()->subDays(2)->toDateString());
        $day5barsmscountfailed=EloquentBuilder::to($query,request()->all())->count();

        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time',now()->subDays(1)->toDateString());
        $day6barsmscountSuccess=EloquentBuilder::to($query,request()->all())->count();

        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time',now()->subDays(1)->toDateString());
        $day6barsmscountSent=EloquentBuilder::to($query,request()->all())->count();

        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time',now()->subDays(1)->toDateString());
        $day6barsmscountfailed=EloquentBuilder::to($query,request()->all())->count();
            
        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Success')->whereDate('date_time',now()->toDateString());
        $day7barsmscountSuccess=EloquentBuilder::to($query,request()->all())->count();

        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','Sent')->whereDate('date_time',now()->toDateString());
        $day7barsmscountSent=EloquentBuilder::to($query,request()->all())->count();


        $query =Currency_Expenditure::where('shopid',$api_account)->where('status','failed')->whereDate('date_time',now()->toDateString());
        $day7barsmscountfailed=EloquentBuilder::to($query,request()->all())->count();

                
        $successarray=array("day7"=>$day1barsmscountSuccess,"day6"=>$day2barsmscountSuccess,"day5"=>$day3barsmscountSuccess,"day4"=>$day4barsmscountSuccess,"day3"=>$day5barsmscountSuccess,"day2"=>$day6barsmscountSuccess,
        "day1"=>$day7barsmscountSuccess);

        $failedarray=array("day7"=>$day1barsmscountfailed,"day6"=>$day2barsmscountfailed,"day5"=>$day3barsmscountfailed,"day4"=>$day4barsmscountfailed,"day3"=>$day5barsmscountfailed,"day2"=>$day6barsmscountfailed,
        "day1"=>$day7barsmscountfailed);

        $sentarray=array("day7"=>$day1barsmscountSent,"day6"=>$day2barsmscountSent,"day5"=>$day3barsmscountSent,"day4"=>$day4barsmscountSent,"day3"=>$day5barsmscountSent,"day2"=>$day6barsmscountSent,
        "day1"=>$day7barsmscountSent);
            
        $alldata=array();
        $alldata['success']=$successarray;
        $alldata['failed']=$failedarray;
        $alldata['sent']=$sentarray;
        return $alldata;
    }



    
    //get shortcode all data
    public function getshortcodealldata()
    {
        $id = Auth::user()->organization_id;
        $api_account = Auth::user()->api_account;
        //     ///////////////////////////////////      SHORTCODE          /////////////////////////////////////
        
        $day1barSHORTCODEcountSuccess= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(6)->toDateString())->count();
        $day1barSHORTCODEcountfailed= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(6)->toDateString())->count();

        $day2barSHORTCODEcountsuccess= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(5)->toDateString())->count();
        $day2barSHORTCODEcountfailed= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(5)->toDateString())->count();

        $day3barSHORTCODEcountSuccess= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(4)->toDateString())->count();
        $day3barSHORTCODEcountfailed= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(4)->toDateString())->count();

        $day4barSHORTCODEcountSuccess= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(3)->toDateString())->count();
        $day4barSHORTCODEcountfailed= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(3)->toDateString())->count();

        $day5barSHORTCODEcountSuccess= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(2)->toDateString())->count();
        $day5barSHORTCODEcountfailed= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(2)->toDateString())->count();

        $day6barSHORTCODEcountSuccess= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(1)->toDateString())->count();
        $day6barSHORTCODEcountfailed= Incoming::where('site',$id)->whereDate('date_responded_to',now()->subDays(1)->toDateString())->count();

        $query =Incoming::where('site',$id)->whereDate('date_responded_to',now()->toDateString());
        $day7barSHORTCODEcountSuccess=EloquentBuilder::to($query,request()->all())->count();


        $query =Incoming::where('site',$id)->whereDate('date_responded_to',now()->toDateString());
        $day7barSHORTCODEcountfailed=EloquentBuilder::to($query,request()->all())->count();

        
        $successSHORTCODEarray=array("day1"=>$day1barSHORTCODEcountSuccess,"day2"=>$day2barSHORTCODEcountsuccess,"day3"=>$day3barSHORTCODEcountfailed,"day4"=>$day4barSHORTCODEcountSuccess,"day5"=>$day5barSHORTCODEcountSuccess,"day6"=>$day6barSHORTCODEcountSuccess,
        "day7"=>$day7barSHORTCODEcountSuccess);

        $failedSHORTCODEarray=array("day1"=>$day1barSHORTCODEcountfailed,"day2"=>$day2barSHORTCODEcountfailed,"day3"=>$day3barSHORTCODEcountfailed,"day4"=>$day4barSHORTCODEcountfailed,"day5"=>$day5barSHORTCODEcountfailed,"day6"=>$day6barSHORTCODEcountfailed,
        "day7"=>$day7barSHORTCODEcountfailed);

        $SHORTCODEalldata=array();
        $SHORTCODEalldata['success']=$successSHORTCODEarray;
        $SHORTCODEalldata['failed']=$failedSHORTCODEarray;
        return $SHORTCODEalldata;
    }
    //get ivralldata
    public function getivralldata()
    {
        $id = Auth::user()->organization_id;
        $api_account = Auth::user()->api_account;
        ///////////////////////   IVR          ///////////////////////////////////////////////////////
        $day1barivrcountSuccess= Ivr::where('organization_id',$id)->where('status','1')->whereDate('updated_at',now()->subDays(6)->toDateString())->count();
        $day1barivrcountfailed= Ivr::where('organization_id',$id)->where('status','2')->whereDate('updated_at',now()->subDays(6)->toDateString())->count();


        $day2barivrcountsuccess= Ivr::where('organization_id',$id)->where('status','2')->whereDate('updated_at',now()->subDays(5)->toDateString())->count();
        $day2barivrcountfailed= Ivr::where('organization_id',$id)->where('status','2')->whereDate('updated_at',now()->subDays(5)->toDateString())->count();


        $day3barivrcountfailed= Ivr::where('organization_id',$id)->where('status','2')->whereDate('updated_at',now()->subDays(4)->toDateString())->count();

        $day4barivrcountSuccess= Ivr::where('organization_id',$id)->where('status','1')->whereDate('updated_at',now()->subDays(3)->toDateString())->count();
        $day4barivrcountfailed= Ivr::where('organization_id',$id)->where('status','2')->whereDate('updated_at',now()->subDays(3)->toDateString())->count();

        $day5barivrcountSuccess= Ivr::where('organization_id',$id)->where('status','1')->whereDate('updated_at',now()->subDays(2)->toDateString())->count();
        $day5barivrcountfailed= Ivr::where('organization_id',$id)->where('status','2')->whereDate('updated_at',now()->subDays(2)->toDateString())->count();

        $query =Ivr::where('organization_id',$id)->where('status','1')->whereDate('updated_at',now()->subDays(1)->toDateString());
        $day6barivrcountSuccess=EloquentBuilder::to($query,request()->all())->count();
            
            
        $query =Ivr::where('organization_id',$id)->where('status','2')->whereDate('updated_at',now()->subDays(1)->toDateString());
        $day6barivrcountfailed=EloquentBuilder::to($query,request()->all())->count();

        $day7barivrcountSuccess= Ivr::where('organization_id',$id)->where('status','>','0')->whereDate('updated_at',now()->toDateString())->count();
        $day7barivrcountfailed= Ivr::where('organization_id',$id)->where('status','0')->whereDate('updated_at',now()->toDateString())->count();

        $successivrarray=array("day1"=>$day1barivrcountSuccess,"day2"=>$day2barivrcountsuccess,"day3"=>$day3barivrcountfailed,"day4"=>$day4barivrcountSuccess,"day5"=>$day5barivrcountSuccess,"day6"=>$day6barivrcountSuccess,
        "day7"=>$day7barivrcountSuccess);

        $failedivrarray=array("day1"=>$day1barivrcountfailed,"day2"=>$day2barivrcountfailed,"day3"=>$day5barivrcountfailed,"day4"=>$day4barivrcountfailed,"day5"=>$day5barivrcountfailed,"day6"=>$day6barivrcountfailed,
        "day7"=>$day7barivrcountfailed);

        $ivralldata=array();
        $ivralldata['success']=$successivrarray;
        $ivralldata['failed']=$failedivrarray;
        return $ivralldata;
    }
    public function index()
    {

        $exist = Organization::pluck('api_account');
        $organizations = Shop::whereNotIn('ShopID',$exist)->get();
        return view('fcviews.organization.index',compact('organizations'));
    }
    //store
    public function store(Request $request)
    {
        request()->validate([
            'name'=> 'required',
            'email' => 'required',
            'username' => 'required',
            'password' => 'required|confirmed',
            'password_confirmation' => 'required'
     
        ]);
        $organization = new Organization();
        $organization->name = $request->get('name');
        $organization->api_account = $request->get('id');
        $organization->email = $request->get('email');
        $organization->username = $request->get('username');
        $organization->short_code = $request->get('shortcode');
        $organization->password = Hash::make($request->password);
        
        // log data
        $orgLog = new AuditLog();
        $orgLog->audit_module = "Organization";
        $orgLog->audit_activity = "Organization ".$organization->username ."added by Admin ID# " .Auth::id();
        
        $orgLog->user_category = "Admin";
        $orgLog->user_id = Auth::id();
        $orgLog->save();
        $organization->save();
        //create accounts user
        $cust_id = $organization['organization_id'];
        $newuser = new User();
        $newuser->username = $request->get('username');
        $newuser->cust_id = $cust_id;
        $newuser->shop_id = $request->get('id');
        $newuser->email = $request->get('email');
        $newuser->user_type = 'organization';
        $newuser->password = Hash::make($request->password);
        $newuser->save();
    }
    //update
    public function update(Request $request)
    {
        request()->validate([
            'name'=> 'required',
            'api_account' => 'required',
            'email' => 'required',
            'username' => 'required',
            'password' => 'confirmed',
     
        ]);
        $organizationdets = Organization::findOrFail($request->id);
        $organization = Organization::findOrFail($request->id);
        $organization->name = $request->get('name');
        $organization->api_account = $request->get('api_account');
        $organization->email = $request->get('email');
        $organization->username = $request->get('username');
        $organization->password = Hash::make($request->password);
     
        // log data
        $orgLog = new AuditLog();
        $orgLog->audit_module = "Organization";
        $orgLog->audit_activity = "Organization ".$organization->username ."updated from ".$organizationdets." to ".$organization." by Admin ID# " .Auth::guard('admin')->user()->admin_id;
        
        $orgLog->user_category = "Admin";
        $orgLog->user_id = Auth::guard('admin')->user()->admin_id;
        
        $orgLog->save();
        $organization->save();
    }
    public function delete($id)
    {
        $organization = organization::where('organization_id',$id)->get();
        //set delete
        $deleteorganization = Organization::findOrFail($id);
        //set logging
        $organizationLog = new AuditLog();
        $organizationLog->audit_module = "Organization";
        $organizationLog->audit_activity = "Organization with details ".$organization." deleted by Admin ID# " .Auth::guard('admin')->user()->admin_id;
        
        $organizationLog->user_category = "Admin";
        $organizationLog->user_id = Auth::guard('admin')->user()->admin_id;
        $organizationLog->save();
        $deleteorganization->delete();
    }
}
