<?php

namespace App\Http\Controllers\AdminAuth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use App\Model\Sitesetting;
use App\Model\Board;
use App\Admin;
use App\Model\Standard;
use App\Model\Subject;
use App\Model\Category;
use App\Model\Semester;
use App\Model\Chapter;
use App\Model\Paper;
use App\Model\PaperDetail;
use App\Model\QuestionType;
use App\Model\QuestionNumber;
use App\Model\QuestionSection;
use Yajra\Datatables\Datatables;
use Dompdf\Dompdf;
use Dompdf\Options;
use PDF;
class PaperController extends Controller {


	private function _validate($request, $id = null) {
        $this->validate($request, [
            'board_id' => 'required',
			'standard_id' => 'required',
			'semester_id' => 'required',
			'subject_id' => 'required',
			'chapter_id' => 'required',
			'paper_date'=>'required',
			'paper_type'=>'required',
			'paper_difficulty'=>'required',
			'generate_as'=>'required',
			'generate_type' => 'required',
        ]);
    }
   public function index(Request $request)
   {
	if ($request->ajax()) {
		
		$records = Paper::with(['board','standard','semester','subject'])->select('papers.*')->orderBy('id','desc');
			
		
		return Datatables::of($records)
				
				
				->addColumn('action', function ($record) {
					return '<a href="' . url('admin/paper/paperpdf/'.$record->id) . '" class="btn btn-success btn-sm" title="" data-toggle="tooltip" data-original-title="Paper Pdf" target="_blank"><i class="fa fa-file-pdf-o"></i></a>' .
							'&nbsp;<a href="' . url('admin/paperedit/'.$record->id) . '" class="btn btn-info btn-sm" title="" data-toggle="tooltip" data-original-title="Edit"><i class="fa fa-pencil"></i></a>';
							/* 
							'&nbsp;<button class="btn btn-danger btn-sm data-delete" data-id="' . $record->id . '" data-toggle="tooltip" data-original-title="Delete"><i class="fa fa-trash"></i></button>' */
				})
				->rawColumns(['action'])
				->make(true);
	}
	
	return view('admin.paper.index');
	
   }
	public function create(){
        $board = Board::get();
		$medium = \App\Model\Medium::with('standard')->where('status','=','Active')->get();
        $medium_array = [];
        foreach ($medium as $key => $m) {
            $medium_array[$m['name']] = $m['standard']->pluck('name','id')->toArray(); 
        }
		$standard = $medium_array;
		$category = Category::get();
		$paper = [];
		return view('admin.paper.create')->with(['board'=>$board,'standard'=>$standard,'category'=>$category,'paper'=>$paper]);
	}
	public function edit($id)
	{
		$paper = Paper::find($id);
	
		$board = Board::get();
		$standard = Standard::where('board_id',$paper->board_id)->where('id',$paper->standard_id)->get();
		
		$semester = Semester::where('id',$paper->semester_id)->get();
		$subject = Subject::where('standard_id',$paper->standard_id)->get();
		$chapter = Chapter::where('subject_id',$paper->subject_id)->get();
		
		$category = Category::get();
		return view('admin.paper.create')->with(['board'=>$board,'standard'=>$standard,'category'=>$category,'paper'=>$paper,'semester'=>$semester,'subject'=>$subject,'chapter'=>$chapter]);

	}

