<?php

namespace App\Http\Controllers\Owner\Booking;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Booking\Application\Report\SalesByPackage\BookingPassengersByMonthReporter;
use App\Modules\Booking\Application\Report\SalesByPackage\BookingSalesByMonthReporter;
use App\Modules\Booking\Application\Report\SalesByPackage\BookingSalesByPackageReporter;
use App\Modules\Booking\Application\Report\SalesByPackage\BookingSalesByTourReporter;
use App\Modules\Booking\Infraestructure\BookingValidators;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;

class BookingReportController extends Controller
{

    public array $names = [];

    public function __construct()
    {
        $this->names = [
            'SalesByPackage' => fn () => (new BookingSalesByPackageReporter())->__invoke(
                dateStart: '2023-01-30 00:00:00',
                dateEnd: '2024-01-30 23:59:59',
                limit: 33
            ),
            'SalesByTour' => fn () => (new BookingSalesByTourReporter())->__invoke(
                dateStart: '2023-01-30 00:00:00',
                dateEnd: '2024-01-30 23:59:59',
                limit: 23
            ),
            'SalesByMonth' => fn () => (new BookingSalesByMonthReporter())->__invoke(
                dateStart: '2023-01-30 00:00:00',
                dateEnd: '2024-01-30 23:59:59'
            ),
            'PassengersByMonth' => fn () => (new BookingPassengersByMonthReporter())->__invoke(
                dateStart: '2023-01-30 00:00:00',
                dateEnd: '2024-01-30 23:59:59'
            )
        ];
    }

    public function __invoke(Request $request)
    {
        (new LaravelValidator)->validate($request->all(), 'Booking', BookingValidators::REPORT);

        if (isset($this->names[$request->input('Name')])) {
            $data = $this->names[$request->input('Name')]();
            echo $this->showTable($data);
        } else {
            return '';
        }
    }

    private function showTable($data)
    {
        if (!isset($data[0])) {
            return '';
        }
        $keys = array_keys(get_object_vars($data[0]));
        $keys = array_map(fn ($key) => "<th>$key</th>", $keys);
        $keys = implode('', $keys);

        $rowValues = '';
        foreach ($data as $element) {
            $values = array_values(get_object_vars($element));
            $values = array_map(fn ($value) => "<td><span>$value</span></td>\n", $values);
            $values = implode('', $values);
            $rowValues .= "<tr>$values</tr>";
        }

        return "<table><tr>$keys</tr>$rowValues</table>";
    }
}
