<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Berita;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use DataTables;
use DateTime;
use App\Models\JenisDokumen;
use Illuminate\Support\Facades\Auth;
use Response;

class BeritaController extends Controller
{
    //
    public function index()
    {
        # code...
        return view('Beritas.index');
    }

    public function getDatatables(Request $request)
    {
        # code...
        $data = Berita::latest()->get();
        return DataTables::of($data)
                    ->addIndexColumn()
                    ->addColumn('author', function($row){
                        $getUser = User::where('id', $row->created_by)->first();
                        return $getUser->name;
                    })
                    ->addColumn('tgl', function($row){
                        return date('d-m-Y H:i:s', strtotime($row->tanggal));
                    })
                    ->addColumn('img', function($row){
                        $img = '<img class="img-fluid" src="uploads/'.$row->thumbnail.'" />';
                        return $img;
                    })
                    ->addColumn('action', function($row){
                        $btn = '<div class="mt-3" style="vertical-align:middle !important;"><a href="/news/show/'.$row->id.'" ><i class="fas fa-edit"></i>
                        </a> <a href="javascript:void(0)" class="ml-1 text-danger" onclick="hapus('.$row->id.')"    ><i class="fas fa-trash"></i>
                        </a></div>';
                        return $btn;
                    })
                    ->rawColumns(['author','tgl','img','action'])
                    ->make(true);

        // return view('Dokumenss.index');
    }
    
    public function add()
    {
        # code...
        return view('Beritas.create');
    }
    public function store(Request $request)
    {
        # code...
        try {
            //code...
            // dd(Auth()->user()->id);die();
            $validator = Validator::make($request->all(), [
                'judul' => 'required|max:255',
                // 'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
                'isi' => 'required',
                'thumbnail' =>'required'
            ]);
    
            if ($validator->fails()) {
                return back()
                            ->withErrors($validator)
                            ->withInput();
            }
    
            $news = new Berita();
            // var_dump($request->file('file'));die();
            if($request->hasfile('thumbnail')){
                $allowedfileExtension=['jpg','png'];
                $filename = time(). " " .$request->file('thumbnail')->getClientOriginalName();
                $ext = $request->file('thumbnail')->getClientOriginalExtension();
              

                $check = in_array($ext, $allowedfileExtension);
                // dd($filename);die();
                if($check){
                    $filepath = $request->file('thumbnail')->move('uploads', $filename, 'public');
    
                    $news->judul = $request->judul;
                    $news->isi = $request->isi;
                    $news->tanggal = new DateTime();
                    $news->created_by = Auth()->user()->id;
                    $news->thumbnail = $filename;
                    $news->save();
                    return redirect()->route('news.index')->with('message', 'Data berhasil disimpan!');

                }
                else{
                return response()->json([
                    'status' => 500,
                    'message'=>'hanya bisa upload jpg, & png. Silakan cek kembali'
                ]);

                }

                // $doc->nama = $request->nama;
                // $doc->level = $request->level;
                // $doc->save();

            }else{
                return response()->json([
                    'status' => 500,
                    'message'=>'check'
                ]);
            }
    
            
            
        } catch (\Throwable $th) {
            //throw $th;
            return response()->json(
                ["data" => $th,
                  "status" => 505,
                 "message" => "error"]
            );
        }
        


    }
    public function showData ($id){
        $data = Berita::where('id',$id)->first();
        return view('Beritas.edit', compact('data'));
    }
    public function get_by_id($id)
    {
        # code...
        try {
            $data = Berita::where('id',$id)->first();

            return response()->json([
                'data' => $data,
                'status' => "200"
            ]);
            
        } catch (\Throwable $th) {
            //throw $th;
            return response()->json([
                'data' => $th,
                'status' => "505",
                'message' => 'error'
            ]);
        }
    }

    public function show($id)
    {
        # code...
        try {
            //code...
            $dok = JenisDokumen::with('children')->get();
            $data = Berita::where('id',$id)->with('author')->first();
            return view('Beritas.view', compact('data','dok'));
        } catch (\Exception $e) {
            //throw $th;
            return response()->json([
                'data' => $e,
                'status' => "505",
                'message' => 'error'
            ]);
        }
    }

    public function update(Request $request)
    {
        # code...
        try {
            // dd($request->all());die();
            $validator = Validator::make($request->all(), [
                'judul' => 'required|max:255',
                'isi' => 'required',
            ]);
    
            if ($validator->fails()) {
                return back()
                            ->withErrors($validator)
                            ->withInput();
                            
            }

            if($request->hasfile('thumbnail')){
                $allowedfileExtension=['jpg','png'];
                $filename = time(). " " .$request->file('thumbnail')->getClientOriginalName();
                $ext = $request->file('thumbnail')->getClientOriginalExtension();
              

                $check = in_array($ext, $allowedfileExtension);
                // dd($filename);die();
                if($check){
                    $filepath = $request->file('thumbnail')->move('uploads', $filename, 'public');
    
                    $data = Berita::where('id',$request->id)->update([
                        'judul' =>$request->judul,
                        'isi' => $request->isi,
                        'tanggal' => new DateTime(),
                        'thumbnail' => $filename
                    ]);
                    if($data){
                        return redirect()->route('news.index')->with('message', 'Data berhasil diedit!');

                    }
                }
                else{
                return response()->json([
                    'status' => 500,
                    'message'=>'hanya bisa upload  jpg, & png. Silakan cek kembali'
                ]);

                }

                // $doc->nama = $request->nama;
                // $doc->level = $request->level;
                // $doc->save();

            }else{
                $data = Berita::where('id',$request->id)->update([
                    'judul' =>$request->judul,

                        'isi' => $request->isi,
                        'tanggal' => new DateTime(),
                        'thumbnail' => $request->old_thumbnail
                ]);
                if($data){
                    return redirect()->route('news.index')->with('message', 'Data berhasil diedit!');

                }

            }

            
        } catch (\Throwable $th) {
            //throw $th;
            return response()->json([
                'data' => $th,
                'status' => "505",
                'message' => 'error'
            ]);
        }
    }

    public function delete($id)
    {
        # code...
        try {
            //code...
            $data = Berita::find($id);
            $data->delete();
            return response()->json([
                'status' => '200',
                'message' => 'Data berhasil dihapus!'
            ]);
        } catch (\Throwable $th) {
            //throw $th;
            return response()->json([
                'data' => $th,
                'status' => "505",
                'message' => 'error'
            ]);
        }
    }
}
