<?php

namespace App\Http\Controllers;

use App\Http\Requests\PostRequest;
use App\Models\Kategori;
use App\Models\Post;
use App\Models\SubKategori;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Illuminate\Support\Facades\DB;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::with(['kategori', 'subkategori'])->latest()->get();
        $kategori = Kategori::all();
        $subkategori = SubKategori::all();

        return Inertia::render('admin/post/index_post', [
            'posts' => $posts,
            'kategori' => $kategori,
            'subkategori' => $subkategori
        ]);
    }

    public function create()
    {
        $kategori = Kategori::all();
        $subkategori = SubKategori::all();

        return Inertia::render('admin/post/add_post', [
            'kategori' => Kategori::all(),
            'subkategori' => SubKategori::all(),
            'existingPosts' => Post::select('JudulPost', 'KategoriId')->get()
        ]);
    }

    public function store(PostRequest $request)
    {
        try {
            $data = $request->validated();

            DB::beginTransaction();

            try {
                $data['IsPublish'] = $request->boolean('IsPublish');

                if ($request->hasFile('ImagePost')) {
                    $file = $request->file('ImagePost');

                    if (!$file->isValid()) {
                        throw new \Exception('Invalid image file');
                    }

                    $data['ImagePost'] = $file->store('images/posts', 'public');

                    if ($data['ImagePost'] === false) {
                        throw new \Exception('Failed to store image');
                    }
                }

                $post = Post::create($data);
                DB::commit();

                return redirect()
                    ->route('admin.post.index')
                    ->with('success', 'Post berhasil ditambahkan');

            } catch (\Exception $e) {
                DB::rollBack();

                if (isset($data['ImagePost']) && Storage::disk('public')->exists($data['ImagePost'])) {
                    Storage::disk('public')->delete($data['ImagePost']);
                }

                Log::error('Error creating post: ' . $e->getMessage());

                return redirect()
                    ->route('admin.post.index')
                    ->with('error', 'Post gagal ditambahkan: ' . $e->getMessage());
            }

        } catch (\Exception $e) {
            Log::error('Validation error: ' . $e->getMessage());

            return redirect()
                ->route('admin.post.index')
                ->with('error', 'Validasi gagal: ' . $e->getMessage());
        }
    }

    public function edit(Post $post)
    {
        // Debug the image path
        Log::info('Image path:', ['path' => $post->ImagePost]);

        return Inertia::render('admin/post/edit_post', [
            'posting' => [
                ...$post->toArray(),
                'ImagePost' => $post->ImagePost ? '/storage/' . $post->ImagePost : null,
            ],
            'kategori' => Kategori::all(),
            'subkategori' => SubKategori::all(),
            'existingPosts' => Post::where('PostId', '!=', $post->PostId)
                ->select('JudulPost', 'KategoriId')
                ->get()
        ]);
    }

    public function update(PostRequest $request, Post $post)
    {
        try {
            DB::beginTransaction();
            $data = $request->validated();

            // Only update image if new one is uploaded
            if ($request->hasFile('ImagePost')) {
                // Delete old image if exists
                if ($post->ImagePost && Storage::disk('public')->exists($post->ImagePost)) {
                    Storage::disk('public')->delete($post->ImagePost);
                }
                $data['ImagePost'] = $request->file('ImagePost')->store('images/posts', 'public');
            } else {
                // Keep existing image if no new one uploaded
                unset($data['ImagePost']);
            }

            $data['IsPublish'] = $request->boolean('IsPublish');
            $post->update($data);

            DB::commit();
            return redirect()->route('admin.post.index')->with('success', 'Post berhasil diperbarui.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error updating Post: ' . $e->getMessage());
            return back()->with('error', 'Terjadi kesalahan saat memperbarui post.');
        }

    }

    public function destroy(Post $post)
    {
        try {
            Storage::disk('public')->delete($post->ImagePost);
            $post->delete();

            return redirect()->route('admin.post.index')->with('success', 'Post berhasil dihapus.');
        } catch (\Exception $e) {
            Log::error('Error deleting Post: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong.');
        }
    }
}
