<?php

namespace App\Http\Controllers\BMControllers;
use Illuminate\Http\Request;
use Auth;
use Hash;
use App\Models\bmmodels\CustomerClient;
use App\Models\bmmodels\AuditLog;
use Exception;
use App\Imports\BMImports\ClientsImport;
use Maatwebsite\Excel\Facades\Excel;

class ClientController extends Controller
{
    // public function __construct()
    // {
    //     //$this->middleware('revalidate');
    //     $this->middleware(['auth:admin'],['auth:customer']);

        
    // }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {

        //fetch all customers
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
            try
            {
            if(isset($id))
            {
                $CustomerClients = CustomerClient::where('customer_cust_id', $id)->get();
                return view('bmviews.clients.index', compact('CustomerClients','id'));
            }
            }
            catch(Exception $e)
            {
                abort(500, $e->getMessage());   
            }
        }
        else
        {
            try{
                $CustomerClients = CustomerClient::where('customer_cust_id', $id)->get();
                return view('bmviews.clients.index', compact('CustomerClients','id'));
            }
            catch(Exception $e)
            {
                abort(500, $e->getMessage());   
            }
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    //import clients to db
    public function import(Request $request,$id) 
    {
         request()->validate([
            'file' => 'required|max:2000|mimes:xlsx,xls,csv'
        ]);
        $path = $request->file;
        
        Excel::import(new ClientsImport($id), $path);
        
        return redirect()->back(); 
        // return $request->file;
    }

    //vue add customer
    public function addclient(Request $request)
    {
        $this->validate($request, [
            'cust_client_fullname'=> 'required',
            'cust_client_idno' => 'required',
            'cust_client_phone' => 'required',
            // 'cust_client_status' => 'required'
            //'email' => 'required',
            //'username' => 'required'
        ]);
        //chceck if exists
        $check = CustomerClient::where('customer_cust_id',$request->customer_id)->where('cust_client_phone',substr($request->cust_client_phone,-9))->pluck('cust_client_phone');
        if(!$check->count())
        {
            $CustomerClient = new CustomerClient();
            $CustomerClient->cust_client_fullname = $request->cust_client_fullname;
            $CustomerClient->cust_client_idno = $request->cust_client_idno;
            $CustomerClient->cust_client_phone = substr($request->cust_client_phone,-9);
            // $CustomerClient->cust_client_status =$request->cust_client_status;
            $CustomerClient->customer_cust_id ='19';
            
            // log data
            $CustomerClientLog = new AuditLog();
            
            
            if(Auth::user()->user_type == 'organization_user'){
                $CustomerClientLog->audit_module = "User";
                $CustomerClientLog->audit_activity = "Payee ".$CustomerClient->cust_client_fullname ."added by user ID# " .Auth::user()->cust_user_id;
                $CustomerClientLog->user_category = "User";
                $CustomerClientLog->user_id = Auth::user()->cust_user_id;
                $CustomerClient->created_by = Auth::user()->cust_user_username;
            }
            else{
                $CustomerClientLog->audit_module = "Admin";
                $CustomerClientLog->audit_activity = "Payee ".$CustomerClient->cust_client_fullname ."added by Admin ID# " .Auth::id();
                $CustomerClientLog->user_category = "Admin";
                $CustomerClientLog->user_id = Auth::id();
                $CustomerClient->created_by = "ADMIN: ".Auth::id();
            }
        
            //dd($customer .$customerLog);
            
            $CustomerClient->save(); 
            $CustomerClientLog->save();
            //write to csv
            $module="User";$activity=$CustomerClientLog->audit_activity;$user_category='user';$user_id=$CustomerClientLog->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 $CustomerClient;
        }
        else
        {
            return response()->json(["errors"=>["cust_client_phone"=>["Contact phone already exists: ".json_encode($check)]]],422);
        }
    }



    public function create()
    {
        //
        return view('bmviews.clients.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $CustomerClients = CustomerClient::where('cust_client_id',$id)->first();
       return view('bmviews.clients.details',compact('CustomerClients'));

       //return response()->json($CustomerClients);

        //return view('clients.details');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $CustomerClients = CustomerClient::where('cust_client_id',$id)->first();
        return view('bmviews.clients.edit',compact('CustomerClients'));
       // return view('clients.edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $this->validate($request, [
            'cust_client_fullname'=> 'required',
            'cust_client_idno' => 'required',
            'cust_client_phone' => 'required',
            // 'cust_client_status' => 'required'
        ]);
        $id = $request->cust_client_id;
        $customerclientdets = CustomerClient::where('cust_client_id',$id)->get();
        //update
        $CustomerClient = CustomerClient::find($id);
        $CustomerClient->cust_client_fullname = $request->cust_client_fullname;
        $CustomerClient->cust_client_idno = $request->cust_client_idno;
        $CustomerClient->cust_client_phone = $request->cust_client_phone;
        $CustomerClient->cust_client_status =$request->cust_client_status;
        
        // log data
        $CustomerClientLog = new AuditLog();
        
        
        if(Auth::user()->user_type == 'organization_user'){
            $CustomerClientLog->audit_module = "User";
            $CustomerClientLog->audit_activity = "Payee ".$CustomerClient->cust_client_fullname ."Updated from ".$customerclientdets." to ".$CustomerClient." by user ID# " .Auth::user()->cust_user_id;
            $CustomerClientLog->user_category = "User";
            $CustomerClientLog->user_id = Auth::user()->cust_user_id;
        }
        else{
            $CustomerClientLog->audit_module = "Admin";
            $CustomerClientLog->audit_activity = "Payee ".$CustomerClient->cust_client_fullname ."Updated from ".$customerclientdets." to ".$CustomerClient." by Admin ID# " .Auth::id();
            $CustomerClientLog->user_category = "Admin";
            $CustomerClientLog->user_id = Auth::id();
        }
       
        //dd($customer .$customerLog);
        
        $CustomerClient->save(); 
        $CustomerClientLog->save();
        //write to csv
        $module="User";$activity=$CustomerClientLog->audit_activity;$user_category='user';$user_id=$CustomerClientLog->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 $request;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
      //  try
        {
        //find customer details before delete
        $CustomerClient = CustomerClient::where('cust_client_id',$id)->get();
        //set delete
        $deleteCustomerClient = CustomerClient::find($id);
        //set logging
        $CustomerClientLog = new AuditLog();
        if(Auth::user()->user_type == 'organization_user'){
            $CustomerClientLog->audit_module = "User";
            $CustomerClientLog->audit_activity = "Payee ".$id." deleted by user ID# " .Auth::user()->cust_user_id;
            $CustomerClientLog->user_category = "User";
            $CustomerClientLog->user_id = Auth::user()->cust_user_id;
        }
        else{
            $CustomerClientLog->audit_module = "Admin";
            $CustomerClientLog->audit_activity = "Payee ".$id ." deleted by Admin ID# " .Auth::id();
            $CustomerClientLog->user_category = "Admin";
            $CustomerClientLog->user_id = Auth::id();
        }
        
        //dd($deleteCustomerClient);
        //initiate delete
        $deleteCustomerClient->delete();
        //initiate log
        $CustomerClientLog->save();
        //write to csv
        $module="User";$activity=$CustomerClientLog->audit_activity;$user_category='user';$user_id=$CustomerClientLog->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','Payee  Deleted Succesfully.');
        }
           // catch (Exception $exception)
       // {
          //  return back()->withInput()
            //    ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
      //  }
    }
}
