<?php

namespace App\Http\Controllers\Instructor;

use App\Classes\GeniusMailer;
use App\Models\Generalsetting;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;

use Validator;


class LoginController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest', ['except' => ['logout', 'userLogout']]);
    }

    public function showLoginForm()
    {
      $this->code_image();
      return view('instructor.login');
    }

    public function login(Request $request)
    {

      $user  = User::where('email',$request->email)->where('register_id',0)->first();

      if($user){
      
        if($user->status == 0){
          return response()->json(array('errors' => [ 0 => __('Your account is deactivate') ]));
        }

        //--- Validation Section
        $rules = [
                  'email'   => 'required|email',
                  'password' => 'required'
                ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
          return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
        }
        //--- Validation Section Ends

      // Attempt to log the user in
      if (Auth::attempt(['id' => $user->id, 'email' => $request->email, 'password' => $request->password], $request->remember)) {
        // if successful, then redirect to their intended location
        return response()->json(route('instructor-dashboard'));
      }

      // if unsuccessful, then redirect back to the login with the form data
          return response()->json(array('errors' => [ 0 => 'Credentials Doesn\'t Match !' ]));

        }else{
          return response()->json(array('errors' => [ 0 => 'Please do registration to this system.' ]));
        }

    }

    public function showForgotForm()
    {
      return view('admin.forgot');
    }

    public function forgot(Request $request)
    {
      $gs = Generalsetting::findOrFail(1);
      $input =  $request->all();
      if (Instructor::where('email', '=', $request->email)->count() > 0) {
      // user found
      $instructor = Instructor::where('email', '=', $request->email)->firstOrFail();
      $token = md5(time().$instructor->name.$instructor->email);

      $file = fopen(public_path().'/project/storage/tokens/'.$token.'.data','w+');
      fwrite($file,$instructor->id);
      fclose($file);

      $subject = "Reset Password Request";
      $msg = "Please click this link : ".'<a href="'.route('instructor.change.token',$token).'">'.route('instructor.change.token',$token).'</a>'.' to change your password.';
      if($gs->is_smtp == 1)
      {
          $data = [
                  'to' => $request->email,
                  'subject' => $subject,
                  'body' => $msg,
          ];

          $mailer = new GeniusMailer();
          $mailer->sendCustomMail($data);
      }
      else
      {
          $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
          mail($request->email,$subject,$msg,$headers);
      }
      return response()->json('Verification Link Sent Successfully!. Please Check your email.');
      }
      else{
      // user not found
      return response()->json(array('errors' => [ 0 => 'No Account Found With This Email.' ]));
      }
    }

    public function showChangePassForm($token)
    {
      if (file_exists(public_path().'/project/storage/tokens/'.$token.'.data')){
        $id = file_get_contents(public_path().'/project/storage/tokens/'.$token.'.data');
        return view('admin.changepass',compact('id','token'));
      }
    }

    public function changepass(Request $request)
    {
        $id = $request->admin_id;
        $admin =  Admin::findOrFail($id);
        $token = $request->file_token;
        if ($request->cpass){
            if (Hash::check($request->cpass, $admin->password)){
                if ($request->newpass == $request->renewpass){
                    $input['password'] = Hash::make($request->newpass);
                }else{
                    return response()->json(array('errors' => [ 0 => 'Confirm password does not match.' ]));
                }
            }else{
                return response()->json(array('errors' => [ 0 => 'Current password Does not match.' ]));
            }
        }
        $admin->update($input);

        unlink(public_path().'/project/storage/tokens/'.$token.'.data');

        $msg = 'Successfully changed your password.<a href="'.route('admin.login').'"> Login Now</a>';
        return response()->json($msg);
    }


    public function logout()
    {
        Auth::guard('web')->logout();
        return redirect('/');
    }

     // Capcha Code Image
     private function  code_image()
     {
         $actual_path = str_replace('project','',base_path());
         $image = imagecreatetruecolor(200, 50);
         $background_color = imagecolorallocate($image, 255, 255, 255);
         imagefilledrectangle($image,0,0,200,50,$background_color);

         $pixel = imagecolorallocate($image, 0,0,255);
         for($i=0;$i<500;$i++)
         {
             imagesetpixel($image,rand()%200,rand()%50,$pixel);
         }

         $font = $actual_path.'assets/front/fonts/NotoSans-Bold.ttf';
         $allowed_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
         $length = strlen($allowed_letters);
         $letter = $allowed_letters[rand(0, $length-1)];
         $word='';
         //$text_color = imagecolorallocate($image, 8, 186, 239);
         $text_color = imagecolorallocate($image, 0, 0, 0);
         $cap_length=6;// No. of character in image
         for ($i = 0; $i< $cap_length;$i++)
         {
             $letter = $allowed_letters[rand(0, $length-1)];
             imagettftext($image, 25, 1, 35+($i*25), 35, $text_color, $font, $letter);
             $word.=$letter;
         }
         $pixels = imagecolorallocate($image, 8, 186, 239);
         for($i=0;$i<500;$i++)
         {
             imagesetpixel($image,rand()%200,rand()%50,$pixels);
         }
         session(['captcha_string' => $word]);
         imagepng($image, $actual_path."assets/images/capcha_code.png");
     }
}
