<?php

namespace App\Classes\Modules\Affiliate\ControllersLogic;

use App\Classes\Modules\Affiliate\Services\UpdatesAffiliate;
use App\Classes\Modules\Affiliate\DataTransferObjects\AffiliateObject;
use App\Models\Affiliate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UpdateAffiliateLogic
{
    /** @var UpdatesAffiliate */
    private $updatesAffiliate;

    /**
     * @param UpdatesAffiliate $updatesAffiliate
     */
    public function __construct(UpdatesAffiliate $updatesAffiliate)
    {
        $this->updatesAffiliate = $updatesAffiliate;
    }

    /**
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function execute(Request $request, int $id): JsonResponse
    {
        $affiliate = Affiliate::findOrFail($id);

        $isActive = $request->input('is_active', $affiliate->is_active);
        // Convert string 'true'/'false' to boolean if needed
        if (is_string($isActive)) {
            $isActive = filter_var($isActive, FILTER_VALIDATE_BOOLEAN);
        }
        $isActive = (bool) $isActive;

        $object = new AffiliateObject(
            $affiliate->code, // Keep existing code
            $request->input('campaign_name'),
            $request->input('campaign_description'),
            $isActive
        );

        $affiliate = $this->updatesAffiliate->execute($affiliate, $object);

        return response()->json([
            'message' => 'Affiliate code updated successfully',
            'data' => $affiliate
        ]);
    }
}

