<?php


namespace App\Classes\Modules\Bookings\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Bookings\Services\ListsBookings;
use App\Classes\Modules\Bookings\Standards\Rules\CanListBookings;
use App\Http\Resources\AutocountSalesInvoiceBookingResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ListBookingsSalesInvoiceLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Retrieved Bookings with Sales Invoice',
            'message' => 'You have successfully retrieved a list of Bookings with Sales Invoice'
        ];
    }

    /** @var CanListBookings */
    private $canListBookings;

    /** @var ListsBookings */
    private $listsBookings;

    /**
     * ListBookingsSalesInvoiceLogic constructor.
     * @param CanListBookings $canListBookings
     * @param ListsBookings $listsBookings
     */
    public function __construct(CanListBookings $canListBookings, ListsBookings $listsBookings)
    {
        $this->canListBookings = $canListBookings;
        $this->listsBookings = $listsBookings;
    }

    public function logic(Request $request) : JsonResponse
    {
        // $this->canListBookings->passes(); //cief todo: 90 - apipub

        $filters = $request->input('filters');
        if (is_string($filters)) {
            $filters = json_decode($filters, true);
        }

        if (!is_array($filters)) {
            return response()->json([
                'message' => 'Invalid filters format. Expected JSON object.',
                'payload' => new \stdClass(),
            ], 400);
        }

        // Only these filters are allowed
        $allowedKeys = ['per_page', 'status', 'order_by', 'date_range', 'date_range_no_data', 'date_range_with_data'];

        $extra = array_diff(array_keys($filters), $allowedKeys);
        if (!empty($extra)) {
            return response()->json([
                'message' => 'Invalid filter(s) provided: ' . implode(', ', $extra),
                'payload' => new \stdClass(),
            ], 400);
        }

        // Required filters that must always exist
        $alwaysRequired = ['per_page', 'status'];

        $missing = array_diff($alwaysRequired, array_keys($filters));
        if (!empty($missing)) {
            return response()->json([
                'message' => 'Missing required filter(s): ' . implode(', ', $missing),
                'payload' => new \stdClass(),
            ], 400);
        }

        if ((int) $filters['status'] !== 3) {
            return response()->json([
                'message' => 'Invalid status value.',
                'payload' => new \stdClass(),
            ], 400);
        }

        // Required at least one of: date_range or date_range_no_data
        if (!isset($filters['date_range']) && !isset($filters['date_range_no_data']) && !isset($filters['date_range_with_data'])) {
            return response()->json([
                'message' => 'Either "date_range" or "date_range_no_data" or "date_range_with_data" filter is required.',
                'payload' => new \stdClass(),
            ], 400);
        }
        $filters = $request->input('filters');
        if (is_string($filters)) {
            $decoded = json_decode($filters, true) ?? [];
            unset($decoded['status']);
            $decoded['order_by'] = ['column' => 'id', 'DESC' => false];
            $request->merge(['filters' => json_encode($decoded)]);
        }

        $query = $this->listsBookings->execute($this->listsBookings->deserializeFilters($request->input('filters')));

        return $this->collectionResponse(AutocountSalesInvoiceBookingResource::collection($query));

    }
}
