<?php

namespace App\Http\Controllers;

use App\Models\DynamicPages;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class PageController extends Controller
{
    public function index(Request $request)
    {
        $customer_id = auth()->user()->id;
        $workspace_id = auth()->user()->current_workspace_id;
        $pages = DynamicPages::where('customer_id', $customer_id)->where('workspace_id', $workspace_id);
        
        // Add search functionality if search parameter is provided
        if ($request->filled('search')) {
            $search = $request->input('search');
            $pages->where(function($query) use ($search) {
                $query->where('title', 'like', '%' . $search . '%')  // Page Title
                      ->orWhere('permalink', 'like', '%' . $search . '%')  // Permalink
                      ->orWhere('main_heading', 'like', '%' . $search . '%');  // Main Heading
            });
        }
        
        $pages = $pages->latest();
        return $this->withCount($pages, "Pages retrieved successfully.");
    }

    // Store new page
    public function store(Request $request)
    {
        $validatedData = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'permalink' => 'required|string|unique:pages',
            'main_heading' => 'required|string',
            'long_description' => 'required|string',
            'seo_title' => 'nullable|string',
            'seo_tags' => 'nullable|string',
            'seo_description' => 'nullable|string',
            'canonical_url' => 'nullable|string|url',
            'schema_markup' => 'nullable|string',
            'page_index' => 'nullable|boolean',
            'short_description' => 'nullable|string',
        ]);

        if ($validatedData->fails()) {
            return $this->handleValidationFailure($validatedData);
        }

        $validatedData = $validatedData->validated();
        $validatedData['customer_id'] = auth()->user()->id;
        $validatedData['workspace_id'] = auth()->user()->current_workspace_id;

        // Set default value for page_index if not provided
        if (!isset($validatedData['page_index'])) {
            $validatedData['page_index'] = 1;
        }

        $page = DynamicPages::create($validatedData);

        return $this->success($page, 'Page Stored Successfully');
    }


    // Show single page
    public function show($id)
    {
        try {
            $page = DynamicPages::where('id', $id)
                ->when(config('auth.check_ownership'), function ($query) {
                    return $query->where('customer_id', auth()->id())
                        ->where('workspace_id', auth()->user()->current_workspace_id);
                })
                ->first();

            if (!$page) {
                return $this->error('Page not found or you don\'t have permission to view it', 404);
            }

            return $this->success(['page' => $page,], 'Page fetched successfully');
        } catch (\Exception $e) {
            Log::error("Page fetch error [ID: $id]: " . $e->getMessage());
            return $this->error('Failed to retrieve page. Please try again.', 500);
        }
    }

    // Update page
    public function update(Request $request, $id)
    {
        $page = DynamicPages::find($id);

        $validatedData = Validator::make($request->all(), [
            'title' => 'sometimes|string|max:255',
            'permalink' => 'sometimes|string|unique:pages,permalink,' . $page->id,
            'main_heading' => 'sometimes|string',
            'long_description' => 'sometimes|string',
            'seo_title' => 'nullable|string',
            'seo_tags' => 'nullable|string',
            'seo_description' => 'nullable|string',
            'canonical_url' => 'nullable|string|url',
            'schema_markup' => 'nullable|string',
            'page_index' => 'nullable|boolean',
            'short_description' => 'nullable|string',
        ]);

        if ($validatedData->fails()) {
            return $this->handleValidationFailure($validatedData);
        }

        $validatedData = $validatedData->validated();

        $validatedData['customer_id'] = auth()->user()->id;
        $validatedData['workspace_id'] = auth()->user()->current_workspace_id;

        $page->update($validatedData);

        return $this->success($page, 'Page Updated Successfully');
    }


    // Delete page
    public function destroy($id)
    {
        try {
            $page = DynamicPages::find($id);

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

            if (
                $page->customer_id != auth()->user()->id ||
                $page->workspace_id != auth()->user()->current_workspace_id
            ) {
                return $this->error('You don\'t have permission to delete this page', 403);
            }

            $page->delete();

            return $this->success($page, 'Page Deleted Successfully');
        } catch (\Exception $e) {
            Log::error('Error deleting page: ' . $e->getMessage());
            return $this->error('Failed to delete page. Please try again.', 500);
        }
    }

    // Get page by permalink
    public function byPermalink($permalink)
    {
        try {
            $page = DynamicPages::where('permalink', urldecode($permalink))->first();

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

            return $this->success($page, 'Page fetched successfully');
        } catch (\Exception $e) {
            Log::error("Page fetch error: " . $e->getMessage());
            return $this->error('Failed to retrieve page', 500);
        }
    }

    /**
     * Public method to get all pages (for web)
     */
    public function indexWeb()
    {
        try {
            $pages = DynamicPages::select('id', 'title', 'permalink')
                                ->orderBy('created_at', 'desc')
                                ->get();
            
            return $this->success($pages, 'Public pages fetched successfully');
            
        } catch (\Exception $e) {
            Log::error("Public pages fetch error: " . $e->getMessage());
            return $this->error('Failed to retrieve public pages', 500);
        }
    }

    /**
     * Public method to show single page (for web)
     */
    public function showWeb($permalink)
    {
        try {
            $page = DynamicPages::select('id', 'title', 'permalink', 'main_heading', 'long_description', 'seo_title', 'seo_tags', 'seo_description', 'canonical_url', 'schema_markup', 'page_index', 'short_description')
                                ->where('permalink', $permalink)
                                ->first();
    
            if (!$page) {
                return $this->error('Page not found', 404);
            }
    
            return $this->success(['page' => $page], 'Public page fetched successfully');
    
        } catch (\Exception $e) {
            Log::error("Public page fetch error [ID: $permalink]: " . $e->getMessage());
            return $this->error('Failed to retrieve public page', 500);
        }
    }
}
