<?php

namespace App\Http\Controllers;

use App\Models\post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class DataController extends Controller
{
    public function index(Request $request)
    {
        $query = $request->query('searchTable');

        if ($query == '') {
            $data = post::orderBy('created_at', 'desc')->paginate(5);
        }elseif ($query != '') {
            $data = post::where('title', 'LIKE', "%{$query}%")
                        ->orderBy('created_at', 'desc')
                        ->paginate(5);
        }
        return view('admin.create', compact('data'));
    }

    public function mencari($search)
    {

        return view('admin.create', compact('data'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'photo' => 'required|image|mimes:jpeg,png,jpg,gif',
            'title' => 'required|string|max:255',
        ], [
            'title.unique' => 'The title has already been taken.',
        ]);

        if ($request->file('photo')->isValid()) {
            $image = $request->file('photo');
            $imageName = time().'.'.$image->getClientOriginalExtension();
            Storage::disk('public')->put("img/{$imageName}", file_get_contents($image));
            $image->move(public_path('theData'), $imageName);

            $existingPost = post::where('title', $request->title)->first();
            if ($existingPost) {
                return redirect()->back()->with('error', 'JUDUL BERITA SUDAH ADA');
            }else{
                $data = [
                    'title' => $request['title'],
                    'slug' => Str::slug($request->title),
                    'photo' => $imageName,
                    'data' => $request->deskripsi,
                    'tags' => $request->tags,
                ];

                post::create($data);
            }

        return redirect('/admin/dashboard')->with('success', 'Data Berhasil Ditambah');
        }

    }


    public function edit($id)
    {
        $data = post::find($id);
        return view('admin.update', compact('data'));
    }

    public function update(Request $request, $id)
    {
        $data = post::find($id);

        $request->validate([
            'photo' => 'image|mimes:jpeg,png,jpg,gif',
            'title' => 'required|string|max:255',
        ], [
            'title.unique' => 'The title has already been taken.',
        ]);

        if ($request->hasFile('photo') && $request->file('photo')->isValid()) {
            $oldPhotoPath = "img/{$data->photo}";
            if (Storage::disk('public')->exists($oldPhotoPath)) {
                Storage::disk('public')->delete($oldPhotoPath);
            }

            if ($request->hasFile('photo') && $request->file('photo')->isValid()) {
                $image = $request->file('photo');
                $imageName = time().'.'.$image->getClientOriginalExtension();
                Storage::disk('public')->put("img/{$imageName}", file_get_contents($image));
                $data->photo = $imageName;
            }
        }

        $data->title = $request->title;
        $data->slug = Str::slug($request['title']);
        $data->data = $request->deskripsi;
        $data->tags = $request->tags;

        $data->save();

        return redirect('/admin/dashboard')->with('success', 'Data berhasil diedit');
    }

    public function destroy($id)
    {
        $data = post::find($id);

        if ($data) {
            $image = "img/$data->photo";
            if (Storage::disk('public')->exists($image)) {

                Storage::disk('public')->delete($image);
            }

            $data->delete();

        return redirect('/admin/dashboard')->with('success', 'Data berhasil dihapus');
        }
    }

}