	public function paperstore(Request $request)
	{
		
		
		$paper = new Paper();
		$paper->board_id = $request->board_id;
		$paper->standard_id = $request->standard_id;
		$paper->semester_id = $request->semester_id;
		$paper->subject_id = $request->subject_id;
        $paper->admin_id = Auth::guard('admin')->user()->id;
		$paper->chapter_id = implode(',',$request->chapter_id);
		if(!empty($request->paper_date))
		{
		$paper->paper_date = date('Y-m-d',strtotime($request->paper_date));
		}
		else{
			$paper->paper_date = null;
		}
		$paper->paper_type = $request->paper_type;
		$paper->paper_difficulty = $request->paper_difficulty;
		$paper->generate_as = $request->generate_as;
		$paper->generate_type = $request->generate_type;
		$paper->save();


		if(!empty($request->questiontype))
		{
			foreach ($request->questiontype as $index => $questionTypeId) {
				
				
					foreach ($request->question[$questionTypeId] as $key => $question) 
					{
						
                       $paperdetail = new PaperDetail();
					  if(!empty($request->question_select[$questionTypeId][$key]))
					  {
					    $paperdetail->paper_id = $paper->id;
						$paperdetail->questiontype_id = $questionTypeId;
						$paperdetail->question_id = $question;
						$paperdetail->question_no = $request->question_no[$index];
						$paperdetail->question_section = $request->question_section[$index];
						$paperdetail->question_mark = $request->question_mark[$questionTypeId][$key];
						$paperdetail->optional = $request->optional[$questionTypeId][$key];
						
						$paperdetail->que_id = $request->que_id[$questionTypeId][$key];
						
						$paperdetail->save();
					  }
					   
					}
				
			}
		}
		Session::flash('success', 'Paper Inserted Successfully.');
        return redirect('admin/paper/create');

	}

	public function paperupdate(Request $request,$id)
	{
		$paper =  Paper::find($id);
		$paper->board_id = $request->board_id;
		$paper->standard_id = $request->standard_id;
		$paper->semester_id = $request->semester_id;
		$paper->subject_id = $request->subject_id;
        $paper->admin_id = Auth::guard('admin')->user()->id;
		$paper->chapter_id = implode(',',$request->chapter_id);
		if(!empty($request->paper_date))
		{
		$paper->paper_date = date('Y-m-d',strtotime($request->paper_date));
		}
		else{
			$paper->paper_date = null;
		}
		$paper->paper_type = $request->paper_type;
		$paper->paper_difficulty = $request->paper_difficulty;
		$paper->generate_as = $request->generate_as;
		$paper->generate_type = $request->generate_type;
		$paper->update();

		$paperde = PaperDetail::where('paper_id',$paper->id)->get();
		foreach ($paperde as $pe) {
			$pe->forceDelete();
		}

		if(!empty($request->questiontype))
		{
			foreach ($request->questiontype as $index => $questionTypeId) {
				
				
					foreach ($request->question[$questionTypeId] as $key => $question) 
					{
						
                       $paperdetail = new PaperDetail();
					  if(!empty($request->question_select[$questionTypeId][$key]))
					  {
					    $paperdetail->paper_id = $paper->id;
						$paperdetail->questiontype_id = $questionTypeId;
						$paperdetail->question_id = $question;
						$paperdetail->question_no = $request->question_no[$index];
						$paperdetail->question_section = $request->question_section[$index];
						$paperdetail->question_mark = $request->question_mark[$questionTypeId][$key];
						$paperdetail->optional = $request->optional[$questionTypeId][$key];
						
						$paperdetail->que_id = $request->que_id[$questionTypeId][$key];
						
						$paperdetail->save();
					  }
					   
					}
				
			}
		}
		Session::flash('success', 'Paper Updated Successfully.');
        return redirect('admin/paper');


	}

	public function getsemester(Request $request)
	{
      
		$id=$request->standard_id;
		$record = \App\Model\Subject::where('standard_id',$id)->pluck('name','id');
        $semesters = Semester::where('standard_id',$request->standard_id)->pluck('name','id');
        $response = [
            'subjects' => $record,
            'semesters' => $semesters,
        ];
		return \Illuminate\Support\Facades\Response::json($response);
	}
	public function getstandard(Request $request)
	{
		$standards = Standard::where('board_id', $request->board_id)->pluck('name', 'id');

        // Return the standards as a JSON response
        return response()->json($standards);
	}

