<?php

namespace App\Http\Controllers\BundlesControllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use Hash;
use Log;
use DB;
use Carbon\Carbon;

use App\Models\atmodels\Airtime_customer;
use App\Models\atmodels\Airtime_contact; //contatcs
use App\Models\atmodels\Airtime_sending_record; //expenditure
use App\Models\atmodels\Currency_credit; //balance
use App\Models\atmodels\CreditTopup; //topups
use App\Models\atmodels\Airtime_group;
use App\Models\bundles\Data_Bundles_TopUp;
use App\Models\atmodels\User;
use App\Models\UserDash;
use App\Models\atmodels\DataBundlesCredits;
use EloquentBuilder;
use App\Charts\BundlesCharts\BundlesChart;
use App\Models\fcmodels\Currency_Expenditure;
class BundlesUserController extends Controller
{
    public function dashboard()
    {
        //
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
            $groups=Airtime_group::where('ShopID',$shop_id)->get();
            $topups=CreditTopup::where('shop_id',$shop_id)->sum('credit_amount');
            $balance=Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
            $expenditure=Airtime_sending_record::where('customer_id',$customer_id)->sum('airtime_sent');
            $contacts = Airtime_contact::where('ShopID',$shop_id)->with('contactGroup')->get();
            $search ='Dear Customer you have received';
            //recent topups
            $expenditure_recent=Currency_Expenditure::where('sms','LIKE', '%'.$search.'%')->latest('date_time')->take(2)->get();
            //recent my account tpups
            $topups_recent=CreditTopup::where('shop_id',$shop_id)->latest('topup_time')->take(2)->get();
            
              $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');   
              $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount');  
           
           
           
           
           
                      
             // $query =Data_Bundles_TopUp::where('shopid',$shop_id);
            //  $bundlescountall=EloquentBuilder::to($query,request()->all())->sum('qnty');
                      
              $query =Data_Bundles_TopUp::where('shopid',$shop_id)->where('unit','MB');
             // $query = Data_Bundles_TopUp::where('shopid', $shop_id)->where('unit', 'MB')->sum('qnty');
              $bundlesinMBs=EloquentBuilder::to($query,request()->all())->sum('qnty');
             // $sum = array_sum($numbers);
              $query =Data_Bundles_TopUp::where('shopid',$shop_id)->where('unit','GB');
              $bundlesinGBs=EloquentBuilder::to($query,request()->all())->sum('qnty');
          
              $bundlescountall=($bundlesinMBs/1000)+$bundlesinGBs;
                      
              $borderColors = [ "#acacac", "#f25961" ];
              $fillColors = ["#f27200","#59d05d" ];
              $chart1 = new BundlesChart;
              // $chart1->minimalist(true);
              $chart1->labels(['Total Bundles in GBs','Total Bundles in MBs']);
              $chart1->dataset('Warranty Statistics', 'bar',[$bundlesinGBs,$bundlesinMBs])
              // ->color($borderColors)
              ->backgroundcolor($fillColors);
         //   return   Carbon::parse($bundlesinMBs->created_at)->format('l');                         

              $visitor = Data_Bundles_TopUp::select(

                  DB::raw("year(created_at) as year"),

                  DB::raw("SUM(qnty) as total_click"),

                  DB::raw("SUM(created_at) as total_viewer"))

              ->get();


  $result[] = ['Year','Data Bundles Topup','Period'];

  foreach ($visitor as $key => $value) {

      $result[++$key] = [$value->year, (int)$value->total_click, (int)$value->total_viewer];

  }

  $ttr=json_encode($result);
 
           
              return view('bundleviews.user-dashboard',compact('visitor','ttr','chart1','bundlescountall','bundlesinMBs','bundlesinGBs','datawallet','wallet','contacts','expenditure','balance','topups','groups','expenditure_recent','topups_recent'))->with('visitor',json_encode($result));
        }
        else{
            return abort('401');
        }
      
    }









    
   //return Airtime_customer view
   public function index()
   {

       if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
       {
      $usersd = Auth::user()->user_type;
           $shop_id=Auth::user()->shop_id;
         
           $customer_id=Auth::user()->userShopUser['customer_id'];
           $company = Airtime_customer::where('customer_id',$customer_id)->pluck("company");
           $userShopCustomer= Auth::user()->userShopCustomer['Name'];
           $airtimecustomeruser = Airtime_customer::where('company',$userShopCustomer)->get();
           $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
           $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
           return view('bundleviews.bundlesuser.index',compact('airtimecustomeruser','wallet','datawallet'));
       }
       else{
           return abort(401);
       }
   }

   

   //return Airtime_customer view
   public function indexUser()
   {

       if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
       {
      $usersd = Auth::user()->user_type;
           $shop_id=Auth::user()->shop_id;     
           $customer_id=Auth::user()->userShopUser['customer_id'];
           $company = Airtime_customer::where('customer_id',$customer_id)->pluck("company");
           $userShopCustomer= Auth::user()->userShopCustomer['Name'];
           $customeruser = UserDash::where('shop_id',$shop_id)->get();
           $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
           $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
           return view('bundleviews.bundlesuser.user',compact('customeruser','wallet','datawallet'));
       }
       else{
           return abort(401);
       }
   }




   public function changepasswordarea($email)
   {

       if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
       {
      $usersd = Auth::user()->user_type;
           $shop_id=Auth::user()->shop_id;
         
   
          //return $email;
           $customer_id=Auth::user()->userShopUser['customer_id'];
           $company = Airtime_customer::where('customer_id',$customer_id)->pluck("company");
           $userShopCustomer= Auth::user()->userShopCustomer['Name'];
          // $airtimecustomeruser = User::where('email',$id)->get();
         $airtimecustomeruser = User::All();
      foreach($airtimecustomeruser as $airtimecustomer){
        //   $airtimecustomer = User::where('email', $email)->get();
        $userid= $airtimecustomer->id;
        $airtimecustomer= $airtimecustomer->email;
      }
           $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
           $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
           return view('bundleviews.bundlesuser.changepasswordarea',compact('userid','airtimecustomer','wallet','datawallet'));
       }
       else{
           return abort(401);
       }
   }
