<?php

namespace App\Http\Controllers;

use App\Models\Package;
use App\Settings\SiteSettings;
use Illuminate\Http\Request;

class PackageController extends Controller
{
    public function index()
    {
        $packages = Package::published()
            ->withCount('tests')
            ->orderBy('sort_order')
            ->get();

        // Group packages by price tier for frontend tabs
        $priceTiers = $this->groupByPriceTier($packages);

        $siteSettings = app(SiteSettings::class);

        return view('packages.index', compact('packages', 'priceTiers', 'siteSettings'));
    }

    public function show(Package $package)
    {
        // Check if package is active and not a draft
        if (!$package->is_active || $package->is_draft) {
            abort(404);
        }

        // Eager load tests with their categories
        $package->load(['tests.category']);

        // Get tests grouped by category
        $groupedTests = $package->testsGroupedByCategory();

        // Load related packages
        try {
            $relatedPackages = Package::published()
                ->where('id', '!=', $package->id)
                ->withCount('tests')
                ->inRandomOrder()
                ->limit(3)
                ->get();
        } catch (\Exception $e) {
            $relatedPackages = collect();
        }

        $siteSettings = app(SiteSettings::class);

        return view('packages.show', compact('package', 'groupedTests', 'relatedPackages', 'siteSettings'));
    }

    /**
     * Preview route (auth-protected for admins).
     */
    public function preview(Package $package)
    {
        $package->load(['tests.category']);
        $groupedTests = $package->testsGroupedByCategory();

        $relatedPackages = Package::published()
            ->where('id', '!=', $package->id)
            ->withCount('tests')
            ->inRandomOrder()
            ->limit(3)
            ->get();

        $isPreview = true;
        $siteSettings = app(SiteSettings::class);

        return view('packages.show', compact('package', 'groupedTests', 'relatedPackages', 'isPreview', 'siteSettings'));
    }

    /**
     * Group packages into price tiers.
     */
    private function groupByPriceTier($packages)
    {
        $tiers = [
            ['label' => 'الكل', 'label_en' => 'All', 'min' => 0, 'max' => PHP_INT_MAX, 'packages' => collect()],
            ['label' => 'أقل من 100 ريال', 'label_en' => 'Under 100 SAR', 'min' => 0, 'max' => 99.99, 'packages' => collect()],
            ['label' => '100 - 199 ريال', 'label_en' => '100 - 199 SAR', 'min' => 100, 'max' => 199.99, 'packages' => collect()],
            ['label' => '200 - 399 ريال', 'label_en' => '200 - 399 SAR', 'min' => 200, 'max' => 399.99, 'packages' => collect()],
            ['label' => '400+ ريال', 'label_en' => '400+ SAR', 'min' => 400, 'max' => PHP_INT_MAX, 'packages' => collect()],
        ];

        foreach ($packages as $package) {
            $price = $package->final_price;
            $tiers[0]['packages']->push($package);

            for ($i = 1; $i < count($tiers); $i++) {
                if ($price >= $tiers[$i]['min'] && $price <= $tiers[$i]['max']) {
                    $tiers[$i]['packages']->push($package);
                    break;
                }
            }
        }

        return collect($tiers)->filter(function ($tier, $index) {
            return $index === 0 || $tier['packages']->count() > 0;
        })->values();
    }
}
