<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Page;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PageController extends Controller
{
    public function index()
    {
        $id = request()->get('id');
        $page = null;
        $ancestors = collect();

        if ($id) {
            $page = Page::find($id);
            if ($page) {
                $ancestors = $page->ancestors();
            }
        }

        return view('admin.pages.index', [
            'page' => $page,
            'ancestors' => $ancestors,
        ]);
    }

    public function create()
    {
        $id = request()->get('id');
        $page = null;
        $ancestors = collect();

        if ($id) {
            $page = Page::find($id);
            if ($page) {
                $ancestors = $page->ancestors();
            }
        }

        return view('admin.pages.create', [
            'page' => $page,
            'ancestors' => $ancestors,
        ]);
    }

    public function edit(int $id)
    {
        $page = Page::findOrFail($id);
        $ancestors = collect();

        if ($id) {
            $page = Page::find($id);
            if ($page) {
                $ancestors = $page->ancestors();
            }
        }

        return view('admin.pages.edit', [
            'page' => $page,
            'ancestors' => $ancestors,
        ]);
    }

    public function ckeditorUpload(Request $request)
    {
        if ($request->hasFile('upload')) {
            $request->validate([
                'upload' => 'required|file|mimes:jpg,jpeg,png,gif|max:10240',
            ]);

            $file = $request->file('upload');

            $filename = uniqid() . '.' . $file->getClientOriginalExtension();

            $destinationPath = public_path('ckeditor');

            $file->move($destinationPath, $filename);

            $url = url('ckeditor/' . $filename);

            return response()->json(['url' => $url]);
        }

        return response()->json(['error' => 'No file uploaded'], 400);
    }
}
