<?php

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();

echo "=== TESTING POST SEARCH FLOW ===" . PHP_EOL . PHP_EOL;

// Test search term
$searchTerm = 'event';
$locale = 'en';

// Step 1: Check how many posts match in Elasticsearch
echo "Step 1: Direct Elasticsearch search for 'event'" . PHP_EOL;
echo str_repeat('-', 80) . PHP_EOL;
$esResults = App\Models\Post::search($searchTerm)->raw();
echo "Total ES hits: " . ($esResults['hits']['total']['value'] ?? 0) . PHP_EOL;

if (!empty($esResults['hits']['hits'])) {
    echo "Sample results:" . PHP_EOL;
    foreach (array_slice($esResults['hits']['hits'], 0, 5) as $hit) {
        $postId = $hit['_source']['id'] ?? 'N/A';
        $categoryId = $hit['_source']['category_id'] ?? 'N/A';
        $title = $hit['_source']['post_translations']['title_en'] ?? 'N/A';
        echo "  - ID: {$postId}, Cat: {$categoryId}, Title: " . substr($title, 0, 40) . PHP_EOL;
    }
}

echo PHP_EOL;

// Step 2: Test with category filter
echo "Step 2: ES search with category filter [4,5,6,7,8,113]" . PHP_EOL;
echo str_repeat('-', 80) . PHP_EOL;

$categoryIds = timebank_config('main_search_bar.category_ids_posts');
echo "Allowed categories: " . json_encode($categoryIds) . PHP_EOL;

// Build filtered query
use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
use ONGR\ElasticsearchDSL\Query\FullText\MultiMatchQuery;

$postsBoolQuery = new BoolQuery();
$postsBoolQuery->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery('__class_name', 'App\Models\Post'),
    BoolQuery::MUST
);

$postSearchFields = ['post_translations.title_' . $locale . '^2'];
$postMultiMatchQuery = new MultiMatchQuery($postSearchFields, $searchTerm);
$postsBoolQuery->add($postMultiMatchQuery, BoolQuery::MUST);

// Add category filter
if (!empty($categoryIds)) {
    $categoryBoolQuery = new BoolQuery();
    foreach ($categoryIds as $categoryId) {
        $categoryBoolQuery->add(
            new \ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery('category_id', $categoryId),
            BoolQuery::SHOULD
        );
    }
    $postsBoolQuery->add($categoryBoolQuery, BoolQuery::MUST);
}

// Execute filtered search via Elasticsearch client
$client = app(Elastic\Elasticsearch\ClientBuilder::class)->build();
$searchBody = ['query' => $postsBoolQuery->toArray()];

try {
    $response = $client->search([
        'index' => 'posts_index',
        'body' => $searchBody
    ])->asArray();

    echo "Total filtered hits: " . ($response['hits']['total']['value'] ?? 0) . PHP_EOL;

    if (!empty($response['hits']['hits'])) {
        echo "Filtered results:" . PHP_EOL;
        foreach ($response['hits']['hits'] as $hit) {
            $postId = $hit['_source']['id'] ?? 'N/A';
            $categoryId = $hit['_source']['category_id'] ?? 'N/A';
            $title = $hit['_source']['post_translations']['title_en'] ?? 'N/A';
            echo "  - ID: {$postId}, Cat: {$categoryId}, Title: " . substr($title, 0, 40) . PHP_EOL;
        }
    }
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . PHP_EOL;
}

echo PHP_EOL;

// Step 3: Process through MainSearchBar logic
echo "Step 3: Simulate processPostCard() for each result" . PHP_EOL;
echo str_repeat('-', 80) . PHP_EOL;

$posts = App\Models\Post::whereIn('category_id', $categoryIds)->get();
foreach ($posts as $post) {
    $translation = $post->translations()->where('locale', $locale)->first();

    if (!$translation) {
        echo "Post ID {$post->id}: NO TRANSLATION" . PHP_EOL;
        continue;
    }

    $currentTime = now();
    $isPublished = true;
    $reason = 'Visible';

    if ($translation->from && $currentTime->lt($translation->from)) {
        $isPublished = false;
        $reason = "Not yet published (from: {$translation->from})";
    }

    if ($translation->till && $currentTime->gt($translation->till)) {
        $isPublished = false;
        $reason = "Publication ended (till: {$translation->till})";
    }

    if ($translation->deleted_at && $currentTime->gte($translation->deleted_at)) {
        $isPublished = false;
        $reason = "Scheduled deletion";
    }

    $status = $isPublished ? '✓ PASS' : '✗ FAIL';
    echo "Post ID {$post->id} (Cat: {$post->category_id}): {$status} - {$reason}" . PHP_EOL;
}

echo PHP_EOL . "=== TEST COMPLETE ===" . PHP_EOL;
