<?php

namespace App\Http\Controllers\BMControllers;

use Illuminate\Http\Request;
use Auth;
use Hash;
use App\Models\bmmodels\Customer;
use App\Models\bmmodels\CustomerUser;
use App\Models\bmmodels\CustomerClient;
use App\Models\bmmodels\CustomerGroup;
use App\Models\bmmodels\CustomerWallet;
use App\Models\bmmodels\CustomerPasswordReset;
use App\Models\bmmodels\ClientBatch;
use App\Models\bmmodels\AuditLog;
use Exception;
use App\Exports\CustomerExport;
use EloquentBuilder;
use App\Libs\Mobisky;


class CustomerController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    //export customers
    public function customerExport(Request $request)
    {
        return new CustomerExport($request);
    }
    public function index(Request $request)
    {
        if(Auth::user()->user_type == 'admin')
        {
            try
            {
                //fetch all customersEloquentBuilder::to($query, $request->all())->get();
                $customers = EloquentBuilder::to(Customer::class, $request->all())->get();
                return view('bmviews.customers.index', compact('customers'));
            }
            catch(Exception $e)
            {
                abort(500, $e->getMessage()); 
            }
        }
        else
        {
            return redirect('/admin/login')->with('failure','Access Denied! Lo in to continue');
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        if(Auth::user()->user_type == 'admin')
        {
            return view('bmviews.customers.create');
        }
        else
        {
            return redirect('/admin/login')->with('failure','Access Denied! Login to continue');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    //vue add customer
    public function addCustomer(Request $request)
    {
        $this->validate($request, [
            'name'=> 'required',
            'primary' => 'required',
            'secondary' => 'required',
            'email' => 'required',
            'username' => 'required'
        ]);
        
        //get username and password for mobisky sms api
         $mobiskysms=app('App\Http\Controllers\BMControllers\ServiceCredentialController')->mobiskySettings();
                
        //read the values from the settings after db mapping
         $sms_username=\Config::get('outpost.sms_username');
         $sms_password=\Config::get('outpost.sms_password'); 

         $smsobject=new Mobisky('demo1','mob1d3m01');
         $otp_code=strtoupper(substr(Hash::make($smsobject->codeGenerator(6)),4,6));
         $otp=$otp_code."0";
        
                     
        //$customer = new Customer();
        $customer['cust_name'] = $request->name;
        $customer['cust_primary_contact_type'] = $request->primary;
        $customer['cust_sec_contact'] = $request->secondary;
        $customer['email'] = $request->email;
        $customer['cust_username'] = "BMP.".$request->username;
        //default password is the username...USER be advised to change
        $customer['password']=Hash::make($otp); //Hash::make(substr(Hash::make($request->username),-8));
        $customer['cust_status'] = 1;
        
        //append once emails work
        $customer['cust_first_time'] = 1;
        
        $customer['role_id'] = 2;

         // log data
        $customerLog = new AuditLog();
        $customerLog->audit_module = "Customer";
        $customerLog->audit_activity = "Customer ".$customer['cust_username'] ."added by Admin ID# " .Auth::id();
        
        $customerLog->user_category = "Admin";
        $customerLog->user_id = Auth::id();
        //dd($customer .$customerLog);
        $customerLog->save();
        //$customer->save();
        $created_customer=Customer::create($customer)->cust_id;
        
        //create customer wallet
        $customerwallet=new CustomerWallet();
        $customerwallet->cust_wallet_bal=0;
        //set account name
        $customerwallet->cust_wallet_account_name="BMP.".$request->username;
        $customerwallet->customer_cust_id=$created_customer;
        $customerwallet->save();
        
        //send a message to the user with some default password
        $phn="254".$request->primary;
        $sms='Dear '.$request->name.',Welcome to Mobisky Bulk Payments Platform.Your username:'."BMP.".$request->username.' and password:'.$otp.'.Kindly keep the password safely and delete the message.';
        $smsobject->sendMessage($phn,$sms);
        
        //write to csv
        $module=$customerLog->audit_module;$activity=$customerLog->audit_activity;$user_category=$customerLog->user_category;$user_id=$customerLog->user_id;$datetime=date('Y-m-d h:i:s');
        $list = array (
        array($module, $activity,  $user_category,$user_id, $datetime),
        );
        
        $file = fopen("csvs/Audit.csv","a+");
        
        foreach ($list as $line) {
        fputcsv($file, $line);
        }
        
        fclose($file);
        // end write to csv

        return response()->json($customer);
    }
    public function store(Request $request)
    {
        //add customers
       // try
       // {
        request()->validate([
            'cust_name'=> 'required',
            'cust_primary_contact_type' => 'required',
            'cust_sec_contact' => 'required',
            'email' => 'required',
            'cust_username' => 'required|unique:'.Customer::class.',cust_username',
        ]);
        $customer = new Customer();
        $customer->cust_name = $request->get('cust_name');
        $customer->cust_primary_contact_type = $request->get('cust_primary_contact_type');
        $customer->cust_sec_contact = $request->get('cust_sec_contact');
        $customer->email = $request->get('email');
        $customer->cust_username = $request->get('cust_username');
        //default password is the username...USER be advised to change
        $customer->password = Hash::make(substr(Hash::make($request->get('cust_username')),-8));
        $customer->cust_status = 1;
        // log data
        $customerLog = new AuditLog();
        $customerLog->audit_module = "Customer";
        $customerLog->audit_activity = "Customer ".$customer->cust_username ."added by Admin ID# " .Auth::id();
        
        $customerLog->user_category = "Admin";
        $customerLog->user_id = Auth::id();
        //dd($customer .$customerLog);
        $customerLog->save();
        $customer->save();
        //write to csv
        $module=$customerLog->audit_module;$activity=$customerLog->audit_activity;$user_category=$customerLog->user_category;$user_id=$customerLog->user_id;$datetime=date('Y-m-d h:i:s');
        $list = array (
        array($module, $activity,  $user_category,$user_id, $datetime),
        );
        
        $file = fopen("csvs/Audit.csv","a+");
        
        foreach ($list as $line) {
        fputcsv($file, $line);
        }
        
        fclose($file);
        // end write to csv
         return redirect()->back()
            ->with('success','Customer Added Succesfully.');
        //}
       // catch (Exception $exception)
       // {
           // return back()->withInput()
           //git   /   ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
      //  }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        if(Auth::user()->user_type == 'admin')
        {
            $customer = Customer::find($id);
            return view('bmviews.customers.details',compact('customer'));
        }
        else
        {
            return redirect('/admin/login')->with('failure','Access Denied! Lo in to continue');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        if(Auth::user()->user_type == 'admin')
        {
        $customer = Customer::find($id);
        return view('bmviews.customers.edit',compact('customer'));
        }
        else
        {
            return redirect('/admin/login')->with('failure','Access Denied! Lo in to continue');
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {

      //  try
        // { 
            request()->validate([
                'name'=> 'required',
                'primary' => 'required',
                'secondary' => 'required',
                'email' => 'required',
                'username' => 'required',
                'password' => 'string',
                            'min:10',             // must be at least 10 characters in length
                            'regex:/[a-z]/',      // must contain at least one lowercase letter
                            'regex:/[A-Z]/',      // must contain at least one uppercase letter
                            'regex:/[0-9]/',      // must contain at least one digit
                            'regex:/[@`~$^!%()-_*#?&]/', // must contain a special character]'
            ]);
        //current customer details
        $customerdets = Customer::where('cust_id',$request->id)->get();

        //update
        $customer = Customer::findorfail($request->id);
       
        $customer->cust_name = $request->get('name');
        $customer->cust_primary_contact_type = $request->get('primary');
        $customer->cust_sec_contact = $request->get('secondary');
        $customer->email = $request->get('email');
        $customer->cust_username = $request->get('username');
        $customer->cust_status = $request->has('status') ? 1 : 0;
        if($request->password)
        {
            $customer->password = Hash::make($request->password);
        }
        // log data
        $customerLog = new AuditLog();
        $customerLog->audit_module = "Customer";
        $customerLog->audit_activity = "Customer details ";
        
        $customerLog->user_category = "Admin";
        $customerLog->user_id = Auth::id();
        //dd($customer .$customerLog);
        $customerLog->save();
        $customer->save();

        //write to csv
        $module=$customerLog->audit_module;$activity=$customerLog->audit_activity;$user_category=$customerLog->user_category;$user_id=$customerLog->user_id;$datetime=date('Y-m-d h:i:s');
        $list = array (
        array($module, $activity,  $user_category,$user_id, $datetime),
        );
        //send a message to the user with some default password
        $phn="254".substr($request->get('cust_primary_contact_type'),-9);
        
        if($request->password)
        {
            $txt = $request->password;
        }
        else
        {
            $txt='old password';
        }
    
         //get username and password for mobisky sms api
         $mobiskysms=app('App\Http\Controllers\BMControllers\ServiceCredentialController')->mobiskySettings();
                
        //read the values from the settings after db mapping
         $sms_username=\Config::get('outpost.sms_username');
         $sms_password=\Config::get('outpost.sms_password'); 

         $smsobject=new Mobisky('twalisha','twalisha');
        
         $sms='Dear '.$request->get('cust_name').',You have edited your account details'."Username: ".$request->cust_name.' and password:'.$txt;
         $smsobject->sendMessage($phn,$sms);
        
        $file = fopen("csvs/Audit.csv","a+");
        
        foreach ($list as $line) {
        fputcsv($file, $line);
        }
        
        fclose($file);
        // end write to csv

          return redirect()->back()
            ->with('success','Customer Edited Succesfully.'); 
            
        // }
      //  catch (Exception $exception)
       // {
          //  return back()->withInput()
            //    ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
      //  }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
      //  try
        {
        //find customer details before delete
        $customer = Customer::where('cust_id',$id)->get();
        //set delete
        $deleteCustomer = Customer::find($id);
        $CustomerUser=CustomerUser::where('customer_cust_id',$id)->get();
        $CustomerClient=CustomerClient::where('customer_cust_id',$id)->get();
        $CustomerGroup=CustomerGroup::where('customer_cust_id',$id)->get();
        $CustomerWallet=CustomerWallet::where('customer_cust_id',$id)->get();
        $CustomerPasswordReset=CustomerPasswordReset::where('customer_cust_id',$id)->get();
        $ClientBatch=ClientBatch::where('client_batch_customer_id',$id)->get();
        //get all the dependencies of a customer before deleting it        
        if( !empty( $CustomerUser->toArray()) ||!empty( $CustomerClient->toArray() ) ||!empty( $CustomerGroup->toArray() )
        ||!empty( $CustomerWallet->toArray() )||!empty( $CustomerPasswordReset->toArray() )||!empty( $ClientBatch->toArray() )) {
            //return an error page or message of a dependency
            return redirect()->back()
                ->with('failure','Cannot delete Customer.Associated data with either Users, Payee and Groups exists.');
           // return response()->json("Cannot delete Cusromer.A dependency exists");
         }
        else {
            //initiate delete
            $deleteCustomer->delete();
            //set logging
            $customerLog = new AuditLog();
            $customerLog->audit_module = "Customer";
            $customerLog->audit_activity = "Customer".$id." deleted by Admin ID# " .Auth::id();
            
            $customerLog->user_category = "Admin";
            $customerLog->user_id = Auth::id();
            //dd($deleteCustomer);
            //initiate log
            $customerLog->save();
            //write to csv
            $module=$customerLog->audit_module;$activity=$customerLog->audit_activity;$user_category=$customerLog->user_category;$user_id=$customerLog->user_id;$datetime=date('Y-m-d h:i:s');
            $list = array (
            array($module, $activity,  $user_category,$user_id, $datetime),
            );
            
            $file = fopen("csvs/Audit.csv","a+");
            
            foreach ($list as $line) {
            fputcsv($file, $line);
            }
            
            fclose($file);
            // end write to csv
            //return message
            return redirect()->back()
                ->with('success','Customer  Deleted Succesfully.');
        }
     }
      
    }
}
