<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\KbArticle;
use App\Models\KbCategory;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class KbApiController extends Controller
{
    /**
     * Verify serial for article access
     */
    public function verifyArticleSerial(Request $request, $articleSlug): JsonResponse
    {
        $request->validate([
            'serial' => 'required|string|max:255',
        ]);

        $article = KbArticle::where('slug', $articleSlug)->first();

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

        // Check if article requires serial
        if (!$article->requires_serial) {
            return response()->json([
                'success' => true,
                'message' => 'No serial required',
                'data' => [
                    'content' => $article->content,
                    'title' => $article->title
                ]
            ]);
        }

        // Check if category requires serial
        $categoryRequiresSerial = $article->category && $article->category->requires_serial;

        if (!$categoryRequiresSerial && !$article->requires_serial) {
            return response()->json([
                'success' => true,
                'message' => 'No serial required',
                'data' => [
                    'content' => $article->content,
                    'title' => $article->title
                ]
            ]);
        }

        // Verify serial
        $serialValid = false;
        $serialSource = '';

        if ($article->requires_serial && $article->serial === $request->serial) {
            $serialValid = true;
            $serialSource = 'article';
        } elseif ($categoryRequiresSerial && $article->category->serial === $request->serial) {
            $serialValid = true;
            $serialSource = 'category';
        }

        if (!$serialValid) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid serial code'
            ], 403);
        }

        // Increment views
        $article->increment('views');

        return response()->json([
            'success' => true,
            'message' => 'Serial verified successfully',
            'data' => [
                'content' => $article->content,
                'title' => $article->title,
                'serial_source' => $serialSource
            ]
        ]);
    }

    /**
     * Get article serial requirements
     */
    public function getArticleRequirements($articleSlug): JsonResponse
    {
        $article = KbArticle::with('category')->where('slug', $articleSlug)->first();

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

        $requiresSerial = $article->requires_serial || ($article->category && $article->category->requires_serial);

        $response = [
            'success' => true,
            'data' => [
                'requires_serial' => $requiresSerial,
                'title' => $article->title,
                'excerpt' => $article->excerpt
            ]
        ];

        if ($requiresSerial) {
            $serialMessage = '';
            $serialSource = '';

            if ($article->requires_serial) {
                $serialMessage = $article->serial_message ?: 'Please enter the serial code to access this article.';
                $serialSource = 'article';
            } elseif ($article->category && $article->category->requires_serial) {
                $serialMessage = $article->category->serial_message ?: 'Please enter the serial code to access articles in this category.';
                $serialSource = 'category';
            }

            $response['data']['serial_message'] = $serialMessage;
            $response['data']['serial_source'] = $serialSource;
        }

        return response()->json($response);
    }

    /**
     * Get category serial requirements
     */
    public function getCategoryRequirements($categorySlug): JsonResponse
    {
        $category = KbCategory::with('articles')->where('slug', $categorySlug)->first();

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

        $response = [
            'success' => true,
            'data' => [
                'requires_serial' => $category->requires_serial,
                'name' => $category->name,
                'description' => $category->description,
                'articles_count' => $category->articles->count()
            ]
        ];

        if ($category->requires_serial) {
            $response['data']['serial_message'] = $category->serial_message ?: 'Please enter the serial code to access articles in this category.';
        }

        return response()->json($response);
    }
}
