<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Media;
use App\Setting;
use DB,Input;
use Request;
use Response;
use URL;
use View;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Routing\Controller as BaseController;

class DownloadController extends BaseController {

	public function index($id){
		$images   = DB::table('media')->where("id", "=", $id)->get();
		$popular  = DB::table('media')->orderBy('count_download', 'DESC')->take(5)->get();
		$mostlike = DB::table('media')->orderBy('count_like', 'DESC')->take(5)->get();
		$alsolike = DB::table('media')->orderByRaw("RAND()")->where("id", "!=", $id)->take(3)->get();
		$settings = Setting::first();
		$previous = DB::table('media')->where('id', '<', $id)->max('id');
		$next     = DB::table('media')->where('id', '>', $id)->min('id');
		$imgshare = DB::table('media')->where("id", "=", $id)->first();
		return view('download.downloadpage', ['images'=>$images , 'popular'=>$popular, 'mostlike'=>$mostlike, 'alsolike'=>$alsolike, 'settings'=>$settings, 'previous'=>$previous, 'next'=>$next, 'imgshare'=>$imgshare]);
	}

	public function countdownload($id){
		$imgdownload = Media::where("id", "=", $id)->first();
		$imgdownload->count_download = $imgdownload->count_download + 1;
		$imgdownload->time_download = date('Y-m-d H:i:s');
		$imgdownload->save();
		echo $imgdownload->count_download;
	}

	public function download($id){
		$imgdownload = DB::table('media')->where("id", "=", $id)->first();
		//$filepath 	 = public_path('files\downloads\images') . "\\" . $imgdownload->name;
		if ($imgdownload->typeFile == 'file') {			
			$filepath 	 = config('view.downloadfilepath') . $imgdownload->file;
			return response()->download($filepath);
		} elseif ($imgdownload->typeFile == 'url') {
			$filepath 	 = $imgdownload->file;
			return Redirect::to($filepath);
			//return header("Location:".$filepath);
		}
	}
	public function afterdownload($id, $page = 0){
		$images 	= DB::table('media')->where("id", "!=", $id)->offset($page*12)->take(12)->orderBy('created_at', 'DESC')->get();
		$imghidden  = DB::table('media')->where("id", "=", $id)->get();
		return view('download.afterdownload', ['images'=>$images, 'imghidden'=>$imghidden]);
	}
	public function loadmore($pageNumber){
		$id = Input::get("post_id");
		$page = config('view.numPage');
		$pageNumber = $pageNumber;
		$offset = ($pageNumber - 1) * $page;
		return view('partials.loadmore_download', ['page'=>$page, 'pageNumber'=>$pageNumber, 'offset'=>$offset, 'id'=>$id]);
	}
}