<?php

namespace App\Http\Controllers\Admin;

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

class SubjectController extends Controller
{
    // public function index()
    // {
    //     $subjects = SubjectMaster::orderBy('created_at', 'desc')->get();
    //     return view('admin.subjects.index', compact('subjects'));
       
    // }

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

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

    public function subject_create(Request $request){
        // $createsub = SubjectMaster::select('id', 'name')->where('status', 1)->get();
        $createsub = SubjectMaster::all();
       return view('admin.subjects.create',compact('createsub'));
    }

    public function subject_store(Request $request){
        $rules = [
            'name' => 'required|unique:subject_masters,name|regex:/^[A-Za-z\s]+$/|max:50',
           'icon' => 'image|mimes:jpeg,png,jpg,gif,svg',
           
        ];

        $messages = [
            'name.required'     => 'Name is required.',
            'name.regex'        => 'name accept character only.',
            'name.max'          => 'Name must not be greater than 50 characters.',
            'name.unique'       => 'This name already exists.',
            'icon.image'        => 'The uploaded file must be an image.',
            'icon.mimes'        => 'Only JPEG, PNG, JPG, GIF, and SVG formats are allowed.',
            
           
        ];

        $validation = Validator::make($request->all(), $rules, $messages);
        if ($validation->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ], 200);
        }

        // DB::beginTransaction();
        try{

         
            $subIcon = null;
            if ($icon = $request->file('icon')) {
                $subIcon = date('YmdHis') . "." . $icon->getClientOriginalExtension();
                $icon->move(public_path('storage/subjects/'), $subIcon);
                $insert_arr['icon'] = $subIcon;
            }

            $insert_arr = array(
            'name'          =>$request->name,
            'status'        =>$request->status,
            'icon'         =>$subIcon,
            'created_at'   => Carbon::now(),
            );

            $insert = SubjectMaster::insert($insert_arr);

            // DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Subject Inserted successfully.'
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'errors' => ['server' => [$e->getMessage()]]
            ]);
        }


    }

    public function subject_edit($id)
    {
        $editsubject = SubjectMaster::findOrFail(base64_decode($id)); 
        // dd($editsubject);
        return view('admin.subjects.edit', compact('editsubject'));
    }


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

        $rules = [
          'name' => 'required|unique:subject_masters,name|regex:/^[A-Za-z\s]+$/|max:50',
            // 'icon' => 'image|mimes:jpeg,png,jpg,gif,svg',
            
        ];

        $messages = [
            'name.required'     => 'Name is required.',
            'name.regex'        => 'name accept character only.',
            'name.max'          => 'Name must not be greater than 50 characters.',
            'name.unique'       => 'This name already exists.',
            // 'icon.image'     => 'The uploaded file must be an image.',
            // 'icon.mimes'     => 'Only JPEG, PNG, JPG, GIF, and SVG formats are allowed.',
           
        ];

        $validation = Validator::make($request->all(), $rules, $messages);
        if ($validation->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ], 200);
        }


        // DB::beginTransaction();

        try {
            $subject = SubjectMaster::findOrFail($id);

            $subject->name  = $request->name;
            $subject->status  = $request->status;


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

                // Remove old image
                if ($subject->image && file_exists(public_path('storage/subjects/' . $subject->icon))) {
                    unlink(public_path('storage/subjects/' . $subject->icon));
                }
                $subject->icon = $filename;
            }
          
            $subject->save();

            // DB::commit();

            // return redirect()->route('admin.feedback-option.index')->with('success', 'Feedback Option updated successfully.');

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


    }


    public function subject_delete(Request $request)
    {
        try {
            $id = base64_decode($request->id);
            $student = SubjectMaster::findOrFail($id);
            $student->delete();
    
            return response()->json(['success' => true, 'message' => 'Subject deleted successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }
    
       
        // public function subjectStatus(Request $request)
        // {
        //     $stu_id=base64_decode($request->id);
        //     $type = base64_decode($request->type);
        
        //     if($type == 'disable')
        //     { 
        //         $user = SubjectMaster::find($stu_id);
        //         $user->status = '0';
        //         $user->save();
                
        //         return response()->json([
        //             'success'=>true,
        //             'type' => $type,
        //             'message'=>'Status change successfully.'
        //         ]);
        //     }
        //     elseif($type == 'enable')
        //     {   
        //         $user = SubjectMaster::find($stu_id);
        //         $user->status = '1';
        //         $user->save();
            
        //         return response()->json([
        //             'success'=>true,
        //             'type' => $type,
        //             'message'=>'Status change successfully.'
        //         ]);
        //     }
        // }


}
