<?php

namespace App\Http\Controllers\Api;

use App\Models\Page;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Dedoc\Scramble\Attributes\HeaderParameter;

/**
 * @tags 10. Pages
 */
class PageController extends ApiController
{
    /**
     * Get Pages List
     * 
     * Get all published pages with localized content.
     * Pages are filtered by user's current locale.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string', example: 'Bearer 1|f832abc...xyz')]
    public function index(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'page' => 'nullable|integer|min:1',
            'per_page' => 'nullable|integer|min:1|max:50',
            'search' => 'nullable|string|max:100',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $locale = $this->getCurrentLocale($request);
        $perPage = $request->input('per_page', 20);
        $search = $request->input('search');

        // Build query
        $query = Page::query()
            ->published()
            ->with(['translations' => function ($q) use ($locale) {
                $q->where('locale_id', $locale['locale_id']);
            }])
            ->whereHas('translations', function ($q) use ($locale) {
                $q->where('locale_id', $locale['locale_id']);
            });

        // Apply search filter
        if ($search) {
            $query->whereHas('translations', function ($q) use ($search, $locale) {
                $q->where('locale_id', $locale['locale_id'])
                  ->where(function ($sq) use ($search) {
                      $sq->where('title', 'like', "%{$search}%")
                        ->orWhere('description', 'like', "%{$search}%");
                  });
            });
        }

        // Order by latest
        $query->orderBy('created_at', 'desc');

        $pages = $query->paginate($perPage);

        // Transform data
        $transformedPages = $pages->getCollection()->map(function ($page) use ($locale) {
            return [
                'id' => $page->id,
                'title' => $page->getTitle($locale['locale_id']),
                'status' => $page->status,
                'created_at' => $page->created_at->toISOString(),
                'updated_at' => $page->updated_at->toISOString(),
            ];
        });

        return $this->resourceResponse([
            'pages' => $transformedPages,
            'pagination' => [
                'current_page' => $pages->currentPage(),
                'last_page' => $pages->lastPage(),
                'per_page' => $pages->perPage(),
                'total' => $pages->total(),
                'from' => $pages->firstItem(),
                'to' => $pages->lastItem(),
            ],
            'filters' => [
                'search' => $search,
                'locale_id' => $locale['locale_id'],
                'country_id' => $locale['country_id'],
                'language_id' => $locale['language_id'],
            ],
        ], 'Pages retrieved successfully');
    }

    /**
     * Get Page Details
     * 
     * Get detailed information about a specific page with full content.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string', example: 'Bearer 1|f832abc...xyz')]
    public function show(Request $request, $pageId): JsonResponse
    {
        $locale = $this->getCurrentLocale($request);

        $page = Page::query()
            ->where('id', $pageId)
            ->published()
            ->with(['translations' => function ($q) use ($locale) {
                $q->where('locale_id', $locale['locale_id']);
            }])
            ->first();

        if (!$page) {
            return $this->errorResponse('Page not found or not published', 404);
        }

        // Check if page has translation for current locale
        $translation = $page->getTranslation($locale['locale_id']);
        if (!$translation) {
            return $this->errorResponse('Page content not available in your language', 404);
        }

        return $this->successResponse([
            'page' => [
                'id' => $page->id,
                'title' => $page->getTitle($locale['locale_id']),
                'description' => $page->getDescription($locale['locale_id']), // الوصف كامل
                'status' => $page->status,
                'created_at' => $page->created_at->toISOString(),
                'updated_at' => $page->updated_at->toISOString(),
            ],
            'locale' => [
                'locale_id' => $locale['locale_id'],
                'country_id' => $locale['country_id'],
                'language_id' => $locale['language_id'],
            ],
        ], 'Page details retrieved successfully');
    }

    /**
     * Search Pages
     * 
     * Search pages by title and content in user's current language.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string', example: 'Bearer 1|f832abc...xyz')]
    public function search(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'query' => 'required|string|min:2|max:100',
            'page' => 'nullable|integer|min:1',
            'per_page' => 'nullable|integer|min:1|max:50',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $searchQuery = $request->input('query');
        $locale = $this->getCurrentLocale($request);
        $perPage = $request->input('per_page', 10);

        // Build search query
        $pages = Page::query()
            ->published()
            ->with(['translations' => function ($q) use ($locale) {
                $q->where('locale_id', $locale['locale_id']);
            }])
            ->whereHas('translations', function ($q) use ($searchQuery, $locale) {
                $q->where('locale_id', $locale['locale_id'])
                  ->where(function ($sq) use ($searchQuery) {
                      $sq->where('title', 'like', "%{$searchQuery}%")
                        ->orWhere('description', 'like', "%{$searchQuery}%");
                  });
            })
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);

        // Transform data
        $transformedPages = $pages->getCollection()->map(function ($page) use ($locale) {
            return [
                'id' => $page->id,
                'title' => $page->getTitle($locale['locale_id']),
                'created_at' => $page->created_at->toISOString(),
            ];
        });

        return $this->resourceResponse([
            'results' => $transformedPages,
            'pagination' => [
                'current_page' => $pages->currentPage(),
                'last_page' => $pages->lastPage(),
                'per_page' => $pages->perPage(),
                'total' => $pages->total(),
                'from' => $pages->firstItem(),
                'to' => $pages->lastItem(),
            ],
            'search' => [
                'query' => $searchQuery,
                'results_count' => $pages->total(),
                'locale_id' => $locale['locale_id'],
            ],
        ], 'Search results retrieved successfully');
    }
}