<?php

namespace App\Http\Controllers\Admin;

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

class PageController extends Controller
{
    public function index()
    {
        $page = 'Pages';

        return view('admin.page.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 = Pages::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}%");
                        
            });
        }
    
        $page = $query->paginate($perPage);
    
        $records = $page->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' => $page->currentPage(),
            'total_pages' => $page->lastPage(),
            'prev_page' => $page->previousPageUrl() ? $page->currentPage() - 1 : null,
            'next_page' => $page->nextPageUrl() ? $page->currentPage() + 1 : null,
        ]);
    }

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

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

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

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

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

    public function update(Request $request, $id)
    {
        $page = Pages::findOrFail($id);
    
        $page->update([
            'title' => $request->title,
            'slug' => $request->slug,
            'content' => $request->content,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
        ]);
    
        return response()->json([
            'status' => 'success',
            'message' => "Page 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)
    {
        Pages::findOrFail($id)->delete();

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