<?php

namespace Give\FormMigration\Controllers;

use Give\Campaigns\Repositories\CampaignRepository;
use Give\Campaigns\ValueObjects\CampaignType;
use Give\DonationForms\V2\Models\DonationForm;
use Give\FormMigration\Actions\GetMigratedFormId;
use Give\FormMigration\Actions\TransferDonations;
use Give\FormMigration\Actions\TransferFormUrl;
use Give\FormMigration\DataTransferObjects\TransferOptions;
use Give\Framework\Database\DB;
use WP_REST_Request;
use WP_REST_Response;

class TransferController
{
    protected $debugContext;

    /**
     * @var WP_REST_Request
     */
    protected $request;

    public function __construct(WP_REST_Request $request)
    {
        $this->request = $request;
    }

    /**
     * @since 4.14.2 updated logic to search for non-core campaigns (e.g., P2P)
     * @since 3.0.0
     */
    public function __invoke(DonationForm $formV2, TransferOptions $options)
    {
        DB::transaction(function() use ($formV2, $options) {

            $v3FormId = (new GetMigratedFormId)($formV2->id);
            TransferFormUrl::from($formV2->id)->to($v3FormId);
            TransferDonations::from($formV2->id)->to($v3FormId);

            // Promote upgraded form to default form
            $campaignRepository = give(CampaignRepository::class);
            if ($campaign = $campaignRepository->getByFormId($formV2->id)) {
                $defaultForm = $campaign->defaultForm();

                if ($defaultForm->id === $formV2->id) {
                    $campaignRepository->updateDefaultCampaignForm($campaign, $v3FormId);
                }
            } else {
                // Fallback: Check for non-core campaigns (e.g., P2P) linked via give_campaigns.form_id
                $campaignData = DB::table('give_campaigns')
                    ->where('form_id', $formV2->id)
                    ->where('campaign_type', CampaignType::CORE, '!=')
                    ->get();

                if ($campaignData) {
                    DB::table('give_campaigns')
                        ->where('id', $campaignData->id)
                        ->update([
                            'form_id' => $v3FormId,
                        ]);
                }
            }

            if($options->shouldDelete()) {
                wp_trash_post($formV2->id);
            }

            wp_update_post(['ID' => $v3FormId, 'post_status' => $formV2->status->getValue()]);
            give_update_meta($v3FormId, 'transferredFormId', true);
        });

        return new WP_REST_Response(array('errors' => [], 'successes' => [
            $formV2->id
        ]));
    }
}
