<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use DB;
use Auth;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    // public function __construct()
    // {
    //     $this->middleware('permission:view users')->only(['index', 'show']);
    //     $this->middleware('permission:create users')->only(['create', 'store']);
    //     $this->middleware('permission:edit users')->only(['edit', 'update']);
    //     $this->middleware('permission:delete users')->only(['destroy']);
    // }


    public function index(Request $request)
    {
        $query = User::orderBy('created_at', 'desc');
        
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('name', 'like', '%' . $search . '%')
                    ->orWhere('email', 'like', '%' . $search . '%');
        }
        $students = $query->paginate(10);

        if ($request->ajax()) {
            return view('admin.students.ajax', compact('students'))->render();
        }
        return view('admin.students.list', compact('students'));
    }

    public function create()
    {
        return view('admin.users.create', [
            'users' => Admin::all(),
            'roles' => Role::all()
        ]);

        
    }

  
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email' => 'required|email|unique:admins',
            // 'password' => 'required|min:8',
            'role' => 'required'
        ]);

        $admin = Admin::create([
            'name' => $request->name,
            'email' => $request->email,
            // 'password' => bcrypt($request->password)
        ]);

        $admin->assignRole($request->role);

        return redirect()->back()->with('success', 'Admin user created successfully.');
    }

   
    public function student_view(Request $request)
    {
        $id = base64_decode($request->id); 
    
        try {
            $student = User::findOrFail($id);
            return view('admin.students.view', compact('student'));
    
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Student not found.');
        }
    }

    public function student_edit($id)
    {
        $student = User::findOrFail(base64_decode($id)); 

        return view('admin.students.edit', compact('student'));
    }

   
    public function student_update(Request $request)
    {
        $id = base64_decode($request->id);

        $rules = [
            'name'  => 'required',
            'email' => 'required|email',
            'p_email' => 'required|email',
            // 'password' => 'required',
            'dob' => 'required',

        ];

        $messages = [
            'name.required'  => 'Name is required.',
            'email.required' => 'Email is required.',
            'p_email.required' => 'Parent Email is required.',
            // 'password.required' => 'Password is required.',
            'dob.required' => 'Dob is required.',
        ];

         $validation = Validator::make($request->all(), $rules,$messages);
        if ($validation->fails()) {

            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ]);
        }

        // DB::beginTransaction();

        try {
            $student = User::findOrFail($id);

            // if ($request->password) {
            //     $student->password = Hash::make($request->password);
            // }
            $student->name      = $request->name;
            $student->email     = $request->email;
            $student->dob       = $request->dob;
            $student->status    = $request->status;
            $student->parent_email  = $request->p_email;
            $student->frequency   = $request->frequency;

            if ($request->hasFile('image') && $request->file('image')->isValid()) {
                $file = $request->file('image');
                $filename = 'img_' . time() . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('storage/avatars'), $filename);

                // Remove old image
                if ($student->image && file_exists(public_path('storage/avatars/' . $student->image))) {
                    unlink(public_path('storage/avatars/' . $student->image));
                }
                $student->image = $filename;
            }

            $student->save();

            // DB::commit();

            // return redirect()->route('admin.students.list')->with('success', 'Student updated successfully.');
             return response()->json([
                'success' => true,
                'message' => 'Student updated successfully.'
            ]);

        } catch (\Exception $e) {
           return response()->json([
                'success' => false,
                'errors' => ['server' => [$e->getMessage()]]
            ]);

            // return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function student_delete(Request $request)
{
    try {
        $id = base64_decode($request->id);
        $student = User::findOrFail($id);
        $student->delete();

       return response()->json(['message' => 'Item deleted successfully'], 200);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Unable to delete item.'], 500);
        }
}

   
    public function studentStatus(Request $request)
    {
        $stu_id=base64_decode($request->id);
        $type = base64_decode($request->type);
    
        if($type == 'disable')
        { 
            $user = User::find($stu_id);
            $user->status = '0';
            $user->save();
            
            return response()->json([
                'success'=>true,
                'type' => $type,
                'message'=>'Status change successfully.'
            ]);
        }
        elseif($type == 'enable')
        {   
            $user = User::find($stu_id);
            $user->status = '1';
            $user->save();
        
            return response()->json([
                'success'=>true,
                'type' => $type,
                'message'=>'Status change successfully.'
            ]);
        }
    }
}
