<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Classes;
use App\Models\Role;
use App\Models\Section;
use App\Models\Subject;
use App\Models\User;
use App\Models\User_detail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\URL;

class TeacherController extends Controller
{
    protected $admin_id;
    protected $school_id;
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            // fetch session and use it in entire class with constructor
            $this->school_id = session()->get('school')['id'] ?? '';
            $this->admin_id = session()->get('loggedIn')['id'];
            return $next($request);
        });
    }
    public function index(Request $request)
    {
        $data['pagetitle'] = "Teacher";
        $data['mainSuperAdminMenu'] = 'master';
        $data['superadminSubMenu'] = 'teacher';
        $query = User::leftJoin('users_roles', 'users_roles.user_id', '=', 'users.id');
        $query->leftJoin('roles', 'roles.id', '=', 'users_roles.role_id');
        $query->leftJoin('user_details', 'users.id', '=', 'user_details.user_id');
        $query->where('users.id', '!=', '1');
        $query->where(['users.admin_id' => $this->admin_id, 'users.school_id' => $this->school_id]);
        $query->where('roles.slug', 'teacher');
        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $searchTerm = $_GET['search'];
            $query->where('users.email', 'LIKE', "%{$searchTerm}%");
            $query->orWhere('users.phone', 'LIKE', "%{$searchTerm}%");
        }
        if (isset($_GET['entry']) && !empty($_GET['entry'])) {
            $entry = $_GET['entry'];
        } else {
            $entry = 25;
        }
        $data['teachers'] = $query->groupBy('users.id')->orderBy('users.id', 'desc')->paginate($entry, ['users.*', DB::raw('GROUP_CONCAT(roles.name) as role'), 'user_details.qualification', 'user_details.experience', 'user_details.expertise_in_subject']);
        return view('teacher.list', $data);
    }
    public function create(Request $request)
    {
        $data['pagetitle'] = "Add Teacher";
        $data['mainSuperAdminMenu'] = 'master';
        $data['superadminSubMenu'] = 'teacher';
        $data['classes'] = Classes::where(['admin_id' => $this->admin_id, 'school_id' => $this->school_id])->orderBy('sort', 'asc')->get();
        $data['subjects'] = Subject::where(['admin_id' => $this->admin_id, 'school_id' => $this->school_id])->orderBy('subject', 'asc')->get();
        return view('teacher.add', $data);
    }
    public function store(Request $request)
    {

        $request->validate([
            "username" => "required",
            "email" => "required",
            "user_type" => "required",
            "phone" => "required",
            "experience" => "required",
            "qualification" => "required",
            "password" => "required",
        ]);
        // Check Image
        if ($request->has('image')) {
            $rules['image'] = 'required|image|mimes:jpeg,png,jpg|max:300';
        }
        $hashed = Hash::make($request->password);
        $user_unique_id = uniqid();
        $imageName = null;
        if ($request->has('image')) {
            $imageName = time() . '.' . $request->image->extension();
            $request->image->move(public_path('profiles'), $imageName);
            $imageName = URL::to('/public/profiles' . $imageName);
        }
        $data = array(
            'name' => $request->username,
            'user_unique_id' => $user_unique_id,
            'email' => $request->email,
            'phone' => $request->phone,
            'profile_pics' => $imageName,
            'admin_id' => $this->admin_id,
            'school_id' => $this->school_id,
            'password' => $hashed,
            'user_type' => $request->user_type,
            'ip_address' => $request->ip(),
        );
        $res = User::create($data);
        $user_id = $res->id;
        if ($res) {
            $user = User::where('user_unique_id', $user_unique_id)->first();
            $role = Role::whereIn('slug', ['teacher'])->first();
            $user->roles()->attach($role);

            $ex_subject = "";
            if ($request->has('expertise_in_subject')) {
                $ex_subject = implode(",", $request->expertise_in_subject);
            }
            $data = array(
                'user_id' => $user_id,
                'experience' => $request->experience,
                'qualification' => $request->qualification,
                'expertise_in_subject' => $ex_subject,
            );
            $res = User_detail::create($data);
            return back()->with('success', $request->username . ' Added Successfully!');
            // return back()->with('success',  ' Subject Successfully Added!');
        } else {
            return back()->with('error', ' added sSuccessfully!');
        }
    }
    // Edit
    public function edit($id)
    {
        $data['pagetitle'] = "Edit Teacher";
        $data['mainSuperAdminMenu'] = 'master';
        $data['superadminSubMenu'] = 'teacher';
        $data['classes'] = Classes::orderBy('sort', 'asc')->get();
        $data['sections'] = Section::orderBy('sort', 'asc')->get();
        $data['subjects'] = Subject::where(['admin_id' => $this->admin_id, 'school_id' => $this->school_id])->orderBy('subject', 'asc')->get();
        $query = User::leftJoin('user_details', 'users.id', '=', 'user_details.user_id')->where(['users.id' => $id]);
        $data['teacher'] = $query->first(['users.*', 'user_details.qualification', 'user_details.experience', 'user_details.expertise_in_subject']);
        return view('teacher.edit', $data);
    }
    // Update
    public function update(Request $request, $id)
    {
        $request->validate([
            "username" => "required",
            "email" => "required",
            "user_type" => "required",
            "phone" => "required",
            "experience" => "required",
            "qualification" => "required",
        ]);
        $user = User::find($id);
        if ($request->has('image')) {
            $imageName = time() . '.' . $request->image->extension();
            $request->image->move(public_path('profiles'), $imageName);
            $user->profile_pics = URL::to('public/profiles/' . $imageName);
        } else {
            $user->profile_pics = "noimage.jpg";
        }
        $user->name = $request->username;
        $user->email = $request->email;
        $user->phone = $request->phone;
        $user->user_type = $request->user_type;
        $res = $user->update();
        if ($res) {
            $ex_subject = "";
            if ($request->has('expertise_in_subject')) {
                $ex_subject = implode(",", $request->expertise_in_subject);
            }

            $data = array(
                'experience' => $request->experience,
                'qualification' => $request->qualification,
                'expertise_in_subject' => $ex_subject,
            );
            User_detail::where(['user_id' => $id])->update($data);
            return back()->with('success', 'Teacher Successfully Updated!');
        } else {
            return back()->with('error', ' Added sSuccessfully!');
        }
    }
    // delete
    public function destroy($id)
    {
        User::where(['id' => $id])->delete();
        return back()->with('success', 'Teacher Delete Successfully!');
    }
    public function deleteAll(Request $request)
    {
        $ids = $request->student_ids;
        User::destroy($ids);
        return back()->with('success', 'Teacher Delete Successfully!');
    }
    public function getTeacherSubjectid(Request $request, $subject_id)
    {
        $html = '';
        $teachers = User::join('user_details', 'users.id', '=', 'user_details.user_id')
            // ->where('user_details.expertise_in_subject', 'Like', "%{$subject_id}%")
            ->get(['users.id', 'users.name']);
        if (!$teachers->isEmpty()) {
            $html .= '<option value="">--teacher--</option>';
            foreach ($teachers as $teacher) {
                $html .= '<option value=' . $teacher->id . '>' . $teacher->name . '</option>';
            }
        }
        return response()->JSON($html);
    }
}
