<?php

namespace App\Http\Controllers\BMControllers;

use Illuminate\Http\Request;
use Auth;
use Hash;
use App\Models\bmmodels\CustomerGroup;
use App\Models\bmmodels\AuditLog;
use Exception;
use Log;
use ErrorException;


class GroupController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {  
        
         
        
           try
           {
                if(isset($id))
                {
                
                    $customerGroups = CustomerGroup::where('customer_cust_id', $id)->orderByDesc('cust_group_id')->get();
                }
                else{
                    $customerGroups = CustomerGroup::all();
                }
                
                return view('bmviews.groups.index', compact('customerGroups','id'));
            }
            catch(Exception $e)
            {
            abort(500, $e->getMessage());
            }
        
        
      
    }

   
    public function create()
    {
        //
        
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
        $id = Auth::user()->customer_cust_id;
        return view('bmviews.groups.create', compact('id'));
        }
        else{
            return abort(401);
        }
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function addGroup(Request $request)
    {
        //add admin user
      //  try
        {
        request()->validate([
            'cust_group_name'=> 'required',
            // 'cust_group_status' => 'required',
            
        ]);
        $customerGroup = new customerGroup();
        $customerGroup->cust_group_name = $request->get('cust_group_name');
        $customerGroup->cust_group_status = 1;
      
        $customerGroup->customer_cust_id = $request->c_id;
     
      
        // log data
        $adminLog = new AuditLog();
        if(Auth::user()->user_type == 'organization_user'){
            $adminLog->audit_module = "User";
            $adminLog->audit_activity = "Group ".$customerGroup->cust_group_name ."added by user ID# " .Auth::user()->cust_user_id;
            $adminLog->user_category = "User";
            $adminLog->user_id = Auth::user()->cust_user_id;
        }
        
        else{
            $adminLog->audit_module = "Admin";
            $adminLog->audit_activity = "Group ".$customerGroup->cust_group_name ."added by Admin ID# " .Auth::id();
            $adminLog->user_category = "Admin";
            $adminLog->user_id = Auth::id();
            
        }
        //dd($adminLog);
        $adminLog->save();
        $customerGroup->save();
        //write to csv
        $module=$adminLog->audit_module;$activity=$adminLog->audit_activity;$user_category=$adminLog->user_category;$user_id=$adminLog->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($request->get('c_id'));
    }
}


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $customerGroup = customerGroup::find($id);
        return view('bmviews.groups.details',compact('customerGroup'));
       /// return view('groups.details');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //

        $customerGroups = customerGroup::where('cust_group_id',$id)->first();
        return view('bmviews.clients.edit',compact('customerGroups'));

        //$customerUser = customerUser::find($id);
        //return view('users.details',compact('customerUser'));


        return view('bmviews.groups.edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function editGroup(Request $request)
    {
         //
      request()->validate([
        'cust_group_name' => 'required',
        // 'cust_group_status' => 'required',
       
      ]);
      //current group details
      $id = $request->cust_group_id;
      $customergroupdets = CustomerGroup::where('cust_group_id',$id)->get();
      //update
      $customerGroup = CustomerGroup::find($id);
      $customerGroup->cust_group_name = $request->cust_group_name;
      $customerGroup->cust_group_status = $request->cust_group_status;
      $customerGroup->customer_cust_id = $request->customer_cust_id;
        // log data
      $customerGroupLog = new AuditLog();
      
      if(Auth::user()->user_type == 'organization_user'){
        $customerGroupLog->audit_module = "User";
        $customerGroupLog->audit_activity = "Group".$request->cust_group_name ." updated from ".$customergroupdets." to ".$customerGroup." by User ID# " .Auth::user()->cust_user_id;
 
        $customerGroupLog->user_category = "User";
        $customerGroupLog->user_id = Auth::user()->cust_user_id;
    }else{
        $customerGroupLog->audit_module = "Admin";
        $customerGroupLog->audit_activity = "Group".$request->cust_group_name ." updated from ".$customergroupdets." to ".$customerGroup." by Admin ID# " .Auth::id();
 
        $customerGroupLog->user_category = "Admin";
        $customerGroupLog->user_id = Auth::id();
    }
      $customerGroupLog->save();
      $customerGroup->save();
      //write to csv
      $module=$customerGroupLog->audit_module;$activity=$customerGroupLog->audit_activity;$user_category=$customerGroupLog->user_category;$user_id=$customerGroupLog->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($request->customer_cust_id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function deleteGroup($id)
    {
        try
        {
        //find user details to delete
        $admin = CustomerGroup::where('cust_group_id',$id)->get();
        //set delete
        $deleteGroup= CustomerGroup::find($id);
        //set logging
        $adminLog = new AuditLog();
        
        if(Auth::user()->user_type == 'organization_user'){
            $adminLog->audit_module = "User";
            $adminLog->audit_activity = "Group of details: ".$admin ."deleted by user ID# " .Auth::user()->cust_user_id;
            $adminLog->user_category = "User";
            $adminLog->user_id = Auth::user()->cust_user_id;
        }else{
            $adminLog->audit_module = "Admin";
            $adminLog->audit_activity = "Group of details: ".$admin ."deleted by Admin ID# " .Auth::id();
            $adminLog->user_category = "Admin";
            $adminLog->user_id = Auth::id();
        }
         
        //dd($deleteAdmin);
        //initiate log
        $adminLog->save();
        //initiate delete
        $deleteGroup->delete();
        //write to csv
        $module=$adminLog->audit_module;$activity=$adminLog->audit_activity;$user_category=$adminLog->user_category;$user_id=$adminLog->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','Group Deleted Succesfully.');
        }
            catch (Exception $exception)
        {
            return back()->withInput()
                ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
        }
    }
    public function getMyGroups()
    {
        $id = Auth::user()->bulk_cust_id;
        $mygroups = CustomerGroup::where('customer_cust_id',$id)->get();
        return view('bmviews.partials.filter-supervise',compact('mygroups'));
    }
}