//store
public function storeCustomerUser(Request $request)
{
     if(Auth::check())
    {
        $id = Auth::user()->organization_id;
        $api_account = Auth::user()->api_account;
    }
    else{
        return abort('401');
    } 
    // $request->validate([
    
    //     'fname' => 'required',

    //     'fname' => 'required|min:3|max:50',
    //     'email' => 'email',
    //     'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
    //     'password_confirmation' => 'min:6'      
    //         ]);
        

            $userdata = new User();
            $userdata->username = $request->username;
            $userdata->password = Hash::make($request->password);
            $userdata->shop_id = Auth::user()->shop_id;
            $userdata->user_type = 'organization_user';
            $userdata->email = $request->email;
            $userdata->remember_token = '';
            
            $userdata->save ();

//             return response()->json($userdata);
// exit();
            $username=$request->username;
            $email=$request->email;
      //check duplicate username
      $check=Airtime_customer::where('username',$username)->get();
      if($check->count())
      {
          $phones_arr=$check[0]->contact;
      
          return response()->json(["errors"=>["username"=>["username already added for this user".json_encode($phones_arr)]]],422);
      }

            //check duplicate Email
            $check=Airtime_customer::where('email',$email)->get();
            if($check->count())
            {
                $phones_arr=$check[0]->contact;
            
                return response()->json(["errors"=>["email"=>["Email already added for this user".json_encode($email)]]],422);
            }


   
        



    $userShopCustomer= Auth::user()->userShopCustomer['Name'];
    
    $data = new Airtime_customer();
    $data->fname = $request->fname;
    $data->lname = $request->lname;
    $data->username = $request->username;
    $data->pwd_xdm_ps = Hash::make($request->password);
    $data->phone = $request->phone;
    $data->email = $request->email;
    $data->user_type = 'normal';
    $data->status = 'Active';
    $data->company =$userShopCustomer;
    
    $data->save ();

    

    //log
    // $adminLog = new AuditLog();
    // $adminLog->audit_module = "Organization";
    // $adminLog->audit_activity = "Organization user ".$request->username ." added by Admin ID# " .$id;
   
    // $adminLog->user_category = "Admin";
    // $adminLog->user_id = $id;
    // ;
    // $adminLog->save();
    
    return response()->json($data);
}

