<?php

namespace Modules\LandingPage\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\LandingPage\Entities\LpPage;
use Modules\BusinessDirectory\Entities\Job as BusinessDirectoryJob; // Alias to avoid conflict
use Modules\BusinessDirectory\Entities\Product as BusinessDirectoryProduct; // Import Product model
use Modules\BusinessDirectory\Entities\Tender as BusinessDirectoryTender; // Import Tender model
use Modules\BusinessDirectory\Entities\Company as BusinessDirectoryCompany; // Import Company model
use Modules\BusinessDirectory\Entities\CompanyProject as BusinessDirectoryCompanyProject; // Import CompanyProject model
use Modules\DigitalVocano\Entities\Project as DigitalVocanoProject; // Import DigitalVocano Project model

class PublicPageController extends Controller
{
    /**
     * Display a dynamic landing page.
     *
     * @param Request $request
     * @param string|null $slug
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse
     */
    public function showPage(Request $request, $slug = null)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $homepageSlug = setting('landingpage_homepage_slug', 'home');

        if (empty($slug)) {
            $slug = $homepageSlug;
        }

        $page = LpPage::where('slug', $slug)->where('is_published', true)->first();

        if (!$page) {
            // If it's the homepage slug and not found, maybe show a default theme homepage or 404
            if ($slug === $homepageSlug) {
                // Check if a default theme homepage view exists
                if (view()->exists("landingpage::themes.{$activeTheme}.home")) {
                    return view("landingpage::themes.{$activeTheme}.home", compact('activeTheme'));
                }
            }
            abort(404);
        }

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

    public function showJobs(Request $request)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $pageTitle = setting('landingpage_jobs_title', 'Job Listings');
        $metaDescription = setting('landingpage_jobs_meta_description', 'Find the latest job opportunities on our platform.');

        $query = BusinessDirectoryJob::query()
            ->where('status', 'open') 
            ->where(function ($query) {
                $query->whereNull('application_deadline')
                      ->orWhere('application_deadline', '>=', now());
            })
            ->with('company');

        // Handle Keywords Search
        if ($request->filled('keywords')) {
            $keywords = $request->input('keywords');
            $query->where(function ($q) use ($keywords) {
                $q->where('title', 'LIKE', "%{$keywords}%")
                  ->orWhere('description', 'LIKE', "%{$keywords}%")
                  ->orWhereHas('company', function ($companyQuery) use ($keywords) {
                      $companyQuery->where('name', 'LIKE', "%{$keywords}%");
                  });
            });
        }

        // Handle Location Search
        if ($request->filled('location')) {
            $location = $request->input('location');
            $query->where('location', 'LIKE', "%{$location}%");
            if (strtolower($location) === 'remote') {
                $query->orWhere('is_remote', true);
            }
        }

        $jobs = $query->orderBy('created_at', 'desc')
                      ->paginate(setting('landingpage_jobs_per_page', 9))
                      ->withQueryString();

