<?php
/**
 * Plugin Name: Pinery Flow
 * Plugin URI: https://best.uvonokay.com
 * Description: AI-powered Amazon affiliate content pipeline. Scrapes Amazon best sellers, generates lifestyle images with Grok Imagine, writes product copy, and auto-publishes to your Pinery-themed site.
 * Version: 1.3.0
 * Author: PineryPicks
 * License: GPL-2.0+
 * Text Domain: pinery-flow
 */

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

define('PINERY_FLOW_DIR', plugin_dir_path(__FILE__));
define('PINERY_FLOW_URL', plugin_dir_url(__FILE__));
define('PINERY_FLOW_VERSION', '1.3.0');

require_once PINERY_FLOW_DIR . 'inc/class-pipeline.php';
require_once PINERY_FLOW_DIR . 'inc/class-admin.php';
require_once PINERY_FLOW_DIR . 'inc/class-cron.php';
require_once PINERY_FLOW_DIR . 'inc/class-creators-api.php';
require_once PINERY_FLOW_DIR . 'inc/metabox.php';
require_once PINERY_FLOW_DIR . 'inc/ads.php';
require_once PINERY_FLOW_DIR . 'inc/overlays.php';

/**
 * Freemius — License & Auto-Update
 *
 * To activate:
 * 1. Sign up at https://freemius.com
 * 2. Create a Plugin product for Pinery Flow
 * 3. Add to wp-config.php:
 *    define('PINERY_FLOW_FREEMIUS_ID', 1234);
 *    define('PINERY_FLOW_FREEMIUS_PK', 'pk_abc123...');
 * 4. Plugin features will be gated behind license validation.
 *
 * When these constants are NOT defined, the plugin runs unrestricted
 * (development / pre-launch mode).
 */
if (defined('PINERY_FLOW_FREEMIUS_ID') && PINERY_FLOW_FREEMIUS_ID > 0) {
    require_once PINERY_FLOW_DIR . 'inc/freemius-init.php';
}

// Activation
register_activation_hook(__FILE__, function() {
    if (!wp_next_scheduled('pinery_flow_daily_run')) {
        wp_schedule_event(time(), 'pinery_flow_interval', 'pinery_flow_daily_run');
    }
    if (!wp_next_scheduled('pinery_flow_price_refresh')) {
        wp_schedule_event(time(), 'hourly', 'pinery_flow_price_refresh');
    }
    Pinery_Flow_Cron::maybe_create_log_table();
});

// Deactivation
register_deactivation_hook(__FILE__, function() {
    wp_clear_scheduled_hook('pinery_flow_daily_run');
    wp_clear_scheduled_hook('pinery_flow_price_refresh');
});

// Custom cron interval
add_filter('cron_schedules', function($schedules) {
    $interval = (int) get_option('pinery_flow_cron_minutes', 6);
    // Migration: old installs stored minutes (e.g., 360 = 6 hours); new scheme stores hours.
    if ($interval > 168) {
        $interval = max(1, (int) ($interval / 60));
        update_option('pinery_flow_cron_minutes', $interval);
    }
    $schedules['pinery_flow_interval'] = [
        'interval' => max(3600, $interval * 3600),
        'display'  => __('Pinery Flow Interval', 'pinery-flow'),
    ];
    return $schedules;
});

// Initialize
Pinery_Flow_Admin::init();
Pinery_Flow_Cron::init();

// ── Creators API — hourly price refresh cron ──
add_action('pinery_flow_price_refresh', function() {
    Pinery_Creators_API::refresh_published_prices();
});

// ── Creators API — AJAX price lookup (frontend real-time refresh) ──
// Logged-in users: full lookup + can update meta
add_action('wp_ajax_pinery_creators_price', ['Pinery_Creators_API', 'ajax_get_price']);
// Anonymous visitors: read-only, cached prices only — no live API call, no meta write
add_action('wp_ajax_nopriv_pinery_creators_price', ['Pinery_Creators_API', 'ajax_get_price_public']);

// ── Frontend SEO output (no plugin dependency) ──
add_action('wp_head', function() {
    if (!get_option('pinery_flow_auto_seo', 1)) return;
    if (!is_single() && !is_page()) return;
    $post_id = get_the_ID();
    if (!$post_id) return;

    $desc    = get_post_meta($post_id, '_pinery_seo_description', true);
    $kw      = get_post_meta($post_id, '_pinery_seo_keyword', true);
    $img     = get_the_post_thumbnail_url($post_id, 'large') ?: get_post_meta($post_id, '_pinery_amazon_image', true);
    $url     = get_permalink($post_id);
    $title   = get_the_title($post_id);

    if ($desc) {
        echo '<meta name="description" content="' . esc_attr($desc) . '">' . "\n";
    }
    if ($kw) {
        echo '<meta name="keywords" content="' . esc_attr($kw) . '">' . "\n";
    }

    // Open Graph
    echo '<meta property="og:title" content="' . esc_attr($title) . '">' . "\n";
    if ($desc) echo '<meta property="og:description" content="' . esc_attr($desc) . '">' . "\n";
    echo '<meta property="og:url" content="' . esc_url($url) . '">' . "\n";
    echo '<meta property="og:type" content="article">' . "\n";
    if ($img) echo '<meta property="og:image" content="' . esc_url($img) . '">' . "\n";

    // Twitter Card
    echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
    echo '<meta name="twitter:title" content="' . esc_attr($title) . '">' . "\n";
    if ($desc) echo '<meta name="twitter:description" content="' . esc_attr($desc) . '">' . "\n";
    if ($img) echo '<meta name="twitter:image" content="' . esc_url($img) . '">' . "\n";

    // Product schema for rich snippets
    $product_meta = get_post_meta($post_id, '_pinery_flow_product', true);
    $aff_url      = get_post_meta($post_id, 'affiliate_url', true);
    if (!empty($product_meta['title'])) {
        $schema = [
            '@context'    => 'https://schema.org',
            '@type'       => 'Product',
            'name'        => $title,
            'description' => $desc ?: $title,
            'image'       => $img,
            'offers'      => [
                '@type' => 'Offer',
                'url'   => $aff_url ?: $url,
            ],
        ];
        if (!empty($product_meta['price']) && $product_meta['price'] !== 'N/A') {
            $schema['offers']['price'] = preg_replace('/[^0-9.]/', '', $product_meta['price']);
            $schema['offers']['priceCurrency'] = 'USD';
        }
        if (!empty($product_meta['rating']) && $product_meta['rating'] !== 'N/A') {
            $schema['aggregateRating'] = [
                '@type'       => 'AggregateRating',
                'ratingValue' => (float) $product_meta['rating'],
                'bestRating'  => 5,
            ];
        }
        echo '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES) . '</script>' . "\n";
    }
}, 5);
