<?php

namespace App\Http\Controllers\BMControllers;

use Illuminate\Http\Request;
use App\Models\bmmodels\AdminUser;
use App\Models\bmmodels\AuditLog;
use Exception;
use Auth;
use Hash;
use App\Models\User;

class AdminUserController extends Controller
{
    // public function __construct()
    // {
    //     $this->middleware('auth:admin');
    // }
    /**
     * Display a listing of the resource..
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        try
        {
        $admins = AdminUser::all();
        return view('bmviews.admin-user.index', compact('admins'));
        }
        catch(Exception $e)
        {
            abort(500, $e->getMessage());   
        }
    }
    public function testIndex()
    {
        //
        $admins = AdminUser::all();
        return $admins;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        try
        {
            return view('bmviews.admin-user.create');
        }
        catch(Exception $e)
        {
            abort(500, $e->getMessage());   
        }
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    //vue add fn()
    public function storeAdmin(Request $request)
    {
        $this->validate($request, [
            'username' => 'required|string',
            'othername' => 'required|string',
            'surname' => 'required|string',
            'password' => ['required',
                        '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]
                   ]]);
        $data = new AdminUser();
        $data->admin_surname = $request->surname;
        $data->admin_othername = $request->othername;
        $data->admin_username = $request->username;
        $data->password = Hash::make($request->password);
        $data->admin_status = 1;
        $data->role_id = 1;
        $data->save ();
        //create accounts user
        $newuser = new User();
        $newuser->username = $request->get('username');
        $newuser->email = $request->get('email');
        $newuser->user_type = 'admin';
        $newuser->password = Hash::make($request->password);
        $newuser->save();
        //log
        $adminLog = new AuditLog();
        $adminLog->audit_module = "Admin";
        $adminLog->audit_activity = "Admin user ".$request->username ." added by Admin ID# " .Auth::id();
       
        $adminLog->user_category = "Admin";
        $adminLog->user_id = Auth::id();
        //dd($adminLog);
        $adminLog->save();
        //write to csv
        $module="Admin";$activity=$adminLog->audit_activity;$user_category='Admin';$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($data);
    }
    public function store(Request $request)
    {
        //add admin user
      //  try
        {
        request()->validate([
            'admin_surname'=> 'required',
            'admin_othername' => 'required',
            'admin_username' => 'required|unique:admin_users,admin_username',
            'password' => 'required|min:6',
        ]);
        $admin = new AdminUser();
        $admin->admin_surname = $request->get('admin_surname');
        $admin->admin_othername = $request->get('admin_othername');
        $admin->admin_username = $request->get('admin_username');
        $admin->password = Hash::make($request->get('admin_password'));
        $admin->admin_status = 1;
        // log data
        $adminLog = new AuditLog();
        $adminLog->audit_module = "Module";
        $adminLog->audit_activity = "Admin user ".$admin->admin_username ."added by Admin ID#" .Auth::id();
      
        $adminLog->user_category = "Admin";
        $adminLog->user_id = Auth::id();
        //dd($adminLog);
        $adminLog->save();
        $admin->save();
         return redirect()->back()
            ->with('success','Admin User Added Succesfully.');
        }
     
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        try
        {
            $admin = AdminUser::find($id);
            return view('bmviews.admin-user.details',compact('admin'));
        }
        catch(Exception $e)
        {
            abort(500, $e->getMessage());   
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    //vue get admin
    public function getAdmin($id)
    {
        //
        $data = AdminUser::find($id);
        return $data;
    }
    public function edit($id)
    {
        //
        try 
        {
            $admindata = AdminUser::find($id);
        
            return view('bmviews.admin-user.edit',compact('admindata'));
        }
        catch(Exception $e)
        {
            abort(500, $e->getMessage());   
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    //vue edit fn()
    public function editAdmin(Request $request)
    {
        $this->validate($request, [
            'username' => 'required|string',
            'othername' => 'required|string',
            'surname' => 'required|string',
                   ]);
        $id = $request->id;
        $admin_surname = $request->surname;
        $admin_othername = $request->othername;
        $admin_username = $request->username;
        if($request->password != '')
        {
        $password = Hash::make($request->password);
        $data = AdminUser::where('admin_id', $id)->update(['admin_surname'=>$admin_surname,'admin_othername'=>$admin_othername,'admin_username'=>$admin_username,'password'=>$password]);
        }
        
        $data = AdminUser::where('admin_id', $id)->update(['admin_surname'=>$admin_surname,'admin_othername'=>$admin_othername,'admin_username'=>$admin_username]);
        ;
       
        if($data==1){
            $updateduser=AdminUser::where('admin_id', $id)->first();
            // log data
            $adminLog = new AuditLog();
            $adminLog->audit_module = "Admin";
            $adminLog->audit_activity = "Admin user ".$admin_username ." updated to " .$admin_username. " by Admin ID#" .Auth::id();
            
            $adminLog->user_category = "Admin";
            $adminLog->user_id = Auth::id();
            $adminLog->save();
            //write to csv
            $module="Admin";$activity=$adminLog->audit_activity;$user_category='Admin';$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 $updateduser;
        }
        else{
            return "user not updated";
        }
       
       
    }
    public function update(Request $request, $id)
    {
        //edit admin
        try
        {
            request()->validate([
                'admin_surname'=> 'required',
                'admin_othername' => 'required',
                'admin_username' => 'required',
            ]);
            //find before update
            $admindets = AdminUser::where('admin_id',$id)->get();
            //update
            $admin = AdminUser::find($id);
            $admin->admin_surname = $request->get('admin_surname');
            $admin->admin_othername = $request->get('admin_othername');
            $admin->admin_username = $request->get('admin_username');
            $admin->admin_status = 1;
            // log data
            $adminLog = new AuditLog();
            $adminLog->audit_module = "Admin";
            $adminLog->audit_activity = "Admin user ".$admindets ." updated to " .$admin. " by Admin ID#" .Auth::id();
            
            $adminLog->user_category = "Admin";
            $adminLog->user_id = Auth::id();
            //dd($admin .$adminLog);
            $adminLog->save();
            $admin->save();
            return redirect()->back()
                ->with('success','Admin User Edited Succesfully.');
            }
            catch (Exception $exception)
            {
                return back()->withInput()
                    ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
            }
    }


    public function deleteAdmin(Request $request,$id){
        //find user details to delete
        $admin = AdminUser::where('admin_id',$id)->get();
        //set delete
        $deleteAdmin = AdminUser::find($id);
        $deleteAdmin->delete();
        //set logging
        $adminLog = new AuditLog();
        $adminLog->audit_module = "Admin";
        $adminLog->audit_activity = "Admin of details: ".$admin." deleted by Admin ID#" .Auth::id();
        
        $adminLog->user_category = "Admin";
        $adminLog->user_id = Auth::id();
        $adminLog->save();
        //write to csv
        $module="Admin";$activity=$adminLog->audit_activity;$user_category='Admin';$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
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try
        {
        //find user details to delete
        $admin = AdminUser::where('admin_id',$id)->get();
        //set delete
        $deleteAdmin = AdminUser::find($id);
        //set logging
        $adminLog = new AuditLog();
        $adminLog->audit_module = "Admin";
        $adminLog->audit_activity = "Admin 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
        $deleteAdmin->delete();
        //return message
        return redirect()->back()
            ->with('success','Admin User Deleted Succesfully.');
        }
            catch (Exception $exception)
        {
            return back()->withInput()
                ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
        }
    }
}

