<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Promotion Manager
 * 
 * Handles the creation, management, and validation of Promotion Rules.
 * Supports: Affiliate Codes, Global Promos, Discounts (Fixed/%/Trial).
 */

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

class VMO_Promotion_Manager {

    private $table;

    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'vmo_manager_promotions';
        
        // Ensure table exists
        $this->maybe_create_table();
    }

    /**
     * Create table if not exists
     */
    private function maybe_create_table() {
        global $wpdb;
        if ($wpdb->get_var("SHOW TABLES LIKE '{$this->table}'") != $this->table) {
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE {$this->table} (
                id bigint(20) NOT NULL AUTO_INCREMENT,
                code varchar(50) NOT NULL,
                name varchar(100) NOT NULL,
                type varchar(20) NOT NULL DEFAULT 'percentage', -- percentage, fixed, trial
                value decimal(10,2) NOT NULL DEFAULT 0.00,
                duration_months int(3) NOT NULL DEFAULT 1, -- 0 = forever, 1 = once, 3 = 3 months
                description text,
                linked_affiliate_id bigint(20) DEFAULT 0,
                is_active tinyint(1) DEFAULT 1,
                created_at datetime DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY  (id),
                UNIQUE KEY code (code)
            ) $charset_collate;";
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }

    /**
     * Create or Update a Promotion
     */
    public function save_promotion($data) {
        global $wpdb;
        $defaults = [
            'id' => 0,
            'code' => '',
            'name' => 'New Promo',
            'type' => 'percentage',
            'value' => 0,
            'duration_months' => 1,
            'description' => '',
            'linked_affiliate_id' => 0,
            'is_active' => 1
        ];
        $data = wp_parse_args($data, $defaults);
        
        // Sanitize code
        $data['code'] = strtoupper(trim(sanitize_text_field($data['code'])));
        
        if (empty($data['code'])) {
            return new WP_Error('empty_code', 'Promotion Code cannot be empty.');
        }

        if ($data['id'] > 0) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update($this->table, $data, ['id' => $data['id']]);
            return $data['id'];
        } else {
            // Check existence
            $exists = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$this->table} WHERE code = %s", $data['code']));
            if ($exists) {
                return new WP_Error('duplicate_code', 'Promotion Code already exists.');
            }
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->insert($this->table, $data);
            return $wpdb->insert_id;
        }
    }

    /**
     * Get Promo by Code
     */
    public function get_promo_by_code($code) {
        global $wpdb;
        $code = strtoupper(trim($code));
        return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table} WHERE code = %s AND is_active = 1", $code));
    }

    /**
     * Get All Promos
     */
    public function get_all_promos() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_results("SELECT * FROM {$this->table} ORDER BY created_at DESC");
    }

    /**
     * Calculate Discounted Price
     */
    public function calculate_discount($original_price_cents, $promo) {
        if (!$promo) return $original_price_cents;

        $discounted = $original_price_cents;

        if ($promo->type === 'percentage') {
            // e.g., 20% off
            $discount = $original_price_cents * ($promo->value / 100);
            $discounted = $original_price_cents - $discount;
        } elseif ($promo->type === 'fixed') {
            // e.g., $10 off (value is in currency units, Stripe expects cents)
            $discount_cents = $promo->value * 100;
            $discounted = $original_price_cents - $discount_cents;
        } elseif ($promo->type === 'trial') {
            // Trial implies 100% off for X duration, usually handled via Stripe 'trial_period_days'
            // For simple calculation, if it's the first payment, it might be 0
            // But usually this logic is handled in session creation
            return $original_price_cents; 
        }

        return max(0, round($discounted));
    }
}
