<?php
namespace App\Http\Controllers;

use App;
use App\Models\News;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\View;
use Intervention\Image\ImageManagerStatic as Image;
use Redirect;

class NewsController extends Controller
{

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

        // Site Settings
        $site_settings = DB::table('settings')->get();

        foreach ($site_settings as $setting) {
            $settings[$setting->name] = $setting->value;
            $setting_name = $setting->name;
            $this->$setting_name = $setting->value;
        }

        // Pass data to views
        View::share(['settings' => $settings]);
    }

    /** Index */
    public function index()
    {
        // List of news
        $news = News::orderBy('id', 'DESC')->paginate(10);

        // Return view
        return view('adminlte::news.index', compact('news'));
    }

    /** Create */
    public function create()
    {
        // Return view
        return view('adminlte::news.create');
    }

    /** Store */
    public function store(Request $request)
    {
         // Check if slug exists
        $slug_check = News::where('slug', $request->get('slug'))->first();

        // Return error message if slug is in use
        if ($slug_check != null) {
            return Redirect::back()->withInput()->withErrors(__('admin.slug_in_use'));
        }
        
        $this->validate($request, [
            'title' => 'required|max:255',
            'description' => 'required|max:755',
            'custom_title' => 'nullable|max:255',
            'custom_description' => 'nullable|max:255',            
            'details' => 'required',
            'image' => 'required'
            ]);

        $news = new News;
        $news->slug = $request->get('slug');
        $news->title = $request->get('title');
        $news->custom_title = $request->get('custom_title');
        $news->custom_description = $request->get('custom_description');
        $news->description = $request->get('description');
        $news->description = strip_tags($news->description);
        $news->details = $request->get('details');

        // Check if the picture has been uploaded
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            if ($this->save_as_webp == '1') {
                $file_name = time() . '.webp';
            } else {
                $file_name = time() . '.' . $image->getClientOriginalExtension();
            }
            $location = public_path('images/news/' . $file_name);
            Image::make($image)->resize(770, 450)->save($location, $this->image_quality);
            $news->image = $file_name;
        }

        $news->save();

        if ($request->get('slug') == null) {
            $news->slug = null;
            $news->update([
                'title' => $news->title,
            ]);
        }

        // Ping Google
        if ($this->ping_google == '1') {
            $sitemap_url = asset('sitemap/' . $this->news_base);
            $ch = curl_init("https://www.google.com/webmasters/tools/ping?sitemap=$sitemap_url");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
            $result = curl_exec($ch);
            curl_close($ch);
        }

        // Clear cache
        Cache::flush();

        // Redirect to news edit page
        return redirect()->route('news.edit', $news->id)
            ->with('success', __('admin.data_added'));
    }

    /** Edit */
    public function edit($id)
    {
        // Retrieve news details
        $news = News::find($id);

        // Return 404 page if news not found
        if ($news == null) {
            abort(404);
        }

        // Return view
        return view('adminlte::news.edit', compact('news', 'id'));
    }

    /** Update */
    public function update(Request $request, $id)
    {
        // Check if slug exists
        $slug_check = News::where('slug', $request->get('slug'))->where('id', '!=', $id)->first();

        // Return error message if slug is in use
        if ($slug_check != null) {
            return Redirect::back()->withErrors(__('admin.slug_in_use'));
        }
        
        $this->validate($request, [
            'title' => 'required|max:255',
            'description' => 'required|max:755',
            'custom_title' => 'nullable|max:255',
            'custom_description' => 'nullable|max:255',            
            'details' => 'required'
            ]);

        // Retrieve news details
        $news = News::find($id);
        
        $news->slug = $request->get('slug');
        $news->title = $request->get('title');
        $news->custom_title = $request->get('custom_title');
        $news->custom_description = $request->get('custom_description');        
        $news->description = $request->get('description');
        $news->description = strip_tags($news->description);
        $news->details = $request->get('details');

        // Check if the picture has been changed
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            if ($this->save_as_webp == '1') {
                $file_name = time() . '.webp';
            } else {
                $file_name = time() . '.' . $image->getClientOriginalExtension();
            }
            $location = public_path('images/news/' . $file_name);
            Image::make($image)->resize(770, 450)->save($location, $this->image_quality);
            // Remove old image file
            if (file_exists(public_path() . '/images/news/' . $news->image)) {
                unlink(public_path() . '/images/news/' . $news->image);
            }
            $news->image = $file_name;
        }

        // Ping Google
        if ($news->isDirty() && $this->ping_google == '1') {
            $sitemap_url = asset('sitemap/' . $this->news_base);
            $ch = curl_init("https://www.google.com/webmasters/tools/ping?sitemap=$sitemap_url");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
            $result = curl_exec($ch);
            curl_close($ch);
        }

         if ($request->get('slug') == null) {
            $news->slug = null;
            $news->update(['title' => $news->title]);
        }

        $news->save();
        $news->update(['title' => $news->title]);

        // Clear cache
        Cache::flush();

        // Redirect to news edit page
        return redirect()
            ->route('news.edit', $news->id)
            ->with('success', __('admin.data_updated'));
    }

    /** Destroy */
    public function destroy($id)
    {
        // Retrieve news details
        $news = News::find($id);

        if (!empty($news->image)) {
            if (file_exists(public_path() . '/images/news/' . $news->image)) {
                unlink(public_path() . '/images/news/' . $news->image);
            }
        }

        $news->delete();

        // Clear cache
        Cache::flush();

        // Ping Google
        if ($this->ping_google == '1') {
            $sitemap_url = asset('sitemap/' . $this->news_base);
            $ch = curl_init("https://www.google.com/webmasters/tools/ping?sitemap=$sitemap_url");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
            $result = curl_exec($ch);
            curl_close($ch);
        }

        // Redirect to list of news
        return redirect()
            ->route('news.index')
            ->with('success', __('admin.data_deleted'));
    }

}
