<?php

namespace App\Http\Controllers\BundlesControllers;

use App\Http\Controllers\Controller;
Use Maatwebsite\Excel\Facades\Excel;
use App\Models\atmodels\Airtime_contact;
use App\Models\atmodels\Airtime_group;
use App\Models\atmodels\Currency_credit;
use App\Models\bmmodels\CustomerClient;
use App\Models\fcmodels\Contact;
use App\Models\atmodels\Airtime_Contacts_Group_Association;
use App\Models\atmodels\DataBundlesCredits;
use App\Models\atmodels\IMELogs;
use App\Models\bundles\Data_Bundles_TopUp;

use Illuminate\Http\Request;
use App\Imports\BundlesImports\BundlesContactsImport;

use Auth;
use Exception;
use Hash;
use Log;
use DB;
class BundlesContactController extends Controller
{
    //return contacts view
    public function index()
    {
        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'];
            $shop_id=Auth::user()->shop_id;            
            $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
            $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount');
            $databundlestopup = Data_Bundles_TopUp::where('ShopID',$shop_id)->get();           

            $contacts = Airtime_contact::where('ShopID',$shop_id)->with('contactGroup')->get();           
            $groups = Airtime_group::where('ShopID',$shop_id)->get();
           
            return view('bundleviews.contacts.index', compact('databundlestopup','datawallet','contacts','groups','wallet'));
        }
    }
     //return contacts view
     public function index1()
     {
        $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
            $shop_id=Auth::user()->shop_id;            
            $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
            $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount');
            $databundlestopup = Data_Bundles_TopUp::where('ShopID',$shop_id)->get();           

            $contacts = Airtime_contact::where('ShopID',$shop_id)->where('bundle',1)->with('groupAssoContacts')->with('contactGroup')->take('50')->orderBy('contact_id','DESC')->get();           
            $groups = Airtime_group::where('ShopID',$shop_id)->get();
           
            return view('bundleviews.contacts.index1', compact('databundlestopup','datawallet','contacts','groups','wallet'));
         } 
     
    //  public function index1()
    //  {
    //      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'];          
    //          $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');          
    //          $groups=Airtime_group::where('ShopID',$shop_id)->get();
    //          return view('bundleviews.contacts.index1', compact('wallet','groups'));
    //      } 
    //  }
    
      //return groups
      public function getcontactsgroups1()
      {
          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_contact::with(['assogroupContacts.groupContacts'])->where('ShopID',$shop_id)->get();
              return $groups;    
          }
      }


     //return index1vuedata
      //return groups
    public function getGroups()
    {
        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_contact::with(['assogroupContacts.groupContacts'])->where('ShopID',$shop_id)->get();
            return $groups;    
        }



        // 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();
        //     return $groups;
        // }
    }

    //get contact data for edit
    public function getContactData($id){
        $contacts = Airtime_contact::where('contact_id',$id)->get();
        return response()->json($contacts);
    }


  //return groups
  public function getContacts()
  {
      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'];
          $contacts = Airtime_contact::where('ShopID',$shop_id)->where('bundle',1)->with('groupAssoContacts')->with('contactGroup')->get();  
          return $contacts;
      }
  }

    //return groups
    public function oldGet()
    {
        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_contact::where('ShopID',$shop_id)->get();
            return $groups;
        }
    }
    
    //get all contacts
    
    public function get(){
        $newdata=array();
        if(Auth::user()->user_type == 'organization_user') 
        {
             $shop_id=Auth::user()->shop_id;
             $customer_id=Auth::user()->userShopUser['customer_id'];
             $contacts = Airtime_contact::where('ShopID',$shop_id)->get();
            
            if(Auth::user()->cust_id){
                $c=array();
                 $fcuser_id = Auth::user()->organization_id;
                 $contacts=Contact::where('organization_id',$fcuser_id)->get(['phone AS contact','name AS fname','contact_id'])->toArray();
       
                foreach($contacts as $a){
                    $b['contact']="+254".substr($a['contact'],-9);
                    $b['fname']=$a['fname'];
                    $b['contact_id']=$a['contact_id'];
                    array_push($c,$b);
                
                }
            }
            
            if(Auth::user()->bulk_cust_id){
                $id=Auth::user()->bulk_cust_id;
                $data = CustomerClient::where('customer_cust_id',$id)->where('cust_client_status',1)->get(['cust_client_phone AS contact','cust_client_fullname AS fname','cust_client_id AS contact_id'])->toArray();
               
                foreach($data as $a){
                    $mdata['contact']="+254".$a['contact'];
                    $mdata['fname']=$a['fname'];
                    $mdata['contact_id']=$a['contact_id'];
                    array_push($c,$mdata);
                
                }
            }
            
           $newdata=array_merge($contacts,$c);
            
            
           
        }
        else if(Auth::user()->user_type == 'organization'){
            
             $shop_id=Auth::user()->shop_id;
             $customer_id=Auth::user()->userShopUser['customer_id'];
             $contacts = Airtime_contact::where('ShopID',$shop_id)->get();
             
             
        }
        
        return $newdata;
    }

    
   //return Contacts groups
   public function getContactGroups($id)
   {
       $m=array_slice(explode(',',$id),0,-1);
      
       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::wherein('group_id',$m)->get();
          // $groups = Airtime_contact::where('ShopID',$shop_id)->get();
           return $groups;
       }
   }

    //
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
        ]);
        
        $number="";

        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);
        }
        
        $no = $request->phone;
        $ime=$request->ime;
        //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, 1)=="7")){
                    
            if(substr($no, 0, 4)=="+254"){
                $number="+254" . substr($no, -9);
            }
            
            elseif(substr($no, 0, 3)=="254"){
                $number="+254" . substr($no, -9);  
            }
            elseif(substr($no, 0, 1)=="0"){
                $number="+254" . substr($no, -9); 
            }
            elseif(substr($no, 0, 1)=="7"){
                $number="+2547" . substr($no, -9); 
            }
        }
        //check duplicate
        $check=Airtime_contact::where('contact',$number)->where('ShopID',$shop_id)->get();
        if($check->count())
        {
            $phones_arr=$check[0]->contact;
        
         //   return response()->json(["errors"=>["phone"=>["Phone number(s) already added ".json_encode($phones_arr)]]],422);
        }
   
      //check duplicate
      $check=Airtime_contact::where('ime',$ime)->where('ShopID',$shop_id)->get();
      if($check->count())
      {
          $phones_arr=$check[0]->contact;
      
          return response()->json(["errors"=>["ime"=>["IMEI number(s) already added for this phone Number".json_encode($phones_arr)]]],422);
      }


         

        $data = new Airtime_contact();
        $data->fname = $request->name;
        $data->contact = $number;
        $data->customer_id = $customer_id;
        $data->group_id = $request->group_id['group_id'];  
        $data->bundle = '1';
        $data->group_id = $request->group_id['group_id'];
        $data->ime = $request->ime;
        $data->ShopID = $shop_id;
      // return $data->group_id;
        // if($request->group_id)
        // {
        //     //get group ids into array
        //     $groups = [];
        //     foreach($request->group_id as $group)
        //     {
        //         array_push($groups,(int)$group['group_id']);
        //     }
        //     $data->group_id = json_encode($groups);
        // }
        $data->save();



        // foreach ($request->group_id as $item) {
        //     $groupasso = new Airtime_Contacts_Group_Association();
        //    // $lastInsertedId = Airtime_contact::getPdo()->lastInsertId();
        //    // $lastInsertID = DB::table('Airtime_contact')->get();
        //    // dd($lastInsertID);
        //     $groupasso->group_id = $item['group_id'];
        //     $groupasso->contact_id = '15810';
        //     $groupasso->save ();  
       
   
        // }


    }

    //import contacts
    public function import(Request $request) 
    {

        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');
        }


         request()->validate([
            'file' => 'required|max:2000'
         ],
         [
             'file.required' => 'Please select a file first',
             'file.max' => 'Please select a file with size under 2MBs',
         ]);
        $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 BundlesContactsImport($customer_id,$request->group), $path);
       
            return back(); 
        }
        else{
           return redirect()->back()->with('failure', 'Please select excel file!');
        }
    }
    //edit grp
    public function update(Request $request)
    {
        $request->validate([
            'name' => '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);
        }
        //get group ids into array
        $groups = [];
        // return $request->group_id; 
        // foreach($request->group_names as $group)
        //  {
        //    array_push($groups,(int)$group['group_id']);
        //  }
         
        $data = Airtime_contact::findOrFail($request->contact_id);

        
        $data->fname = $request->name;
        $data->contact =  $request->phone;
        $data->customer_id = $customer_id;
        $data->group_id = $request->group_id['group_id'];  
        $data->bundle = '1';
        $data->ime = $request->ime;
        $data->ShopID = $shop_id;




        $data->save ();



        // $activitylog = new IMELogs();
        // $activitylog->ShopID = $shop_id;
        // $activitylog->audit_module = Auth::user()->user_type;
        
        // $activitylog->user_id = $customer_id;
        // $activitylog->activity_log = 'Updated IMEI';
        // $activitylog->current_messages= $request->current_messages;
        // $activitylog->previous_messages = $request->ime;
    
        // $activitylog->save (); 




    }

    //delete group
    public function destroy($id)
    {
        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_contact::findOrFail($id);
        $data->delete();
        return redirect()->back()->with('success', 'Deleted succesfully');
    }
    //delete all contacts
    public function destroyAllContacts()
    {
        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_contact::where('ShopID',$shop_id)->delete();
        return redirect()->back()->with('success', 'Deleted succesfully');
        
    }
    //delete selected
    public function destroySelectedContacts(Request $request)
    {
        $id = $request->contact;
      
        if(empty($id))
        {
            return redirect()->back()->with('failure', 'Select atleast one contact');
        }
        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_contact::where('ShopID',$shop_id)->whereIn('contact_id',$id)->delete();
        return redirect()->back()->with('success', 'Deleted succesfully');
    }

    //deleteselectedcontact
    public function delselectedContacts($id){
        $contactsids=explode(',',$id);
        
        if(empty($contactsids))
        {
            return redirect()->back()->with('failure', 'Select atleast one contact');
        }
        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_contact::where('ShopID',$shop_id)->whereIn('contact_id',$contactsids)->delete();
        $status="";
        if($data){
            return $status="success";
        }
        else{
            $status="failed";   
        }
        return $status;

    }
}
