<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use Validator;
use App\Model\Paper;
use App\Model\PaperDetail;
use App\Model\QuestionDetail;
use App\Model\PreviousPaper;
use App\User;
class PaperController extends Controller {
	
    public function __construct() {
    }
	
    public function savepaper(Request $request) {
        $auth = User::where('api_token', $request['api_token'])->whereNotNull('api_token')->first();
        if (!empty($auth)) {
            $validator = Validator::make($request->all(), ['name_of_instiute' => 'required', 'standard' => 'required', 'marks' => 'required', ]);
            if ($validator->fails()) {
                $response['result'] = "2";
                $response['message'] = $validator->errors()->first();
                return Response::json($response);
            }
            $record = new Paper;
            $record->uid = $auth->id;
            $record->name_of_instiute = $request->name_of_instiute;
            $record->standard = $request->standard;
            $record->type_of_test = $request->type_of_test;
            $record->marks = $request->marks;
            $record->date = $request->date;
            $record->time = $request->time;
            $record->instruction = $request->instruction;
            $record->solution = $request->solution;
            $record->omr_sheet = $request->omr_sheet;
            $record->set_watermark = $request->set_watermark;
            $record->footer = $request->footer;
            $record->board_id = $request->board_id;
            $record->medium_id = $request->medium_id;
            $record->standard_id = $request->standard_id;
            $record->subject_id = $request->subject_id;
            $record->chapter_id = $request->chapter_id;
            $record->paperstyle_id = $request->paperstyle_id;
            $record->chapter_name = $request->chapter_name;
            $record->save();
            $question = json_decode($request['question']);
            foreach ($question->question_data as $q) {
                if ($q->type == 'OR') {
                    $array = explode('~', $q->qid);
                    $random = rand(99999, 999999);
                    $questiondetail3 = QuestionDetail::with(['paperstyle'])->where('id', $array[0])->first();
                    $questiondetail4 = QuestionDetail::with(['paperstyle'])->where('id', $array[1])->first();
                    $record3 = new PaperDetail;
                    $record3->paper_id = $record->id;
                    $record3->qdid = $array[0];
                    $record3->type = 'OR' . $random;
                    $record3->mark = $questiondetail3->paperstyle->mark;
                    $record3->save();
                    $record4 = new PaperDetail;
                    $record4->paper_id = $record->id;
                    $record4->qdid = $array[1];
                    $record4->type = 'OR' . $random;
                    $record4->mark = $questiondetail4->paperstyle->mark;
                    $record4->save();
                } else if ($q->type == 'AND') {
                    $array = explode('~', $q->qid);
                    $random = rand(99999, 999999);
                    $questiondetail5 = QuestionDetail::with(['paperstyle'])->where('id', $array[0])->first();
                    $record5 = new PaperDetail;
                    $record5->paper_id = $record->id;
                    $record5->qdid = $array[0];
                    $record5->type = 'AND' . $random;
                    $record5->mark = ($questiondetail4->paperstyle->mark / 2);
                    $record5->save();
                    $record6 = new PaperDetail;
                    $record6->paper_id = $record->id;
                    $record6->qdid = $array[1];
                    $record6->type = 'AND' . $random;
                    $record6->mark = ($questiondetail4->paperstyle->mark / 2);
                    $record6->save();
                } else {
					$questiondetail = QuestionDetail::with(['paperstyle'])->where('id', $q->qid)->first();
                    $record2 = new PaperDetail;
                    $record2->paper_id = $record->id;
                    $record2->qdid = $q->qid;
                    $record2->mark = $questiondetail->paperstyle->mark;
                    $record2->save();
                }
            }
            $paper = Paper::with(['subject','chapter'])->where('id', $record->id)->first();
            $query = PaperDetail::with(['question'])->where('paper_id', $record->id)->orderBy('paper_id', 'ASC')->orderBy('sequence', 'ASC');
            $paperdetail = $query->paginate(15);
            $paperdetail->appends($request->all());
            $response['result'] = '1';
            $response['message'] = 'Successfully Save.';
            $response['paper'] = $paper;
            $response['paperdetail'] = $paperdetail;
        } else {
            $response['result'] = '0';
            $response['message'] = 'Invalid authentication.';
        }
        return Response::json($response);
    }
	
    public function updatepaper(Request $request) {
        $auth = User::where('api_token', $request['api_token'])->whereNotNull('api_token')->first();
        if (!empty($auth)) {
            $question = json_decode($request['question']);
            foreach ($question->question_data as $q) {
                $paperdetail = PaperDetail::where('id', $q->id)->first();
                $paperdetail->mark = $q->mark;
                $paperdetail->sequence = $q->sequence;
                $paperdetail->save();
            }
            $paper = Paper::with(['subject','chapter'])->where('id', $request['paper_id'])->first();
            $paper->marks = $request['mark'];
            $paper->status = 1;
            $paper->save();
            $query = PaperDetail::with(['question'])->where('paper_id', $request['paper_id'])->orderBy('sequence', 'ASC');
            $paperdetail = $query->get();
            $response['result'] = '1';
            $response['message'] = 'Successfully Update.';
            $response['user'] = $auth;
            $response['paper'] = $paper;
            $response['paperdetail'] = $paperdetail;
        } else {
            $response['result'] = '0';
            $response['message'] = 'Invalid authentication.';
        }
        return Response::json($response);
    }
	