//edit updatepasswordconfirm
public function updatepasswordconfirm(Request $request)
{
    Log::info($request);
     $request->validate([ 
        'username' => 'required',
         'email' => 'email',
         'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
         'password_confirmation' => 'min:6'       
            ]);


    if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
    {
        $shop_id=Auth::user()->shop_id;
        $customer_id=Auth::user()->userShopUser['customer_id'];
    }
    else{
        return abort(401);
    }

    $data = User::findOrFail($request->id);
    $data->username = $request->username;
    $data->password = Hash::make($request->password);
    $data->save ();

   return response()->json($data);
}


//edit updatepasswordconfirm
public function updateCustomerUser(Request $request)
{
  
    $request->validate([
        'fname' => 'required',
    ]);
    if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
    {
        $shop_id=Auth::user()->shop_id;
        $customer_id=Auth::user()->userShopUser['customer_id'];
    }
    else{
        return abort(401);
    }

    $data = Airtime_customer::findOrFail($request->customer_id);
    $data->fname = $request->fname;
    $data->lname = $request->lname;
    $data->username = $request->username;
    $data->pwd_xdm_ps = Hash::make($request->password);
    $data->phone = $request->phone;
    $data->email = $request->email;
  //  $data->user_type = 'normal';
  //  $data->status = 'Active';
   // $data->company =$userShopCustomer;
    
    $data->save ();
  
    //$data = User::where('email',$request->email)->get();
    $userdata->username = $request->username;
    $userdata->password = Hash::make($request->password);
    $ppd=Hash::make($request->password);

    $affected = DB::table('users')
            ->where('email', ".$userdata->password.")
            ->update(['password' => ".$ppd."]);
  //  $userdata->shop_id = Auth::user()->shop_id;
   // $userdata->user_type = 'organization_user';
   // $userdata->email = $request->email;
   // $userdata->remember_token = '';
    
    $userdata->save ();
   return response()->json($data);
}


//Update Customer User Password
public function updateCustomerp(Request $request)
{
  foreach($request as $requests){
    Log::info('ID: '.$request->userid);

    DB::table('users') ->where('id',$request->userid)->update(['password' =>$request->password]);

    DB::table('users')
    ->where('id', $request->userid)  // find your user by their email
    ->limit(1)  // optional - to ensure only one record is updated.
    ->update(array('password' => $request->password));  // update the record in the DB. 
  //  Log::info('password: ',$request->password);

    //Log::info('password: '.$request->password);
    // $data = User::where('id',$request->userid);
    // $data->password =  Hash::make($request->password);
    // $data->save ();
   // return response()->json($data);
   return redirect()->route('home')
   ->withInput()
   ->with('success', 'Record Updated');
    //return redirect()->route('home');
  }
}


//Update Customer User Password
public function updateCustomerUserPassword(Request $request)
{
  
    $request->validate([
        'fname' => 'required',
    ]);
    if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
    {
        $shop_id=Auth::user()->shop_id;
        $customer_id=Auth::user()->userShopUser['customer_id'];
    }
    else{
        return abort(401);
    }

    $data = Airtime_customer::findOrFail($request->customer_id);
    $data = Airtime_customer::findOrFail($request->customer_id);
    $data->pwd_xdm_ps =  Hash::make($request->password);

    $data->save ();
}

 //delete
 public function destroy(Request $request,$id)
  {

    //find user details to delete
    $admin = Airtime_customer::where('customer_id',$id)->get();
    //set delete
    $deleteAirtimecustomer = Airtime_customer::findOrFail($id);
    $deleteAirtimecustomer->delete();
    
    
    
     $data = User::findOrFail($id);
        $data->delete();
    //set logging
   
    // $adminLog = new AuditLog();
    // $adminLog->audit_module = "Organization";
    // $adminLog->audit_activity = "Organization of details: ".$admin." deleted by Admin ID#" .$id;
    
    // $adminLog->user_category = "organization";
    // $adminLog->user_id = $id; 
    // $adminLog->save();
}

//api customer
public function storeCustomer(Request $request)
{
    return 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrr';
    return response()->json($request);
     
    $userdata = new User();
    $userdata->username = $request->username;
    $userdata->pwd_xdm_ps = Hash::make($request->password);
    $userdata->shop_id = $request->shop_id;
    $userdata->user_type = 'organization';
    $userdata->email = $request->email;
    
    $userdata->save ();    

}


public function datahistory(Request $request)
{
   

}



}
