<?php

namespace MailerPress\Actions;

use MailerPress\Core\Attributes\Action;
use MailerPress\Core\Enums\Tables;

class CampaignDetectUnlock
{
    #[Action('admin_init')]
    function maybeUnlockCampaign()
    {
        if (!isset($_COOKIE['mailerpress_lock_data'])) {
            return;
        }

        $lockData = json_decode(stripslashes($_COOKIE['mailerpress_lock_data']), true);

        if (empty($lockData['userId'])) {
            return;
        }

        global $wpdb;
        $table = Tables::get(Tables::MAILERPRESS_CAMPAIGNS);

        $campaign_id = intval($lockData['campaignId']);
        $user_id = intval($lockData['userId']);
        $current_url = $_SERVER['REQUEST_URI'];

        // If user left the editor page, unlock the campaign
        if (strpos($current_url, '/mailerpress-editor') === false) {
            $wpdb->update(
                $table,
                [
                    'editing_user_id' => null,
                    'editing_started_at' => null
                ],
                [
                    'campaign_id' => $campaign_id,
                    'editing_user_id' => $user_id
                ]
            );

            // Optionally remove the cookie
            setcookie('mailerpress_lock_data', '', time() - 3600, '/');
        }
    }
}