<?php

namespace App\Http\Controllers;

use App\Models\DocumentManagement;
use App\Models\FinancialYear;
use App\Models\LmsClasses;
use App\Models\LmsCourse;
use Illuminate\Http\Request;
use App\Models\StudyMaterial;
use App\Models\StudyMaterialType;
use App\Models\Semester;
use App\Models\VoucherType;
use Illuminate\Support\Facades\Auth;

class StudyMaterialsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $study_materials = StudyMaterial::leftjoin('study_material_types' , 'study_materials.material_type_id',  '=' , 'study_material_types.id' )
        ->leftjoin('lms_classes' , 'study_materials.semester_id',  '=' , 'lms_classes.id' )
        ->select(
            'study_materials.id as id',
            'study_materials.title as title',
            'study_materials.file_url as file_url',
            'study_materials.description as description',
            'study_materials.priority as priority',
            'study_materials.is_default as is_default',
            'study_materials.status as status',
            'study_materials.created_by as created_by',
            'study_material_types.name as study_material_type_name',
            'lms_classes.class_name as semester_name',
        )->orderBy('study_materials.priority', 'ASC')
        ->get();

        // if ($request->ajax()) {
        //     $sort_by      = $request->get('sortby') ?? 10;
        //     $sort_type    = $request->get('sorttype');
        //     $search_query = $request->get('query');

        //     $study_materials = $study_materials->when(!empty($search_query), function ($query) use ($search_query) {
        //         return $query->where('study_materials.title', 'like', '%'.$search_query.'%')
        //                     ->orWhere('study_materials.description', 'like', '%'.$search_query.'%')
        //                     ->orWhere('study_material_types.name', 'like', '%'.$search_query.'%')
        //                     ->orWhere('semesters.name', 'like', '%'.$search_query.'%');
        //     })->paginate($sort_by);

            return view('study-materials.table', compact('study_materials'));
        // } else {
        //     $study_materials = $study_materials->paginate(10);

        //     return view('study-materials.index', compact('study_materials'));
        // }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $study_materials      = StudyMaterial::findOrFail($id);
        $study_material_types = StudyMaterialType::all();
        $semesters            = LmsClasses::all();
        $financialYear = FinancialYear::where(['status' => '1'])->get(['financialyearid','financial_year_name','is_default']);
        return view('study-materials.edit', compact('study_materials' , 'study_material_types' , 'semesters','financialYear'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $study_materials = StudyMaterial::findOrFail($id);
        $study_materials->delete();

        return response()->json([
            'success' => true,
            'message' => ['Study Materials Deleted successfully'],
            'data' => [
                'redirect' => '', 
            ]
        ]);
    }

    public function createStudyMaterials(Request $request)
    {
       $semesters            = LmsClasses::all();
       $priority = StudyMaterial::max('priority');
       $priority = $priority != '' ? $priority : 0;
       $financialYear = FinancialYear::where(['status' => '1'])->get(['financialyearid','financial_year_name','is_default']);
       $course_id = $request->course_id;
       $material_type_id = $request->material_type_id;

        return view('study-materials.create', compact('semesters' , 'priority','financialYear','course_id','material_type_id'));
    } 

    public function storeStudyMaterials(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'title'            => 'required',
            'priority'         => 'required',
            'semester_id'      => 'required',
            'material_type_id' => 'required',
        ]);

        if ($validator->fails()) {

            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                    'redirect' => 'study-materials.index'],
            ]);
        }

        $study_materials = StudyMaterial::create([
            'title'            => $request->title,
            'description'      => $request->description??'',
            'priority'         => $request->priority,
            'semester_id'      => $request->semester_id,
            'material_type_id' => $request->material_type_id,
            'created_by'       => Auth::user()->id,
            'course_id'        => $request->course_id,
            'financial_year_id'=> $request->financial_year_id,
        ]);

        return response()->json([
            'success'  => true,
            'message'  => 'Study Material Created successfully',
            'data'     => [
                'redirect' => 'study-materials.index', 
            ]
        ]);
    }

    public function updateStudyMaterials(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'title'             => 'required',
            'priority'          => 'required',
            'semester_id'      => 'required',
        ]);

        if ($validator->fails()) {
           return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                    'redirect' => 'study-materials.index'],
            ]);
        }

        $study_materials = StudyMaterial::findOrFail($id);
        $study_materials->update($request->all());

        return response()->json([
            'success'  => true,
            'message'  => 'Study Material updated successfully',
            'data'     => [
                'redirect' => 'study-materials.index', 
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $update = StudyMaterial::where('id', '=', $request->id)->update($data);

            if($update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Study Material status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function isDefaultchangeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $update = StudyMaterial::where('id', '=', $request->id)->update($data);

            if($update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Study Material is Default status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }


    public function table(Request $request,$course_id)
    {
        $study_materials = StudyMaterial::leftjoin('study_material_types' , 'study_materials.material_type_id',  '=' , 'study_material_types.id' )
        ->leftjoin('lms_classes' , 'study_materials.semester_id',  '=' , 'lms_classes.id' )
        ->select(
            'study_materials.id as id',
            'study_materials.title as title',
            'study_materials.file_url as file_url',
            'study_materials.description as description',
            'study_materials.priority as priority',
            'study_materials.is_default as is_default',
            'study_materials.status as status',
            'study_materials.created_by as created_by',
            'study_materials.material_type_id',
            'study_material_types.name as study_material_type_name',
            'lms_classes.class_name as semester_name',
        )->orderBy('study_materials.priority', 'ASC')
        ->where('study_materials.course_id',$course_id)
        ->get();
        return view('study-materials.table', compact('study_materials','course_id'));
    }

    public function fileCreate($id){
        return view('study-materials.create-file',compact('id'));
    }

    public function fileStore(Request $request){
        $voucher_type = VoucherType::with('voucherSeries')->where('code', 'COURSE_VOUCHER')->where(['status' => 1])->first();

        # last voucher count for main voucher type invoice number
        $voucher_type_last_count = DocumentManagement::select('last_voucher_count')
            ->where(['voucher_type' => 'COURSE_VOUCHER'])
            ->orderBy('created_at', 'DESC')
            ->first();

        $voucher_type_count = isset($voucher_type_last_count) && isset($voucher_type_last_count->last_voucher_count) ? $voucher_type_last_count->last_voucher_count + 1 : ($voucher_type->voucherSeries->start_from + 1 ?? 1);

        $voucher_type_invoice_no = $this->generateCode(
            $voucher_type_count,
            ($voucher_type->voucherSeries->prefix ?? 'RV'),
            ($voucher_type->voucherSeries->postfix ?? ''),
            ($voucher_type->voucherSeries->separator ?? '-'),
            ($voucher_type->voucherSeries->length ?? 5)
        );

        $data['document_no'] = $voucher_type_invoice_no;
        if($request->file_types==6 || $request->file_types==7 || $request->file_types==8)
        {
            $data['file_url'] = $request->notes??"";
        }
        else
        {
            if ($request->hasFile('attachment')) {
                $path     = 'document-management/' . date('Y') . '/' . date('M');
                $response = uploadImage($path, $request->attachment);
    
                if ($response['status'] == true) {
                    $data['file_url'] = $response['file_name'];
                } else {
                    if ($request->ajax()) {
                        return response()->json([
                            'success' => false,
                            'message' => $response['message'],
                            'data'    => []
                        ]);
                    }
    
                    return redirect()->back()->with('error', $response['message']);
                }
            }
        }

        

        $default_check = DocumentManagement::where(['is_default' => '1','status' => '1'])->first();

        if (!$default_check) {
            $data['is_default'] = "1";
        }

        $data['last_voucher_count'] = $voucher_type_count;
        $data['voucher_id']         = $request->id;
        $data['company_id']         = \Auth::user()->company_id;
        $data['user_id']            = \Auth::id();
        $data['voucher_type']       = 'COURSE_VOUCHER';
        $data['date_time']          = date('Y-m-d H:i:s');
        $data['document_note']      = $request->document_note??'';
        $data['file_types']         = $request->file_types??'';

        DocumentManagement::create($data);

        return response()->json([
            'success'=>true,
            'message'=>['Document has been uploaded successfully.'],
            'data'=>[
               'redirect'=>'',
               'reload'=>true,
            ]
        ]);
    }

    public function fileShow($course_id,$material_type_id,$material_id){
        $data['documents'] = DocumentManagement::where(['voucher_type'=>'COURSE_VOUCHER','voucher_id'=>$material_id])->get();
        $data['materialType'] = StudyMaterialType::select('name')->find($material_type_id);
        $data['course'] = LmsCourse::select('course_title')->find($course_id);
        $data['study_materials'] = StudyMaterial::select('title')->find($material_id);
        $data['course_id'] = $course_id;
        $data['material_type_id'] = $material_type_id;
        $data['material_id'] = $material_id;
        return view('study-materials.files-table', $data);
    }

    public function fileDestroy($id){
        DocumentManagement::find($id)->delete();
        return response()->json([
            'success'=>true,
            'message'=>['Document has been Deleted successfully.'],
            'data'=>[
               'redirect'=>'',
               'reload'=>true,
            ]
        ]);
    }
}
