<?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 App\Model\Contribute;
use App\Model\ContributeDetail;
use App\User;

class ContributeController extends Controller
{
    
    public function __construct()
    {
        //$this->middleware('auth');
    }
	
	public function save_contribute(Request $request)
    {
		$auth = User::where('api_token', $request['api_token'])->whereNotNull('api_token')->first();
		if (!empty($auth)) {
			if($request->image != ''){
				
				$contribute = Contribute::where('uid',$auth->id)->first();
					
				if(!empty($contribute)){
					$contributedetail = ContributeDetail::where('contribute_id',$contribute->id)->get();
					foreach($contributedetail as $c){
						 $this->deleteFile($c,'image',false);
						 $c->delete();
					}
					$contribute->delete();
				}	
				
				$record = new Contribute;
				$record->uid = $auth->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->mark = $request->mark;
				$record->save();
			    
				$files = $request->image;
				
					foreach($files as $file) {
						$record2 = new ContributeDetail;    
						$filename = $this->uploadmultipleFile($file, null, 'image', 'contribute', false, 650);
						$record2->contribute_id = $record->id;
						$record2->image = $filename;
						$record2->save();
					}
			}
			$response['result'] = '1';
			$response['message'] = 'Successfully Save.';
			
		}
		else {
            $response['result'] = '0';
            $response['message'] = 'Invalid authentication.';
		}
        return Response::json($response);
    }

}