        return view("landingpage::themes.{$activeTheme}.jobs", compact(
            'jobs', 
            'pageTitle', 
            'metaDescription',
            'activeTheme' 
        ));
    }

    public function showProducts(Request $request)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $pageTitle = setting('landingpage_products_title', 'Our Products');
        $metaDescription = setting('landingpage_products_meta_description', 'Browse our collection of high-quality products.');

        $query = BusinessDirectoryProduct::query()
            ->where('status', 'published') // Assuming 'published' status
            ->with('company');

        if ($request->filled('keywords')) {
            $keywords = $request->input('keywords');
            $query->where(function ($q) use ($keywords) {
                $q->where('name', 'LIKE', "%{$keywords}%")
                  ->orWhere('description', 'LIKE', "%{$keywords}%");
            });
        }

        $products = $query->orderBy('created_at', 'desc')
                           ->paginate(setting('landingpage_products_per_page', 12))
                           ->withQueryString();

        return view("landingpage::themes.{$activeTheme}.products", compact(
            'products', 
            'pageTitle', 
            'metaDescription',
            'activeTheme'
        ));
    }

    public function showTenders(Request $request)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $pageTitle = setting('landingpage_tenders_title', 'Current Tenders');
        $metaDescription = setting('landingpage_tenders_meta_description', 'Browse current tender opportunities.');

        $query = BusinessDirectoryTender::query()
            ->where('status', 'open') // Assuming 'open' status
            ->where('deadline', '>=', now())
            ->with('company');

        if ($request->filled('keywords')) {
            $keywords = $request->input('keywords');
            $query->where(function ($q) use ($keywords) {
                $q->where('title', 'LIKE', "%{$keywords}%")
                  ->orWhere('description', 'LIKE', "%{$keywords}%");
            });
        }

        if ($request->filled('location')) {
            $query->where('location', 'LIKE', "%{$request->input('location')}%");
        }

        $tenders = $query->orderBy('deadline', 'asc')
                         ->paginate(setting('landingpage_tenders_per_page', 10))
                         ->withQueryString();

        return view("landingpage::themes.{$activeTheme}.tenders", compact(
            'tenders', 
            'pageTitle', 
            'metaDescription',
            'activeTheme'
        ));
    }

    public function showCompanies(Request $request)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $pageTitle = setting('landingpage_companies_title', 'Company Directory');
        $metaDescription = 'Browse our directory of registered companies.';

        $query = BusinessDirectoryCompany::query()
            ->where('status', 'approved');

        if ($request->filled('name')) {
            $query->where('name', 'LIKE', "%{$request->input('name')}%");
        }

        if ($request->filled('location')) {
            $location = $request->input('location');
            $query->where(function ($q) use ($location) {
                $q->where('city', 'LIKE', "%{$location}%")
                  ->orWhere('state', 'LIKE', "%{$location}%")
                  ->orWhere('country', 'LIKE', "%{$location}%")
                  ->orWhere('address', 'LIKE', "%{$location}%");
            });
        }

        $companies = $query->orderBy('name', 'asc')
                           ->paginate(setting('landingpage_companies_per_page', 12))
                           ->withQueryString();

        return view("landingpage::themes.{$activeTheme}.companies", compact(
            'companies', 
            'pageTitle', 
            'metaDescription',
            'activeTheme'
        ));
    }

    public function showCompanyProjects(Request $request)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $pageTitle = setting('landingpage_company_projects_title', 'Company Projects');
        $metaDescription = 'Browse projects undertaken by companies in our directory.';
        
        // Allow filtering by status via query parameter, e.g., /company-projects?status=completed
        $statusFilter = $request->query('status');

        $projectsQuery = BusinessDirectoryCompanyProject::query()
            ->with('company') // Eager load company
            ->orderBy('end_date', 'desc') // Or created_at, name, etc.
            ->orderBy('start_date', 'desc');

        if ($statusFilter && $statusFilter !== 'all') {
            $projectsQuery->where('status', $statusFilter);
        }

        $projects = $projectsQuery->paginate(setting('landingpage_company_projects_per_page', 9))
                                  ->withQueryString();

        return view("landingpage::themes.{$activeTheme}.company-projects", compact(
            'projects', 
            'pageTitle', 
            'metaDescription',
            'activeTheme'
        ));
    }

    public function showPortfolioProjects(Request $request)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $pageTitle = setting('landingpage_portfolio_title', 'Our Portfolio');
        $metaDescription = 'Explore the projects developed by DigitalVocano.';

        $query = DigitalVocanoProject::query()
            ->where('is_published', true);

        // Add search for portfolio if needed, e.g., by name or tags
        // if ($request->filled('keywords')) {
        //     $query->where('name', 'LIKE', "%{$request->input('keywords')}%");
        // }

        $portfolioProjects = $query->orderBy('sort_order', 'asc')
                                   ->orderBy('created_at', 'desc')
                                   ->paginate(setting('landingpage_portfolio_projects_per_page', 9))
                                   ->withQueryString();

        return view("landingpage::themes.{$activeTheme}.portfolio", compact(
            'portfolioProjects', 
            'pageTitle', 
            'metaDescription',
            'activeTheme'
        ));
    }

    public function showNews(Request $request)
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $pageTitle = setting('landingpage_news_title', 'Latest News');
        $metaDescription = setting('landingpage_news_meta_description', 'Stay updated with our latest news and articles.');

        $query = LpPage::query()->where('is_published', true); // Assuming news are LpPages for now
        // Add a filter if news pages have a specific template or category
        // $query->where('theme_template', 'news_article');

        if ($request->filled('keywords')) {
            $keywords = $request->input('keywords');
            $query->where(function ($q) use ($keywords) {
                $q->where('title', 'LIKE', "%{$keywords}%")
                  ->orWhere('content', 'LIKE', "%{$keywords}%"); // Search in content as well
            });
        }

        $newsItems = $query->orderBy('created_at', 'desc')
                           ->paginate(setting('landingpage_news_per_page', 9))
                           ->withQueryString();

        return view("landingpage::themes.{$activeTheme}.news", compact(
            'newsItems',
            'pageTitle',
            'metaDescription',
            'activeTheme'
        ));
    }
}