<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Media;
use App\Http\Controllers\AdminController;
use App\Aws\FileSystem;
use Illuminate\Support\Facades\Schema;
use DB;
use Session;

class MediaController extends AdminController {

    private $title = "media";
    private $action = "media";
    private $folder = "media";
    private $heading = "media";

    public function __construct() {
        $this->middleware('auth');

        $this->breadcrumbs = $this->getBreadcrumbs();
        $this->breadcrumbs[1]['link'] = "admin/" . $this->action;
        $this->breadcrumbs[1]['name'] = $this->title;
    }

    public function index() {

        $model = Media::orderBy("id", "desc")->paginate(12);

        $data["pageHeader"] = false;
        $data["model"] = $model;
        $data["activeClass"] = "grid-view";

        $data["title"] = $this->title;
        $data["folder"] = $this->folder;
        $data["action"] = $this->action;
        $data["heading"] = $this->heading;
        $data["SubTitle"] = "List";
        $data['breadcrumbs'] = $this->breadcrumbs;

        return view('admin/media/index', $data);
    }

    public function create(Request $request) {

        $data["model"] = new Media();
        $data["title"] = $this->title;
        $data["folder"] = $this->folder;
        $data["action"] = $this->action;
        $data["heading"] = $this->heading;
        $data["SubTitle"] = "Create";
        $data['breadcrumbs'] = $this->breadcrumbs;


        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Create";

        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/media/create', $data);
    }

    public function save(Request $request) {

        $rules = [
            'file' => 'required',
        ];
        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {
            $file = $request->file('file');
            unset($input["_token"]);
//            if ($request->hasFile('file')) {
//
//                $model = new Media();
//                $fileName = $file->getClientOriginalName();
//                $extension = $file->getClientOriginalExtension();
//
//                $input['file'] = FileSystem::storeImage($fileName, $file, 'uploads/' . $this->folder . '/', 'uploads/' . $this->folder . '/thumbnails/', 206, 172);
//                $input["type"] = $extension;
//                $input["fileName"] = rand(111, 999) . time();
//                $input["category"] = "media";
//                $input["created_at"] = date("Y-m-d H:i:s");
//
//                $id = $model->insertGetId($input);
//            }
              if ($request->hasFile('file')) {

                $model = new Media();
                $fileName = rand(111, 999) . time();
                $extension = $file->getClientOriginalExtension();
                $originalName = $file->getClientOriginalName();
                $base = basename($originalName, '.'.$extension);
                $input["fileName"]=$fileName;
                $media=Media::where('file',$originalName)->first();
//                $count=count($media);
                
              
                   if(!empty($media)){
                        $count=1;
                    while($count>0){
                       
                       $media2=Media::where('file',$base."-". $count.'.'.$extension)->first();
                        if(!empty($media2)){
                            $count++;
                        }else{
                            $originalName=$base."-". $count.'.'.$extension;
                            $input["file"] = $originalName;
                            $count= 0;
                        }
                       
                    }
                                    
                    }else{
                        $input["file"] = $originalName;
                        $count=0;
                    }
         
                $input['file'] = FileSystem::storeImage($originalName, $file, 'uploads/' . $this->folder . '/', 'uploads/' . $this->folder . '/thumbnails/', 206, 172);
                $input["type"] = $extension;
                
                $input["category"] = 'media';
                $input["created_at"] = date("Y-m-d H:i:s");
                $id = $model->insertGetId($input);
            }
            
           


            \Session::flash('success', 'Media added successfully!');
            return redirect('admin/media');
        }
    }

