<?php

namespace App\Http\Controllers;

use App\Models\ContentPage;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class ContentPageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = ContentPage::with(['creator']);

            // Filter by page type
            if ($request->has('type')) {
                $query->where('page_type', $request->get('type'));
            }

            // Filter by published status
            if ($request->has('published')) {
                $query->where('is_published', $request->get('published'));
            }

            // Search by title or content
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function($q) use ($search) {
                    $q->where('page_title', 'like', "%{$search}%")
                      ->orWhere('page_content', 'like', "%{$search}%");
                });
            }

            // Order by
            $orderBy = $request->get('order_by', 'page_title');
            $orderDirection = $request->get('order_direction', 'asc');
            $query->orderBy($orderBy, $orderDirection);

            // Pagination
            $perPage = $request->get('per_page', 10);
            $pages = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $pages->items(),
                'pagination' => [
                    'current_page' => $pages->currentPage(),
                    'per_page' => $pages->perPage(),
                    'total' => $pages->total(),
                    'last_page' => $pages->lastPage(),
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch content pages',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $validated = $request->validate([
                'page_title' => 'required|string|max:255',
                'page_slug' => 'required|string|max:255|unique:content_pages,page_slug',
                'page_content' => 'required|string',
                'page_type' => 'required|in:about,privacy,terms,faq,contact,home,general',
                'is_published' => 'boolean'
            ]);

            $validated['created_by'] = $user->user_id;

            // Set default values if not provided
            if (!isset($validated['is_published'])) {
                $validated['is_published'] = true; // Default to published
            }

            $page = ContentPage::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Content page created successfully',
                'data' => $page->load('creator')
            ], 201);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create content page',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        try {
            $page = ContentPage::with(['creator'])->find($id);

            if (!$page) {
                return response()->json([
                    'success' => false,
                    'message' => 'Content page not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $page
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch content page',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $page = ContentPage::find($id);

            if (!$page) {
                return response()->json([
                    'success' => false,
                    'message' => 'Content page not found'
                ], 404);
            }

            $validated = $request->validate([
                'page_title' => 'sometimes|string|max:255',
                'page_slug' => 'sometimes|string|max:255|unique:content_pages,page_slug,' . $id . ',page_id',
                'page_content' => 'sometimes|string',
                'page_type' => 'sometimes|in:about,privacy,terms,faq,contact,home,general',
                'is_published' => 'boolean'
            ]);

            $page->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Content page updated successfully',
                'data' => $page->load('creator')
            ]);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update content page',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $page = ContentPage::find($id);

            if (!$page) {
                return response()->json([
                    'success' => false,
                    'message' => 'Content page not found'
                ], 404);
            }

            $page->delete();

            return response()->json([
                'success' => true,
                'message' => 'Content page deleted successfully'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete content page',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get page by slug (public)
     */
    public function getBySlug(string $slug): JsonResponse
    {
        try {
            $page = ContentPage::published()->where('page_slug', $slug)->first();

            if (!$page) {
                return response()->json([
                    'success' => false,
                    'message' => 'Content page not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $page
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch content page',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get pages by type (public)
     */
    public function getByType(string $type): JsonResponse
    {
        try {
            $pages = ContentPage::published()
                        ->where('page_type', $type)
                        ->ordered()
                        ->get();

            return response()->json([
                'success' => true,
                'data' => $pages
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch content pages',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Publish page
     */
    public function publish(string $id): JsonResponse
    {
        try {
            $page = ContentPage::find($id);

            if (!$page) {
                return response()->json([
                    'success' => false,
                    'message' => 'Content page not found'
                ], 404);
            }

            $page->publish();

            return response()->json([
                'success' => true,
                'message' => 'Content page published successfully',
                'data' => $page->load('creator')
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to publish content page',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Unpublish page
     */
    public function unpublish(string $id): JsonResponse
    {
        try {
            $page = ContentPage::find($id);

            if (!$page) {
                return response()->json([
                    'success' => false,
                    'message' => 'Content page not found'
                ], 404);
            }

            $page->unpublish();

            return response()->json([
                'success' => true,
                'message' => 'Content page unpublished successfully',
                'data' => $page->load('creator')
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to unpublish content page',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
