<?php

namespace App\Http\Controllers;

use App\Models\ShareReportSetting;
use App\Services\ShareReportService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class ReportShareController extends Controller
{
    public function index(): View
    {
        $settings = ShareReportSetting::current();
        if (! $settings->share_reports_enabled) {
            abort(404);
        }

        return view('reports.share.index', [
            'settings' => $settings,
            'sizes' => $this->sizes(),
        ]);
    }

    public function preview(Request $request, ShareReportService $shareReportService): View
    {
        $settings = ShareReportSetting::current();
        if (! $settings->share_reports_enabled) {
            abort(404);
        }

        $data = $request->validate([
            'report_type' => ['required', Rule::in(['weekly', 'monthly'])],
            'image_size' => ['required', Rule::in(array_keys($this->sizes()))],
            'image_theme' => ['nullable', Rule::in(['dark', 'light'])],
            'show_profit' => ['nullable', 'boolean'],
        ]);

        $size = $this->sizes()[$data['image_size']];
        $showProfit = $settings->allow_profit_display && $request->boolean('show_profit');

        return view('reports.share.preview', [
            'user' => $request->user(),
            'report' => $shareReportService->build($request->user(), $data['report_type']),
            'imageSize' => $data['image_size'],
            'imageTheme' => $data['image_theme'] ?? 'dark',
            'size' => $size,
            'showProfit' => $showProfit,
            'settings' => $settings,
            'sizes' => $this->sizes(),
        ]);
    }

    public function weekly(Request $request, ShareReportService $shareReportService): View
    {
        $request->merge([
            'report_type' => 'weekly',
            'image_size' => $request->input('image_size', 'story'),
            'image_theme' => $request->input('image_theme', 'dark'),
        ]);

        return $this->preview($request, $shareReportService);
    }

    /**
     * @return array<string,array{label:string,width:int,height:int,ratio:string}>
     */
    private function sizes(): array
    {
        return [
            'story' => ['label' => 'WhatsApp / Instagram Story', 'width' => 1080, 'height' => 1920, 'ratio' => '9 / 16'],
            'square' => ['label' => 'Instagram Post', 'width' => 1080, 'height' => 1080, 'ratio' => '1 / 1'],
            'facebook' => ['label' => 'Facebook Post', 'width' => 1200, 'height' => 630, 'ratio' => '40 / 21'],
        ];
    }
}