    public function edit($id) {
//        $haveImageId=array();
//        $data=array();
//        $tables = DB::select('SHOW TABLES');
//        foreach($tables as $table){
//            
//            $columns = Schema::getColumnListing($table->Tables_in_trafeka); // users table
//            foreach ($columns as $col){
//                if("image_media_id"==$col || "media_id"==$col){
//                   $haveImageId[]=array("tableName"=>$table->Tables_in_trafeka,"colName"=>$col);
//                }
//                
//            }
//
//        }
//        foreach ($haveImageId as $table){
//          $data[]= Media::join($table["tableName"].' as t','media.id','=','t.image_media_id' )->get();  
//        }
//        dd($data[0][0]['category']); // dump the result and die




        $data['model'] = Media::find($id);
        $data["title"] = $this->title;
        $data["folder"] = $this->folder;
        $data["action"] = $this->action;
        $data["heading"] = $this->heading;
        $data["SubTitle"] = "Edit";
        $data['breadcrumbs'] = $this->breadcrumbs;

        return view('admin/media/edit', $data)->with('id', $id);
    }

    public function update($id, Request $request) {

        $rules = [
        ];
        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {
            $file = $request->file('file');
            unset($input["_token"]);

            $category = isset($input["media_action"]) ? $input["media_action"] : "page";

            
//             if ($request->hasFile('file')) {
// 
//                $model = new Media();
//                $fileName = $file->getClientOriginalName();
//                $extension = $file->getClientOriginalExtension();
//                
//             
//                $input['file'] = FileSystem::storeImage($fileName, $file, 'uploads/' . $this->folder . '/', 'uploads/' . $this->folder . '/thumbnails/', 206, 172);
//                $input["type"] = $extension;
//                $input["fileName"] = rand(111, 999) . time();
//                $input["category"] = $category;
//            
//            }
            
            if ($request->hasFile('file')) {

                $model = new Media();
                $fileName = rand(111, 999) . time();
                $extension = $file->getClientOriginalExtension();
                $originalName = $file->getClientOriginalName();
                $base = basename($originalName, '.'.$extension);
                $input["fileName"]=$fileName;
                $media=Media::where('file',$originalName)->first();
//                $count=count($media);
                
              
                   if(!empty($media)){
                        $count=1;
                    while($count>0){
                       
                       $media2=Media::where('file',$base."-". $count.'.'.$extension)->first();
                        if(!empty($media2)){
                            $count++;
                        }else{
                            $originalName=$base."-". $count.'.'.$extension;
                            $input["file"] = $originalName;
                            $count= 0;
                        }
                       
                    }
                                    
                    }else{
                        $input["file"] = $originalName;
                        $count=0;
                    }
         
                $input['file'] = FileSystem::storeImage($originalName, $file, 'uploads/' . $this->folder . '/', 'uploads/' . $this->folder . '/thumbnails/', 206, 172);
                $input["type"] = $extension;
                
                $input["category"] = 'media';
            }

  
            $input["updated_at"] = date("Y-m-d H:i:s");
            Media::where('id', '=', $id)->update($input);



            \Session::flash('message', 'Media updated successfully!');
            return redirect('admin/media');
        }
    }

    public function delete($id) {

        Media::where('id', $id)->delete();

        \Session::flash('error', 'Media deleted successfully!');
        return redirect('admin/media');
    }

    public function show($id) {

        $q = new Media();
        $data['model'] = $q->find($id);
        $data["title"] = $this->title;
        $data["folder"] = $this->folder;
        $data["action"] = $this->action;
        $data["heading"] = $this->heading;

        $data["SubTitle"] = "Show";
        $data["tours"] = Media::first();


        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = $data['model']->title;

        $data['breadcrumbs'] = $this->breadcrumbs;

        return view('admin/media/show', $data);
    }

    
    
