<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\User;
use Auth;
use Mail;
use PDF;
use File;
use Excel;
use DB;

class TecherController extends Controller
{
    
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function create()
    {
        return view('admin.teacher.add');
    }

    public function view()
    {
        $teachers = User::where('user_type', 'teacher')->latest()->get();
        return view('admin.teacher.view', compact('teachers'));
    }

    public function edit($id)
    {
        $teachers = User::where('id', $id)->first();
        return view('admin.teacher.edit', compact('teachers'));
    }

    public function delete($id)
    {

        User::findOrFail($id)->delete();
        return redirect()->back()->with('error', 'Deleted Successfully');

    }

    public function store(Request $request)
    {
        // dd($request->all());
        $request->validate([
            'name'          => 'required|max:255'
        ]);

        if ($request->user_id) {
            $user                = User::find($request->user_id);
            if ($request->password) {
                $user->password      = Hash::make($request->password);
            }
        }
        else
        {
            $user                = new User();
            if ($request->password) {
                $user->password      = Hash::make($request->password);
            }
        }

        $user->name          = $request->name;
        $user->email         = $request->email;
        $user->phone         = $request->phone;
        $user->salary        = $request->salary;
        $user->join_date     = $request->join_date;
        $user->user_type     = "teacher";
        $user->status        = $request->status;
        
        if ($user->save()) {

            if ($request->user_id) 
            {
                return redirect()->route('admin.teacher.view')->with('warning', 'Teacher Details Updated Successfully');
            }
            else
            {
                return redirect()->route('admin.teacher.view')->with('success', 'Teacher Created Successfully');
            }
        }
        else{
            return redirect()->back()->with('error', 'Something Wrong');
        }
    }

}
