<?php

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

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

// Simulate the EXACT flow that MainSearchBar uses
echo "=== TESTING FULL MAINSEARCHBAR FLOW ===" . PHP_EOL . PHP_EOL;

$searchTerm = 'event';
$locale = 'en';

// Set app locale
app()->setLocale($locale);

// Clean search term (same as MainSearchBar)
$search = preg_replace('/[^a-zA-Z0-9\s]/', '', $searchTerm);
$search = rtrim($search);
$cleanSearch = trim(str_replace('*', '', $search));

echo "Original term: '{$searchTerm}'" . PHP_EOL;
echo "Cleaned term: '{$cleanSearch}'" . PHP_EOL;
echo "Locale: {$locale}" . PHP_EOL;
echo PHP_EOL;

// Create the exact query from MainSearchBar
$currentTime = now()->toISOString();

use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
use ONGR\ElasticsearchDSL\Query\FullText\MultiMatchQuery;
use Matchish\ScoutElasticSearch\MixedSearch;
use ONGR\ElasticsearchDSL\Search;
use Elastic\Elasticsearch\Client;

$mainBoolQuery = new BoolQuery();

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

$postSearchFields = [
    'post_translations.title_' . $locale . '^3',
    'post_translations.content_' . $locale . '^1',
    'post_translations.excerpt_' . $locale . '^2',
];

$postMultiMatchQuery = new MultiMatchQuery($postSearchFields, $cleanSearch);
$postMultiMatchQuery->addParameter('boost', 4);
$postsBoolQuery->add($postMultiMatchQuery, BoolQuery::MUST);

// Publication filters
$postsBoolQuery->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\ExistsQuery(
        "post_translations.from_{$locale}"
    ),
    BoolQuery::MUST
);
$postsBoolQuery->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery(
        "post_translations.from_{$locale}",
        ['lte' => $currentTime]
    ),
    BoolQuery::MUST
);

$tillFilter = new BoolQuery();
$tillNotExists = new BoolQuery();
$tillNotExists->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\ExistsQuery(
        "post_translations.till_{$locale}"
    ),
    BoolQuery::MUST_NOT
);
$tillFilter->add($tillNotExists, BoolQuery::SHOULD);

$tillInFuture = new BoolQuery();
$tillInFuture->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\ExistsQuery(
        "post_translations.till_{$locale}"
    ),
    BoolQuery::MUST
);
$tillInFuture->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery(
        "post_translations.till_{$locale}",
        ['gte' => $currentTime]
    ),
    BoolQuery::MUST
);
$tillFilter->add($tillInFuture, BoolQuery::SHOULD);
$postsBoolQuery->add($tillFilter, BoolQuery::MUST);

$deletionFilter = new BoolQuery();
$deletionNotExists = new BoolQuery();
$deletionNotExists->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\ExistsQuery(
        "post_translations.deleted_at_{$locale}"
    ),
    BoolQuery::MUST_NOT
);
$deletionFilter->add($deletionNotExists, BoolQuery::SHOULD);

$deletionInFuture = new BoolQuery();
$deletionInFuture->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\ExistsQuery(
        "post_translations.deleted_at_{$locale}"
    ),
    BoolQuery::MUST
);
$deletionInFuture->add(
    new \ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery(
        "post_translations.deleted_at_{$locale}",
        ['gt' => $currentTime]
    ),
    BoolQuery::MUST
);
$deletionFilter->add($deletionInFuture, BoolQuery::SHOULD);
$postsBoolQuery->add($deletionFilter, BoolQuery::MUST);

// Category filter
$categoryIds = timebank_config('main_search_bar.category_ids_posts');
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);
}

$mainBoolQuery->add($postsBoolQuery, BoolQuery::SHOULD);

// Execute search via MixedSearch
try {
    $rawResponse = MixedSearch::search($cleanSearch, function (Client $client, Search $body) use ($mainBoolQuery) {
        $body->addQuery($mainBoolQuery);
        $body->setSize(50);

        return $client->search([
            'index' => implode(',', timebank_config('main_search_bar.model_indices', [])),
            'body' => $body->toArray(),
        ])->asArray();
    })->raw();

    echo "Total hits: " . ($rawResponse['hits']['total']['value'] ?? 0) . PHP_EOL;
    echo "Indices searched: " . json_encode(timebank_config('main_search_bar.model_indices')) . PHP_EOL;
    echo PHP_EOL;

    if (!empty($rawResponse['hits']['hits'])) {
        echo "Raw search results:" . PHP_EOL;
        echo str_repeat('-', 100) . PHP_EOL;
        foreach ($rawResponse['hits']['hits'] as $hit) {
            $modelClass = $hit['_source']['__class_name'] ?? 'N/A';
            $id = $hit['_source']['id'] ?? 'N/A';
            $score = $hit['_score'] ?? 'N/A';

            echo "Model: {$modelClass} | ID: {$id} | Score: {$score}" . PHP_EOL;

            if ($modelClass === 'App\Models\Post') {
                $title = $hit['_source']['post_translations']['title_en'] ?? 'N/A';
                $categoryId = $hit['_source']['category_id'] ?? 'N/A';
                echo "  Title: " . substr($title, 0, 60) . PHP_EOL;
                echo "  Category: {$categoryId}" . PHP_EOL;
            } elseif (in_array($modelClass, ['App\Models\User', 'App\Models\Organization', 'App\Models\Bank'])) {
                $name = $hit['_source']['name'] ?? 'N/A';
                echo "  Name: {$name}" . PHP_EOL;
            }
            echo PHP_EOL;
        }

        // Now process through processPostCard to see if they get filtered
        echo PHP_EOL . "Processing results through processPostCard logic:" . PHP_EOL;
        echo str_repeat('-', 100) . PHP_EOL;

        foreach ($rawResponse['hits']['hits'] as $hit) {
            $modelClass = $hit['_source']['__class_name'] ?? null;
            $modelId = $hit['_source']['id'] ?? null;

            if ($modelClass === 'App\Models\Post' && $modelId) {
                $post = App\Models\Post::with(['translations', 'category'])->find($modelId);
                if ($post) {
                    $translation = $post->translations()->where('locale', $locale)->first();

                    echo "Post ID {$modelId}:" . PHP_EOL;
                    if (!$translation) {
                        echo "  ✗ FILTERED OUT: No translation for locale '{$locale}'" . PHP_EOL;
                        continue;
                    }

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

                    if (!$translation->from) {
                        $isPublished = false;
                        $reason = "No publication date (from is null)";
                    } elseif ($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";
                    }

                    if ($isPublished) {
                        echo "  ✓ PASSED: {$reason}" . PHP_EOL;
                        echo "    Title: {$translation->title}" . PHP_EOL;
                    } else {
                        echo "  ✗ FILTERED OUT: {$reason}" . PHP_EOL;
                    }
                }
            }
        }
    } else {
        echo "No results found!" . PHP_EOL;
    }
} catch (\Exception $e) {
    echo "ERROR: " . $e->getMessage() . PHP_EOL;
    echo "Stack trace:" . PHP_EOL;
    echo $e->getTraceAsString() . PHP_EOL;
}

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