	public function getquestiontype(Request $request)
	{
		$paperdetail = [];
    if (!empty($request->paper_id)) {
        $paperdetail = PaperDetail::where('paper_id', $request->paper_id)->get()->toArray();
    }
		$subject_ids = Chapter::wherein('id',$request->chapter_id)->pluck('subject_id')->toArray();
		$question_no = QuestionNumber::pluck('question_no','id');
		$question_section = QuestionSection::pluck('question_section','id');
		$questionType = QuestionType::with(['question' => function($query) use ($request) {
			$query->whereIn('chapter_id', $request->chapter_id);
		},'question.chapter'])
        ->whereIn('subject_id', $subject_ids)
		->select('questiontypes.*') 
        ->get();
		$response = [
			'questionType' => $questionType,
			'question_no' => $question_no,
			'question_section' => $question_section,
			'paperdetail' => $paperdetail, // Include paper details
		];
     
    // Return the data as JSON
    return response()->json($response);
	}

	public function paperpdf(Request $request,$id)
	{ 
		$user = Auth::guard('admin')->user();
    $admin = Admin::find($user->id);
    $paper = Paper::with(['board', 'standard', 'subject'])->select('papers.*')->where('id', $id)->first();
    $paperdetail = PaperDetail::where('paper_id', $id)->get();
    $totalmark = Paperdetail::where('paper_id', $id)->sum('question_mark');
    $sitesetting = Sitesetting::first();
/*
    $questionTypeIds = PaperDetail::where('paper_id', $id)->get()->groupBy('questiontype_id'); 
	
    $questionTypeIds = $questionTypeIds->keys()->toArray();
	
  
    $paperDetails = [];
    foreach ($questionTypeIds as $questionTypeId) {
        $paperDetails[$questionTypeId] = PaperDetail::where('paper_id', $id)->where('questiontype_id', $questionTypeId)->get();
    }
   */

   $groupedBySection = $paperdetail->groupBy('question_section'); 
  
    $sectionData = [];
	$url = url('/');
    foreach ($groupedBySection as $section => $details) {
		$questionTypeIds = $details->groupBy('questiontype_id');
		
        $sectionData[$section] = [];
        foreach ($questionTypeIds as $questionTypeId => $questions) {
            $sectionData[$section][$questionTypeId] = $questions;
        }
	}
		$html = view('admin.paper.paperpdf', [
			'sitesetting' => $sitesetting,
			'admin'=> $admin,
			'paper'=> $paper,
			'sectionData'=> $sectionData,
			'totalmark'=> $totalmark,
			'url'=> $url,
			/*'default_font'=> 'hindi' */
		])->render();
		$html = mb_convert_encoding($html, 'UTF-8', 'UTF-8');
		

		
		
		try {
			$pdf = PDF::loadHTML($html);
			$pdf->showImageErrors = true;  // Show image errors directly in the PDF

			return $pdf->stream('test.pdf');
		} catch (\Mpdf\MpdfException $e) {
			dd($e->getMessage());  // Dump the error to check for issues
		}

/*
IMPORTANT WORKING
$pdf = PDF::loadHTML($html, [], [
			'margin_left'   => 5,
			'margin_right'  => 5,
			'margin_top'    => 5,
			'margin_bottom' => 5,
			'title'         => 'Paper Pdf For ',
		]);*/
		
		
		/*$pdf = PDF::loadView('admin.paper.paperpdf',['sitesetting'=>$sitesetting,'admin'=>$admin,'paper'=>$paper,'sectionData'=>$sectionData,'totalmark'=>$totalmark,'url'=>$url],[],[
			'margin_left'          => 5,
			'margin_right'         => 5,
			'margin_top'           => 5,
			'margin_bottom'        => 5,
			'title' => 'Paper Pdf For ',
			
				]);*/
		$filename = str_replace('/','-','123121').'.pdf';
         
    return response()->stream($pdf->stream($filename), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="' . $filename . '"',
    ]);
	}
}
