<?php
/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 * 
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 * 
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 * 
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 * 
 * END OF HEADER
 */


/**
 * Content Block: class-sponsor-block.php
 */

if (!defined('ABSPATH')) {
	exit;
}

require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/content-blocks/class-base-block.php';

class CastConductor_Sponsor_Block extends CastConductor_Base_Block {
	public $type = 'sponsor';
	public $display_name = 'Sponsor';
	public $description = 'Sponsor message / slate with scheduling.';

    public function get_field_schema() {
		$schema = parent::get_field_schema();
		$schema['content']['fields']['sponsor_name'] = [
			'type' => 'text',
			'label' => 'Sponsor Name',
			'default' => ''
		];
		$schema['content']['fields']['sponsor_logo'] = [
			'type' => 'text',
			'label' => 'Logo URL',
			'default' => ''
		];
		return $schema;
	}

    /**
     * Fetch live data for sponsor block (single item)
     */
    public function fetch_data($data_config) {
        $items = $this->fetch_items($data_config, 1);
        
        if (!empty($items)) {
            return $items[0];
        }
        
        // Fallback if no data
        return [
            'title' => 'No Active Sponsors',
            'content' => 'Sponsor campaigns will appear here when active',
            'featured_media_url' => $this->get_fallback_artwork(),
            'artwork_url' => $this->get_fallback_artwork(),
            'status' => 'awaiting_campaigns',
            'source' => 'WordPress Content Manager'
        ];
    }

    /**
     * Fetch list of sponsors
     */
    public function fetch_items($data_config, $limit = 20) {
        // Use local controller to avoid HTTP loopback issues
        if (!class_exists('CastConductor_Content_Controller')) {
            require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/api/class-content-controller.php';
        }
        
        $controller = new CastConductor_Content_Controller();
        $request = new WP_REST_Request('GET', '/castconductor/v5/content/sponsors/active');
        $request->set_param('limit', $limit);
        
        $response = $controller->get_active_sponsors($request);
        $mapped_items = [];
        
        if ($response && !is_wp_error($response)) {
            $data = $response->get_data();
            $items = $data['data'] ?? [];
            
            foreach ($items as $item) {
                $mapped_items[] = [
                    'title' => $this->strip_quotes($item['title'] ?? 'Untitled Sponsor'),
                    'content' => $this->strip_quotes($item['content'] ?? 'No sponsor content'),
                    'featured_media_url' => $item['featured_media_url'] ?? $this->get_fallback_artwork(),
                    'artwork_url' => $item['featured_media_url'] ?? $this->get_fallback_artwork(),
                    'status' => 'live_data',
                    'source' => 'WordPress Content Manager'
                ];
            }
        }
        
        return $mapped_items;
    }

    private function strip_quotes($text) {
        return trim($text, '"\'');
    }

    private function get_fallback_artwork() {
        return plugins_url('assets/images/branding-square.png', CASTCONDUCTOR_PLUGIN_DIR . 'castconductor-v5.php');
    }
}