     public function upload(Request $request) {

        $input = $request->all();
        $validator = Validator::make($request->all(), ['file' => 'required']);

        if ($validator->fails()) {
            $errors = $validator->errors();
            $response['errors'] = $errors;
            $response['error'] = true;
            $header = 402;
        } else {

            $category = isset($input["media_action"]) ? $input["media_action"] : "page";

            unset($input["_token"]);
            unset($input["media_action"]);


            $file = $request->file('file');

            if ($request->hasFile('file')) {

                $model = new Media();
                $fileName = rand(111, 999) . time();
                $extension = $file->getClientOriginalExtension();
                $originalName = $file->getClientOriginalName();
                $base = basename($originalName, '.'.$extension);
                $input["fileName"]=$fileName;
                $media=Media::where('file',$originalName)->first();
//                $count=count($media);
                
              
                   if(!empty($media)){
                        $count=1;
                    while($count>0){
                       
                       $media2=Media::where('file',$base."-". $count.'.'.$extension)->first();
                        if(!empty($media2)){
                            $count++;
                        }else{
                            $originalName=$base."-". $count.'.'.$extension;
                            $input["file"] = $originalName;
                            $count= 0;
                        }
                       
                    }
                                    
                    }else{
                        $input["file"] = $originalName;
                        $count=0;
                    }
         
                $input['file'] = FileSystem::storeImage($originalName, $file, 'uploads/' . $this->folder . '/', 'uploads/' . $this->folder . '/thumbnails/', 206, 172);
                $input["type"] = $extension;
                
                $input["category"] = $category;
                $input["created_at"] = date("Y-m-d H:i:s");
                $id = $model->insertGetId($input);
            }
            list($width, $height, $type, $attr) = getimagesize(public_path(Config("params.media_path.large"))."".$input['file']); 
            if($input['type']!='svg'){
			list($width2, $height2, $type2, $attr2) = getimagesize(public_path(Config("params.media_path.thumbnail"))."".$input['file']); 
			}

            //\Session::flash('success', 'Missions added successfully!');
            $response["type"] = $input['type'];
            $response["file"] = $input['file'];
			$response["fileName"] = $input['fileName'];
			$response["title"] = "No Title";
			$response["category"] = $input['category'];
			$response["description"] = "No description";
			$response["dimensions"]=$width."x".$height;
                        if($input['type']!='svg'){
                            $response["thumbnailsDimensions"]=$width2."x".$height2;
                        }
            $response["id"] = $id;
            $header = 200;
            $response['error'] = false;
        }

        return response()->json($response, $header);
    }

    public function get(Request $request) {

        $search = "";

        //d($request->all());
        if (isset($request->search)) {

            $search = $request->search;
            //d($search,1);
        }
        $model = Media::orderBy("id", "desc");

        if ($search != "") {
            $model = $model->where('title', "like", "%" . $search . "%")
                    ->orWhere('description', "like", "%" . $search . "%")
                    ->orWhere('fileName', "like", "%" . $search . "%")
                    ->orWhere('category', "like", "%" . $search . "%");
        }


        if (isset($_GET["page"])) {
            //die($search);
        }

        $model = $model->paginate(5);

        $data["pageHeader"] = false;
        $data["model"] = $model;
        $data["title"] = $this->title;
        $data["folder"] = $this->folder;
        $data["action"] = $this->action;
        $data["heading"] = $this->heading;
        $data["SubTitle"] = "List";
        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/' . $this->folder . '/modal', $data);
    }

    public function searchData(Request $request) {



        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $search = $_GET['search'];

            $model = Media::where('title', "like", "%" . $search . "%")
                            ->orWhere('description', "like", "%" . $search . "%")
                            ->orWhere('fileName', "like", "%" . $search . "%")
                            ->orWhere('category', "like", "%" . $search . "%")->paginate(12);

            $data["activeClass"] = $_GET['activeClass'];
            $data["pageHeader"] = false;
            $data["model"] = $model;
            $data["title"] = $this->title;
            $data["folder"] = $this->folder;
            $data["action"] = $this->action;
            $data["heading"] = $this->heading;
            $data["SubTitle"] = "List";
            $data['breadcrumbs'] = $this->breadcrumbs;

//         $response["message"] = "Hotels added successfully!";
//        $response["data"] = $data;
//            $header = 200;
//            $error = false;
//      d($_GET['sessionTest'],1);


            return view('admin/media/index', $data);
        } else {
            return redirect()->back()->withErrors("Search required");

//            $response['error'] = true;
//            $header = 402;
        }
//           return response()->json($response, $header);
    }

}
