<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Session;
use Mail;
use Auth;
use Hash;

class ContentController extends Controller
{
	public function addpost()
    {
        return view('admin.addpost');
    }

    public function addpostnow(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            $data1['title'] = $data['title'];
            $data1['summary'] = $data['summary'];
            $data1['details'] = $data['details'];
            $data1['status'] = $data['type'];
            $image = $request->file('image');
           
            $image_name = hexdec(uniqid());
            $extention = strtolower($image->getClientOriginalExtension());
            $image_full_name = $image_name.'.'.$extention;
            $upload_path = 'web/uploads/news/';
            $image_url = $upload_path.$image_full_name;
            $success = $image->move($upload_path,$image_full_name);
            $data1['image'] = $image_url;
            DB::table('contents')->insert($data1);

            toastr()->success('Post Added Successfully!');
            return redirect()->back();

        }
    }

    public function postList()
    {
        $data['posts'] = DB::table('contents')->orderBy('created_at', 'desc')->get();
        return view('admin.posts', $data);
    }

    public function postMng($id)
    {
        $data['post_data'] = DB::table('contents')->where('id', $id)->first();
        return view('admin.postmng', $data);
    }

    public function postEdit(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            $post_data = DB::table('contents')->where('id', $data['post_id'])->first();

            $data1['title'] = $data['title'];
            $data1['summary'] = $data['summary'];
            $data1['details'] = $data['details'];
            $data1['status'] = $data['type'];
            $image = $request->file('image');
            if ($image) {
                unlink($post_data->image);
                $image_name = hexdec(uniqid());
                $extention = strtolower($image->getClientOriginalExtension());
                $image_full_name = $image_name.'.'.$extention;
                $upload_path = 'web/uploads/news/';
                $image_url = $upload_path.$image_full_name;
                $success = $image->move($upload_path,$image_full_name);
                $data1['image'] = $image_url;
            }

            DB::table('contents')->where('id', $post_data->id)->update($data1);

            toastr()->success('Post Updated Successfully!');
            return redirect('admin/posts');
        }
    }
}