<?php

namespace Modules\LandingPage\Http\Controllers;

use App\Http\Controllers\Controller;
use Modules\BusinessDirectory\Entities\Job;
use Modules\BusinessDirectory\Entities\Company;
use Modules\BusinessDirectory\Entities\Product;
use Modules\BusinessDirectory\Entities\Tender;
// use Modules\News\Entities\Article; // Assuming a future News module and Article model
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str; // Add Str import
use Modules\LandingPage\Entities\LpPage; // For fallback or if some items are LpPages

class FrontendController extends Controller
{
    /**
     * Display a single job listing.
     *
     * @param string $slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showJob($slug)
    {
        $job = Job::where('slug', $slug)->where('status', 'open')->firstOrFail(); // Assuming 'open' status for active jobs
        $activeTheme = setting('landingpage_active_theme', 'general');

        // Construct a simple $page object for meta tags and layout compatibility
        $page = (object) [
            'title' => $job->title,
            'meta_title' => $job->meta_title ?? $job->title . ' - ' . setting('site_name'),
            'meta_description' => $job->meta_description ?? Str::limit(strip_tags($job->description), 160),
            'meta_keywords' => $job->meta_keywords ?? ($job->skills_required && is_array($job->skills_required) ? implode(', ', $job->skills_required) : ''),
            'content' => null, // Single job pages usually don't have LpPage content
            'sections' => collect(), // No LpPage sections for a single job usually
        ];

        // Ensure the theme view exists
        if (!View::exists("landingpage::themes.{$activeTheme}.templates.job_single")) {
            abort(404, "Job single template for theme '{$activeTheme}' not found.");
        }

        return view("landingpage::themes.{$activeTheme}.templates.job_single", compact('job', 'page', 'activeTheme'));
    }

    /**
     * Display a single company profile.
     *
     * @param string $slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showCompany($slug)
    {
        $company = Company::where('slug', $slug)
            ->where('status', 'approved')
            ->with([
                'companyType', // Already there, good.
                'products' => function ($query) {
                    $query->where('status', 'published')->latest()->take(4); // Show 4 latest published products
                },
                'jobs' => function ($query) {
                    $query->where('status', 'open')
                          ->where(fn($q) => $q->whereNull('application_deadline')->orWhere('application_deadline', '>=', now()))
                          ->latest()->take(3); // Show 3 latest open jobs
                },
                'tenders' => function ($query) {
                    $query->where('status', 'open')
                          ->where('deadline', '>=', now())
                          ->latest()->take(3); // Show 3 latest open tenders
                }
            ])->firstOrFail();
        $activeTheme = setting('landingpage_active_theme', 'general');

        $page = (object) [
            'title' => $company->name,
            'meta_title' => $company->meta_title ?? $company->name . ' Profile - ' . setting('site_name'),
            'meta_description' => $company->meta_description ?? Str::limit(strip_tags($company->description), 160),
            'meta_keywords' => $company->meta_keywords ?? $company->name,
            'content' => null,
            'sections' => collect(),
        ];

        if (!View::exists("landingpage::themes.{$activeTheme}.templates.company_single")) {
            abort(404, "Company single template for theme '{$activeTheme}' not found.");
        }

        return view("landingpage::themes.{$activeTheme}.templates.company_single", compact('company', 'page', 'activeTheme'));
    }

    /**
     * Display a single product.
     *
     * @param string $slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showProduct($slug)
    {
        $product = Product::where('slug', $slug)->where('status', 'active')->firstOrFail(); // Assuming 'active' status
        $activeTheme = setting('landingpage_active_theme', 'general');

        $page = (object) [
            'title' => $product->name,
            'meta_title' => $product->meta_title ?? $product->name . ' - ' . setting('site_name'),
            'meta_description' => $product->meta_description ?? Str::limit(strip_tags($product->description), 160),
            'meta_keywords' => $product->meta_keywords ?? $product->name,
            'content' => null,
            'sections' => collect(),
        ];

        if (!View::exists("landingpage::themes.{$activeTheme}.templates.product_single")) {
            abort(404, "Product single template for theme '{$activeTheme}' not found.");
        }

        return view("landingpage::themes.{$activeTheme}.templates.product_single", compact('product', 'page', 'activeTheme'));
    }

    /**
     * Display a single tender.
     *
     * @param string $slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showTender($slug)
    {
        $tender = Tender::where('slug', $slug)->where('status', 'open')->firstOrFail(); // Assuming 'open' status
        $activeTheme = setting('landingpage_active_theme', 'general');

        $page = (object) [
            'title' => $tender->title,
            'meta_title' => $tender->meta_title ?? $tender->title . ' - ' . setting('site_name'),
            'meta_description' => $tender->meta_description ?? Str::limit(strip_tags($tender->description), 160),
            'meta_keywords' => $tender->meta_keywords ?? $tender->title,
            'content' => null,
            'sections' => collect(),
        ];

        if (!View::exists("landingpage::themes.{$activeTheme}.templates.tender_single")) {
            abort(404, "Tender single template for theme '{$activeTheme}' not found.");
        }

        return view("landingpage::themes.{$activeTheme}.templates.tender_single", compact('tender', 'page', 'activeTheme'));
    }

    /**
     * Display a single news article.
     * (Placeholder - assuming a News module and Article model in the future)
     *
     * @param string $slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showNewsArticle($slug)
    {
        // $article = \Modules\News\Entities\Article::where('slug', $slug)->where('is_published', true)->firstOrFail();
        // For now, let's simulate an article or use LpPage if news are managed as pages
        $article = LpPage::where('slug', $slug)->where('is_published', true)->firstOrFail(); // Example if news are LpPages
        $activeTheme = setting('landingpage_active_theme', 'general');

        $page = $article; // Use the LpPage object directly

        if (!View::exists("landingpage::themes.{$activeTheme}.templates.news_single")) {
            abort(404, "News single template for theme '{$activeTheme}' not found.");
        }
        return view("landingpage::themes.{$activeTheme}.templates.news_single", compact('article', 'page', 'activeTheme'));
    }

    /**
     * Display all products for a specific company.
     *
     * @param string $company_slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showCompanyProducts($company_slug)
    {
        $company = Company::where('slug', $company_slug)->where('status', 'approved')->firstOrFail();
        $activeTheme = setting('landingpage_active_theme', 'general');

        $products = $company->products()
            ->where('status', 'published')
            ->latest()
            ->paginate(setting('theme_company_products_per_page', 12)); // Configurable items per page

        $page = (object) [
            'title' => 'Products from ' . $company->name,
            'meta_title' => 'Products from ' . $company->name . ' - ' . setting('site_name'),
            'meta_description' => 'Browse all products offered by ' . $company->name . '.',
            'meta_keywords' => $company->name . ', products, ' . $company->companyType->name ?? '',
            'content' => null,
            'sections' => collect(),
        ];

        $viewPath = "landingpage::themes.{$activeTheme}.templates.company_products_listing";
        if (!View::exists($viewPath)) {
            abort(404, "Company products listing template for theme '{$activeTheme}' not found.");
        }

        return view($viewPath, compact('company', 'products', 'page', 'activeTheme'));
    }

    /**
     * Display all jobs for a specific company.
     *
     * @param string $company_slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showCompanyJobs($company_slug)
    {
        $company = Company::where('slug', $company_slug)->where('status', 'approved')->firstOrFail();
        $activeTheme = setting('landingpage_active_theme', 'general');

        $jobs = $company->jobs()
            ->where('status', 'open')
            ->where(fn($q) => $q->whereNull('application_deadline')->orWhere('application_deadline', '>=', now()))
            ->latest()
            ->paginate(setting('theme_company_jobs_per_page', 10));

        $page = (object) [
            'title' => 'Job Openings at ' . $company->name,
            'meta_title' => 'Job Openings at ' . $company->name . ' - ' . setting('site_name'),
            'meta_description' => 'Find current job openings and career opportunities at ' . $company->name . '.',
            'meta_keywords' => $company->name . ', jobs, careers, ' . $company->companyType->name ?? '',
            'content' => null,
            'sections' => collect(),
        ];

        $viewPath = "landingpage::themes.{$activeTheme}.templates.company_jobs_listing";
        if (!View::exists($viewPath)) {
            abort(404, "Company jobs listing template for theme '{$activeTheme}' not found.");
        }

        return view($viewPath, compact('company', 'jobs', 'page', 'activeTheme'));
    }

    /**
     * Display all tenders for a specific company.
     *
     * @param string $company_slug
     * @return \Illuminate\Contracts\View\View
     */
    public function showCompanyTenders($company_slug)
    {
        $company = Company::where('slug', $company_slug)->where('status', 'approved')->firstOrFail();
        $activeTheme = setting('landingpage_active_theme', 'general');

        $tenders = $company->tenders()
            ->where('status', 'open')
            ->where('deadline', '>=', now())
            ->latest()
            ->paginate(setting('theme_company_tenders_per_page', 10));

        $page = (object) [
            'title' => 'Tenders from ' . $company->name,
            'meta_title' => 'Tenders from ' . $company->name . ' - ' . setting('site_name'),
            'meta_description' => 'View current tenders and procurement opportunities from ' . $company->name . '.',
            'meta_keywords' => $company->name . ', tenders, procurement, ' . $company->companyType->name ?? '',
            'content' => null,
            'sections' => collect(),
        ];

        $viewPath = "landingpage::themes.{$activeTheme}.templates.company_tenders_listing";
        if (!View::exists($viewPath)) {
            abort(404, "Company tenders listing template for theme '{$activeTheme}' not found.");
        }

        return view($viewPath, compact('company', 'tenders', 'page', 'activeTheme'));
    }
}