<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Str;

class PostController extends Controller
{
    public function index()
    {
        $page = 'Blog';

        return view('admin.blog.index', compact('page'));
    }


    public function load(Request $request)
    {
        if (!$request->ajax()) {
            return response()->json(['error' => 'Invalid request'], 400);
        }
    
        $perPage = 10;
        $search = $request->input('search');
    
        $query = Post::orderBy('created_at', 'desc');
    
        if (!empty($search)) {
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('slug', 'like', "%{$search}%")
                    ->orWhere('meta_title', 'like', "%{$search}%")
                      ->orWhere('meta_description', 'like', "%{$search}%");
                        
            });
        }
    
        $Post = $query->paginate($perPage);
    
        $records = $Post->getCollection()->map(function ($user) {
            return [
                'id' => $user->id,
                'title' => $user->title,
                'created_at' => $user->created_at->format('Y-m-d H:i:s'),
                'updated_at' => $user->updated_at->format('Y-m-d H:i:s'),
            ];
        });
    
        return response()->json([
            'records' => $records,
            'current_page' => $Post->currentPage(),
            'total_pages' => $Post->lastPage(),
            'prev_page' => $Post->previousPageUrl() ? $Post->currentPage() - 1 : null,
            'next_page' => $Post->nextPageUrl() ? $Post->currentPage() + 1 : null,
        ]);
    }

    public function create()
    {
        $page = 'Add Post';
        return view('admin.blog.create', compact('page'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|unique:posts,title',
            'content' => 'required',
            'meta_title' => 'nullable',
            'meta_description' => 'nullable',
        ]);

        Post::create([
            'title' => $request->title,
            'slug' => Str::slug($request->title, '-'),
            'content' => $request->content,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
        ]);

        return response()->json([
            'status' => 'success',
            'message' => "Post created successfully."
        ]);
    }

    public function edit($id)
    {
        $post = Post::findOrFail($id);
        $page = 'Edit Post';
        return view('admin.blog.edit', compact('page', 'post'));
    }

    public function update(Request $request, $id)
    {
        $post = Post::findOrFail($id);
    
        $post->update([
            'title' => $request->title,
            'slug' => Str::slug($request->title, '-'),
            'content' => $request->content,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
        ]);
    
        return response()->json([
            'status' => 'success',
            'message' => "Post updated successfully."
        ]);
    }

    public function uploadFile(Request $request, $type = 'image')
    {
        if(empty($type)) {
            return response()->json([
                'status' => 'error'
            ]);
        }
        $assetPath = public_path('assets/gallery/');
        if (!file_exists($assetPath)) {
            mkdir($assetPath, 0755, true);
        }
    
        $file = $request->file($type);
        $fileName = $type . '_' . time() . '.' . $file->getClientOriginalExtension();
        $file->move($assetPath, $fileName);
    
        return response()->json([
            'status' => 'success',
            'url' => "/assets/gallery/$fileName"
        ]);
    }
    public function delete($id)
    {
        Post::findOrFail($id)->delete();

        return response()->json(['message' => 'Post deleted successfully!']);
    }
}
