<?php

namespace App\Http\Controllers;

use App\Models\PageContent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class PageContentController extends Controller
{
    /**
     * Display a listing of page content
     */
    public function index()
    {
        $pageContents = PageContent::with(['createdBy', 'updatedByUser'])->orderBy('section')->get();
        return view('admin.page-content.index', compact('pageContents'));
    }

    /**
     * Show the form for creating new page content
     */
    public function create()
    {
        $sections = PageContent::getAvailableSections();
        return view('admin.page-content.create', compact('sections'));
    }

    /**
     * Store a newly created page content
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'section' => 'required|string|unique:page_content,section',
            'title_en' => 'nullable|string|max:255',
            'title_km' => 'nullable|string|max:255',
            'description_en' => 'nullable|string',
            'description_km' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        // Handle image upload
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('page-content', 'public');
            $validated['image'] = $path;
        }

        // Add user tracking
        $validated['created_by'] = Auth::id();
        $validated['updated_by'] = Auth::id();

        PageContent::create($validated);

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

    /**
     * Display the specified page content
     */
    public function show(PageContent $pageContent)
    {
        $pageContent->load(['createdBy', 'updatedByUser']);
        return view('admin.page-content.show', compact('pageContent'));
    }

    /**
     * Show the form for editing page content
     */
    public function edit(PageContent $pageContent)
    {
        $sections = PageContent::getAvailableSections();
        return view('admin.page-content.edit', compact('pageContent', 'sections'));
    }

    /**
     * Update the specified page content
     */
    public function update(Request $request, PageContent $pageContent)
    {
        $validated = $request->validate([
            'section' => 'required|string|unique:page_content,section,' . $pageContent->id,
            'title_en' => 'nullable|string|max:255',
            'title_km' => 'nullable|string|max:255',
            'description_en' => 'nullable|string',
            'description_km' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        // Handle image upload
        if ($request->hasFile('image')) {
            // Delete old image if exists
            if ($pageContent->image) {
                Storage::disk('public')->delete($pageContent->image);
            }
            $path = $request->file('image')->store('page-content', 'public');
            $validated['image'] = $path;
        }

        // Update user tracking
        $validated['updated_by'] = Auth::id();

        $pageContent->update($validated);

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

    /**
     * Remove the specified page content
     */
    public function destroy(PageContent $pageContent)
    {
        // Delete image if exists
        if ($pageContent->image) {
            Storage::disk('public')->delete($pageContent->image);
        }

        $pageContent->delete();

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

    /**
     * DataTable AJAX endpoint
     */
    public function datatable(Request $request)
    {
        $query = PageContent::with(['createdBy', 'updatedByUser']);

        // Search
        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('section', 'like', "%{$search}%")
                  ->orWhere('title_en', 'like', "%{$search}%")
                  ->orWhere('title_km', 'like', "%{$search}%");
            });
        }

        // Sorting
        $order = $request->get('order', 'asc');
        $sort = $request->get('sort', 'section');
        $query->orderBy($sort, $order);

        // Pagination
        $skip = $request->get('skip', 0);
        $take = $request->get('take', 10);
        $total = $query->count();

        $data = $query->skip($skip)->take($take)->get();

        return response()->json([
            'data' => $data,
            'total' => $total,
        ]);
    }
}