    public function mydownload(Request $request) {
        $auth = User::where('api_token', $request['api_token'])->whereNotNull('api_token')->first();
        if (!empty($auth)) {
            $query = Paper::with(['paperdetail','subject','chapter'])->where('uid', $auth->id)->where('status', 1);
            $paper = $query->paginate(15);
            $paper->appends($request->all());
            $response['result'] = '1';
            $response['message'] = 'Success.';
            $response['user'] = $auth;
            $response['paper'] = $paper;
        } else {
            $response['result'] = '0';
            $response['message'] = 'Invalid authentication.';
        }
        return Response::json($response);
    }
	
    public function getpreviouspaper(Request $request) {
        $query = PreviousPaper::with(['papertype','medium','standard','subject'])->where('papertype_id', $request->papertype_id);
        $PreviousPaper = $query->paginate(15);
        $PreviousPaper->appends($request->all());
        $response['result'] = '1';
        $response['message'] = 'Success.';
        $response['data'] = $PreviousPaper;
        return Response::json($response);
    }
	
	public function auto_paper_generate(Request $request) {
        $auth = User::where('api_token', $request['api_token'])->whereNotNull('api_token')->first();
        if (!empty($auth)) {
            $validator = Validator::make($request->all(), ['name_of_instiute' => 'required', 'standard' => 'required', 'type_of_test' => 'required', 'marks' => 'required', 'date' => 'required', 'time' => 'required', ]);
            if ($validator->fails()) {
                $response['result'] = "0";
                $response['message'] = $validator->errors()->first();
                return Response::json($response);
            }
			
            $record = new Paper;
            $record->uid = $auth->id;
            $record->name_of_instiute = $request->name_of_instiute;
            $record->standard = $request->standard;
            $record->type_of_test = $request->type_of_test;
            $record->marks = $request->marks;
            $record->date = $request->date;
            $record->time = $request->time;
            $record->instruction = $request->instruction;
            $record->solution = $request->solution;
            $record->omr_sheet = $request->omr_sheet;
            $record->set_watermark = $request->set_watermark;
            $record->footer = $request->footer;
            $record->board_id = $request->board_id;
            $record->medium_id = $request->medium_id;
            $record->standard_id = $request->standard_id;
            $record->subject_id = $request->subject_id;
            $record->chapter_id = $request->chapter_id;
            $record->paperstyle_id = $request->paperstyle_id;
            $record->chapter_name = $request->chapter_name;
			$record->status = 1;
            $record->save();
			
            $mark_obj = json_decode($request['mark_obj']);
            foreach ($mark_obj->mark_data as $key=>$q) {
				$k = $key+1;
				$m='Mark'.$k;
				if($q->$m > 0){
				$questiondetail = QuestionDetail::with(['paperstyle'])->where('paperstyle_id', $k)->inRandomOrder()->limit($q->$m)->get();
					foreach($questiondetail as $qd){
						$record2 = new PaperDetail;
						$record2->paper_id = $record->id;
						$record2->qdid = $qd->id;
						$record2->mark = $qd->paperstyle->mark;
						$record2->save();
					}
				}
            }
            $paper = Paper::with(['subject','chapter'])->where('id', $record->id)->first();
            $paperdetail = PaperDetail::with(['question'])->where('paper_id', $record->id)->get();
            $response['result'] = '1';
            $response['message'] = 'Successfully Save.';
			$response['user'] = $auth;
            $response['paper'] = $paper;
            $response['paperdetail'] = $paperdetail;
        } else {
            $response['result'] = '0';
            $response['message'] = 'Invalid authentication.';
        }
        return Response::json($response);
    }
	
	public function deletepaper(Request $request) {
		if(!empty($request->id)){
			$ids=explode(',',$request->id);
			if(count($ids) > 0){
				foreach($ids as $id){
					$paper = Paper::where('id',$id)->first();
					if (!empty($paper)) {
						PaperDetail::where('paper_id',$paper->id)->delete();
						$paper->delete();
					}
					/**/
					$response['result'] = '1';
					$response['message'] = 'Delete Successfully.';
				}
			}
			else{
				$response['result'] = '2';
				$response['message'] = 'Not Paper Available.';
			}
		}
		else{
			$response['result'] = '2';
			$response['message'] = 'Not Paper Available.';
		}
        return Response::json($response);
    }
}
