<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\SiteContent;

class SiteContentController extends Controller
{
    /**
     * Display all site content with optional page filter
     */
    public function index(Request $request)
    {
        $pages = SiteContent::select('page')->distinct()->pluck('page');
        $query = SiteContent::query();

        if ($request->filled('page')) {
            $query->where('page', $request->page);
        }

        return view('admin.content.index', [
            'content' => $query->get(),
            'pages' => $pages,
            'selectedPage' => $request->page ?? ''
        ]);
    }

    /**
     * Show create content form
     */
    public function create()
    {
        return view('admin.content.create');
    }

    /**
     * Store new site content
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'page' => 'required|string|max:255',
            'section' => 'required|string|max:255',
            'title' => 'required|string|max:255',
            'content' => 'nullable|string',
        ]);

        // Handle image upload like Members
        if ($request->hasFile('image')) {
            $image = $request->file('image');

            if ($image && $image->isValid()) {
                $filename = time() . '_' . preg_replace('/\s+/', '_', $image->getClientOriginalName());

                // Save image to frontend public folder
                $destinationPath = base_path('../ahoj/public/uploads/content');
                if (!is_dir($destinationPath)) {
                    mkdir($destinationPath, 0775, true);
                }

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

                $validated['image_url'] = 'uploads/content/' . $filename;
            }
        }

        SiteContent::create($validated);

        return redirect()->route('content.index')
                         ->with('success', 'Content created successfully!');
    }

    /**
     * Show edit form
     */
    public function edit($id)
    {
        return view('admin.content.edit', [
            'content' => SiteContent::findOrFail($id)
        ]);
    }

    /**
     * Update existing site content
     */
    public function update(Request $request, $id)
    {
        $content = SiteContent::findOrFail($id);

        $data = $request->only(['page', 'section', 'title', 'content']);

        // Handle image upload like Members
        if ($request->hasFile('image')) {
            $image = $request->file('image');

            if ($image && $image->isValid()) {
                $filename = time() . '_' . preg_replace('/\s+/', '_', $image->getClientOriginalName());

                // Save image to frontend public folder
                $destinationPath = base_path('../ahoj/public/uploads/content');
                if (!is_dir($destinationPath)) {
                    mkdir($destinationPath, 0775, true);
                }

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

                $data['image_url'] = 'uploads/content/' . $filename;
            }
        }

        $content->update($data);

        return redirect()->route('content.index')
                         ->with('success', 'Content updated successfully!');
    }

    /**
     * Delete site content
     */
    public function destroy($id)
    {
        SiteContent::destroy($id);

        return redirect()->route('content.index')
                         ->with('success', 'Content deleted successfully!');
    }
}
