<?php

namespace App\Http\Controllers;

use App\News;
use App\Section;
use App\Event;
use App\Page;
use App\Home;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Auth;
use App\Notifications\FacebookPost;
use App\Notifications\TwitterPost;
class NewsController extends Controller
{

    protected $rules = [
        //'section_id' => ['required']
        'title' => ['required'],
        //'page_id' => ['required'],
    ];

    public function index(Request $request)
    {

        // Se stavo modificando una news metto a null il campo
        if ($request->session()->has('current_news')) {
            $news_id = session('current_news', 0);
            if ($news_id > 0)
            {
                $n = News::where('id', '=', $news_id)->take(1000)->get();
                if ($n->count() > 0)
                {
                    $n = $n->first();
                    if ($n->user_id == Auth::user()->id)
                    {
                        $n->user_id = null;
                        $n->save();
                    }
                }
                $request->session()->forget('current_news');
            }
        }

        $news = News::orderBy('date', 'DESC')->take(1000)->get();//->paginate(50);

        return view('news.index',compact('news'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    public function load_json()
    {
        $start = $_GET["start"];
        $end = 50;//$_GET["length"];
        $total = News::count();
        $filtered = $total;

        $sort_by = '';
        $sort = $_GET["order"][0]["column"];
        switch ($sort) {
            case '0':
                $sort_by = 'date';
                break;
            case '2':
                $sort_by = 'title';
                break;
            case '3':
                $sort_by = 'name';
                break;
            case '4':
                $sort_by = 'name';
                break;
            case '5':
                $sort_by = 'name';
                break;
            case '6':
                $sort_by = 'title';
                break;
            case '7':
                $sort_by = 'online';
                break;
            case '8':
                $sort_by = 'clicks';
                break;
            default:
                $sort_by = 'date';
                break;
        }
        $sort_by_dir = $_GET["order"][0]["dir"];


        $search = $_GET["search"]["value"];

        if ($sort == '3')
        {
            $news = News::with(['section' => function ($query) use ($sort_by, $sort_by_dir) {
                $query->orderBy($sort_by, $sort_by_dir);
            }]);
        }
        else if ($sort == '4')
        {
            $news = News::with(['region_1' => function ($query) use ($sort_by, $sort_by_dir) {
                $query->orderBy($sort_by, $sort_by_dir);
            }]);
        }
        else if ($sort == '5')
        {
            $news = News::with(['region_2' => function ($query) use ($sort_by, $sort_by_dir) {
                $query->orderBy($sort_by, $sort_by_dir);
            }]);
        }
        else if ($sort == '6')
        {
            $news = News::with(['event' => function ($query) use ($sort_by, $sort_by_dir) {
                $query->orderBy($sort_by, $sort_by_dir);
            }]);
        }
        else
            $news = News::orderBy($sort_by, $sort_by_dir);

        if ($search != '')
        {
            $news = $news->where('title', 'LIKE', '%' . $search . '%');
            $filtered = $news->count();
        }

        $news = $news->limit($end)->offset($start)->get();//->paginate(50);

        $aData = array();
        foreach($news as $n)
        {
            $x = array();
            $x[] = $n->date;
            if ($n->image != '')
                $x[] = '<img src="/files/news/' . $n->image . '" style="max-width:100px" />';
            else
                $x[] = '';
            $x[] = $n->title;
            $section = @$n->section->name;
            if($n->section)
                $section .= '<br>' . isset($n->section) ? $n->section->position($n->id) : '';
            $x[] = $section;
            $region_1 = @$n->region_1->name;
            if($n->region_1)
                $region_1 .= '<br>' . isset($n->region_1) ? $n->region_1->position($n->id) : '';
            $x[] = $region_1;
            $region_2 = @$n->region_2->name;
            if($n->region_2)
                $region_2 .= '<br>' . isset($n->region_2) ? $n->region_2->position($n->id) : '';
            $x[] = $region_2;
            //$x[] = @$n->event->title;
            $x[] = @$n->online ? '<a si class="btn btn-w-m btn-default" href="/admin/news/status/' . $n->id . '/offline">&nbsp;Si&nbsp;</a>' : '<a no class="btn btn-w-m btn-default" href="/admin/news/status/' . $n->id . '/online">No</a>';
            $x[] = @$n->clicks;
            $x[] = '<a href="/admin/news/duplicate/' . $n->id . '" type="button" class="btn btn-w-m btn-primary"><i class="fa fa-clone" aria-hidden="true"></i></a>';
            $x[] = '<a href="/admin/news/' . $n->id . '/edit" type="button" class="btn btn-w-m btn-primary"><i class="fa fa-pencil" aria-hidden="true"></i></a>';
            $form = '<form method="POST" action="/admin/news/' . $n->id . '" accept-charset="UTF-8" class="form-inline">
                <input name="_method" type="hidden" value="DELETE">
                <input name="_token" type="hidden" value="' . csrf_token() . '">
                <button type="submit" class="btn btn-w-m btn-danger" onclick="return confirm(\'Sei sicuro?\')"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
            </form>';
            $x[] = $form;
            $aData[] = $x;
        }
        $aRet = array('recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $aData);
        return json_encode($aRet);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        $sections = Section::where('type', '=', 'section')->orderBy('position')->pluck('name', 'id')->toArray();;
        $regions = Section::where('type', '=', 'region')->orderBy('name')->pluck('name', 'id')->toArray();;
        $layouts = Section::pluck('layout', 'id')->toArray();
        $events = Event::orderBy('title')->pluck('title', 'id')->toArray();;
        $pages = Page::where('online', '=', true)->orderBy('title')->pluck('title', 'id')->toArray();;

        $section_position = '';
        $region_1_position = '';
        $region_2_position = '';

        $first = '';
        $aFirst = array();
        $home = Home::first();
        if ($home != null)
        {
            $pos = '';
            $home->loadData();
            if (isset($home->slide1) && $home->slide1 != '')
                $aFirst[] = $home->slide1->title . " (immagine grande)";
            for($a=1;$a<=5;$a++)
            {
                if (isset($home["left" . $a]) && $home["left" . $a] != '')
                    $aFirst[] = $home["left" . $a]["title"] . " (slide sinistra)";
            }
            for($a=1;$a<=5;$a++)
            {
                if (isset($home["right" . $a]) && $home["right" . $a] != '')
                    $aFirst[] = $home["right" . $a]["title"] . " (slide destra)";
            }
            $first = '<li>' . implode("</li><li>", $aFirst) . '</li>';
        }

        return view('news.create', compact('sections', 'regions', 'events', 'pages', 'layouts', 'section_position', 'region_1_position', 'region_2_position', 'first'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate($this->rules);

        $input = $request->all();

        if(request()->image)
        {

            $file = request()->image;
            $filename  = time() . '_' . $file->getClientOriginalName();

            if (! File::exists(public_path()."/files/news"))
                File::makeDirectory(public_path()."/files/news");

            $path = public_path('files/news');

            request()->image->move($path, $filename);

            $input["image"] = $filename;

        }
        else
        {
            if (isset($_POST["filename"]))
                $input["image"] = $_POST["filename"];
        }

        for($i=1;$i<=5;$i++)
        {
            if(isset($input["image" . $i]))
            {

                $file = $input["image" . $i];
                $filename  = time() . '_' . $file->getClientOriginalName();

                if (! File::exists(public_path()."/files/news"))
                    File::makeDirectory(public_path()."/files/news");

                $path = public_path('files/news');

                $input["image" . $i]->move($path, $filename);

                $input["image" . $i] = $filename;

            }
        }

        if(request()->pdf)
        {

            $file = request()->pdf;
            $filename  = time() . '_' . $file->getClientOriginalName();

            if (! File::exists(public_path()."/files/news"))
                File::makeDirectory(public_path()."/files/news");

            $path = public_path('files/news');

            request()->pdf->move($path, $filename);

            $input["pdf"] = $filename;

        }

        $final_date = null;
        if ($input["date"] != '')
        {
            list($dt, $time) = explode(" ", $input["date"]);
            list($day, $month, $year) = explode("/", $dt);
            $final_date = $year . "-" . $month . "-" . $day . " " . $time;
        }
        $input["date"] = $final_date;

        $input["online"] = false;
        $input["homepage"] = isset($input["homepage"]) ? ($input["homepage"] == 'on' ? true : false) : false;
        $input["live"] = isset($input["live"]) ? ($input["live"] == 'on' ? true : false) : false;
        $input["breaking_news"] = isset($input["breaking_news"]) ? ($input["breaking_news"] == 'on' ? true : false) : false;

        $news = News::create($input);

        if (isset($input['publish']))
        {
            $news->online = true;
            $news->save();

            // Posiziono la notizia se la data non è
            if ($final_date <= date("Y-m-d H:i:s"))
            {

                if ($_POST["section_position"] != '')
                {
                    $s = Section::findOrFail($input["section_id"]);
                    $s[$_POST["section_position"]] = $news->id;
                    $s->save();
                    $news->section_position = '';

                }
                if ($_POST["region_1_position"] != '')
                {
                    $s = Section::findOrFail($input["region_1_id"]);
                    $s[$_POST["region_1_position"]] = $news->id;
                    $s->save();
                    $news->region_1_position = '';
                }
                if ($_POST["region_2_position"] != '')
                {
                    $s = Section::findOrFail($input["region_2_id"]);
                    $s[$_POST["region_2_position"]] = $news->id;
                    $s->save();
                    $news->region_2_position = '';
                }

            }
            if (isset($input['no_social']))
            {
            }
            else
            {
                @$news->notify(new FacebookPost());
                $news->notify(new TwitterPost());
                $news->published = true;
                $news->save();
            }

        }
        if (isset($input['unpublish']))
        {
            $news->online = false;
            $news->save();
        }

        if ($_POST["homepage_position"] != '' && $news->online)
        {
            $home = Home::first();
            if ($home != null)
            {
                $home->fill([
                    $_POST["homepage_position"] => $news->id
                ]);
                $home->save();
            }
        }

        if (isset($input['publish']))
            return redirect()->route('news.index')->with('success','News updated successfully');

        if (isset($input['unpublish']))
            return redirect()->route('news.index')->with('success','News updated successfully');

        if (isset($input['save']))
        {
            return redirect()->route('news.edit', $news->id)->with('success','News updated successfully');
        }
        if (isset($input['save_exit']))
        {
            return redirect()->route('news.index')->with('success','News updated successfully');
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function show(News $news)
    {
        return view('news.show',compact('news'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function edit(News $news)
    {

        // Aggiorno l'utente che sta guardando la news
        if ($news->user_id == null)
        {
            session(['current_news' => $news->id]);
            $news->user_id = Auth::user()->id;
            $news->save();
        }

        $sections = Section::where('type', '=', 'section')->orderBy('position')->pluck('name', 'id')->toArray();;
        $regions = Section::where('type', '=', 'region')->orderBy('name')->pluck('name', 'id')->toArray();;
        $layouts = Section::pluck('layout', 'id')->toArray();
        $events = Event::orderBy('title')->pluck('title', 'id')->toArray();;
        $pages = Page::where('online', '=', true)->orderBy('title')->pluck('title', 'id')->toArray();;
        $final_date = null;
        if ($news->date != null)
        {
            list($dt, $time) = explode(" ", $news->date);
            list($year, $month, $day) = explode("-", $dt);
            $final_date = $day . "/" . $month . "/" . $year . " " . $time;
        }

        $section_position = $news->section_position;
        $region_1_position = $news->region_1_position;
        $region_2_position = $news->region_2_position;
        $first = '';
        $aFirst = array();
        $home = Home::first();
        if ($home != null)
        {
            $pos = '';
            if ($home->slide1 == $news->id)
                $news->homepage_position = "slide1";
            if ($home->left1 == $news->id)
                $news->homepage_position = "left1";
            if ($home->left2 == $news->id)
                $news->homepage_position = "left2";
            if ($home->left3 == $news->id)
                $news->homepage_position = "left3";
            if ($home->right1 == $news->id)
                $news->homepage_position = "right1";
            if ($home->right2 == $news->id)
                $news->homepage_position = "right2";
            if ($home->right3 == $news->id)
                $news->homepage_position = "right3";
            $home->loadData();
            if (isset($home->slide1) && $home->slide1 != '')
                $aFirst[] = $home->slide1->title . " (immagine grande)";
            for($a=1;$a<=5;$a++)
            {
                if (isset($home["left" . $a]) && $home["left" . $a] != '')
                    $aFirst[] = $home["left" . $a]["title"] . " (slide sinistra)";

            }
            for($a=1;$a<=5;$a++)
            {
                if (isset($home["right" . $a]) && $home["right" . $a] != '')
                    $aFirst[] = $home["right" . $a]["title"] . " (slide destra)";
            }
            $first = '<li>' . implode("</li><li>", $aFirst) . '</li>';
        }


        $news->date = $final_date;

        return view('news.edit',compact('news', 'sections', 'regions', 'pages', 'events', 'layouts', 'section_position', 'region_1_position', 'region_2_position', 'first'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, News $news)
    {
        $request->validate($this->rules);

        $input = $request->all();


        $old_section_id = $news->section_id;
        $old_region_1_id = $news->region_1_id;
        $old_region_2_id = $news->region_2_id;
        $old_event_id = $news->event_id;

        $section_position = '';
        if ($news->section_id > 0)
        {
            if ($news->section->big == $news->id)
                $section_position = 'big';
            if ($news->section->small1 == $news->id)
                $section_position = 'small1';
            if ($news->section->small2 == $news->id)
                $section_position = 'small2';
            if ($news->section->small3 == $news->id)
                $section_position = 'small3';
            if ($news->section->small4 == $news->id)
                $section_position = 'small4';
            if ($news->section->small5 == $news->id)
                $section_position = 'small5';
            if ($news->section->small6 == $news->id)
                $section_position = 'small6';

            if ($section_position == null)
                $section_position = $news->section_position;


        }
        $region_1_position = '';
        if ($news->region_1_id > 0)
        {
            if ($news->region_1->big == $news->id)
                $region_1_position = 'big';
            if ($news->region_1->small1 == $news->id)
                $region_1_position = 'small1';
            if ($news->region_1->small2 == $news->id)
                $region_1_position = 'small2';
            if ($news->region_1->small3 == $news->id)
                $region_1_position = 'small3';
            if ($news->region_1->small4 == $news->id)
                $region_1_position = 'small4';
            if ($news->region_1->small5 == $news->id)
                $region_1_position = 'small5';
            if ($news->region_1->small6 == $news->id)
                $region_1_position = 'small6';

            if ($region_1_position == '')
                $region_1_position = $news->region_1_position;

        }
        $region_2_position = '';
        if ($news->region_2_id > 0)
        {
            if ($news->region_2->big == $news->id)
                $region_2_position = 'big';
            if ($news->region_2->small1 == $news->id)
                $region_2_position = 'small1';
            if ($news->region_2->small2 == $news->id)
                $region_2_position = 'small2';
            if ($news->region_2->small3 == $news->id)
                $region_2_position = 'small3';
            if ($news->region_2->small4 == $news->id)
                $region_2_position = 'small4';
            if ($news->region_2->small5 == $news->id)
                $region_2_position = 'small5';
            if ($news->region_2->small6 == $news->id)
                $region_2_position = 'small6';

            if ($region_2_position == '')
                $region_2_position = $news->region_2_position;

        }

        if ($old_section_id == $input["section_id"] && $section_position == $input["section_position"])
            unset($input["section_position"]);

        if ($old_region_1_id == $input["region_1_id"] && $region_1_position == $input["region_1_position"])
            unset($input["region_1_position"]);

        if ($old_region_2_id == $input["region_2_id"] && $region_2_position == $input["region_2_position"])
            unset($input["region_2_position"]);

        if(request()->image)
        {

            $file = request()->image;
            $filename  = time() . '_' . $file->getClientOriginalName();

            if (! File::exists(public_path()."/files/news"))
                File::makeDirectory(public_path()."/files/news");

            $path = public_path('files/news');

            request()->image->move($path, $filename);

            $input["image"] = $filename;

        }
        for($i=1;$i<=5;$i++)
        {
            if(isset($input["image" . $i]))
            {

                $file = $input["image" . $i];
                $filename  = time() . '_' . $file->getClientOriginalName();

                if (! File::exists(public_path()."/files/news"))
                    File::makeDirectory(public_path()."/files/news");

                $path = public_path('files/news');

                $input["image" . $i]->move($path, $filename);

                $input["image" . $i] = $filename;

            }
        }

        if (isset($input["remove_pdf"]))
        {
            $input["pdf"] = '';
        }
        if(request()->pdf)
        {

            $file = request()->pdf;
            $filename  = time() . '_' . $file->getClientOriginalName();

            if (! File::exists(public_path()."/files/news"))
                File::makeDirectory(public_path()."/files/news");

            $path = public_path('files/news');

            request()->pdf->move($path, $filename);

            $input["pdf"] = $filename;

        }

        $final_date = null;
        if ($input["date"] != '')
        {
            list($dt, $time) = explode(" ", $input["date"]);
            list($day, $month, $year) = explode("/", $dt);
            $final_date = $year . "-" . $month . "-" . $day . " " . $time;
        }
        $input["date"] = $final_date;

        // $input["online"] = isset($input["online"]) ? ($input["online"] == 'on' ? true : false) : false;
        $input["homepage"] = isset($input["homepage"]) ? ($input["homepage"] == 'on' ? true : false) : false;
        $input["live"] = isset($input["live"]) ? ($input["live"] == 'on' ? true : false) : false;
        $input["breaking_news"] = isset($input["breaking_news"]) ? ($input["breaking_news"] == 'on' ? true : false) : false;

        $news->update($input);

        $news->user_id = null;
        $news->save();
        $request->session()->forget('current_news');

        if (isset($input['publish']))
        {

            $news->online = true;
            $news->save();

            if (isset($input['no_social']))
            {
                // Non pubblico sui social
            }
            else
            {

                $news->published = true;
                $news->save();
            }

        }
        if (isset($input['unpublish']))
        {
            $news->online = false;

            $news->save();
        }

        if ($_POST["homepage_position"] != '' && $news->online)
        {
            $home = Home::first();
            if ($home != null)
            {
                $home->fill([
                    $_POST["homepage_position"] => $news->id
                ]);
                $home->save();
            }
        }

        if ($news->event_id != $old_event_id)
        {
            $e = Event::where('id', '=', $old_event_id)->first();
            if ($e)
            {
                if ($e->big == $news->id)
                    $e->big = '';
                if ($e->small1 == $news->id)
                    $e->small1 = '';
                if ($e->small2 == $news->id)
                    $e->small2 = '';
                if ($e->small3 == $news->id)
                    $e->small3 = '';
                if ($e->small4 == $news->id)
                    $e->small4 = '';
                $e->save();
            }
        }

        if (isset($input['publish']))
        {

            return redirect()->route('news.index')->with('success','News updated successfully');
        }
        if (isset($input['crop']))
        {
            return redirect('/admin/news/crop?news_id=' . $news->id);
        }
        if (isset($input['unpublish']))
        {
            return redirect()->route('news.index')->with('success','News updated successfully');
        }
        if (isset($input['save']))
        {
            return redirect()->route('news.edit', $news->id)->with('success','News updated successfully');
        }
        if (isset($input['save_exit']))
        {
            return redirect()->route('news.index')->with('success','News updated successfully');
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function destroy(News $news)
    {
        $section = null;
        if (isset($news->section))
        {
            $section = $news->section;
        }
        $region_1 = null;
        if (isset($news->region_1))
        {
            $region_1 = $news->region_1;
        }
        $region_2 = null;
        if (isset($news->region_2))
        {
            $region_2 = $news->region_2;
        }

        $news->delete();

        return redirect()->route('news.index')
                        ->with('success','News deleted successfully');
    }
}
