<?php
/**
 * Database migration script for WP Digital Download
 * Adds missing columns and updates database schema
 */

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

function wpdd_migrate_database() {
    global $wpdb;
    
    // Check if available_at column exists in wpdd_creator_earnings table
    $column_exists = $wpdb->get_results(
        "SHOW COLUMNS FROM {$wpdb->prefix}wpdd_creator_earnings LIKE 'available_at'"
    );
    
    if (empty($column_exists)) {
        // Add the missing available_at column
        $result = $wpdb->query(
            "ALTER TABLE {$wpdb->prefix}wpdd_creator_earnings 
             ADD COLUMN available_at datetime DEFAULT NULL AFTER payout_status,
             ADD INDEX available_at (available_at)"
        );
        
        if ($result !== false) {
            error_log('WPDD Migration: Successfully added available_at column to wpdd_creator_earnings table');
            
            // Update existing pending earnings to have an available_at date
            $holding_days = intval(get_option('wpdd_earnings_holding_days', 15));
            $wpdb->query(
                $wpdb->prepare(
                    "UPDATE {$wpdb->prefix}wpdd_creator_earnings 
                     SET available_at = DATE_ADD(created_at, INTERVAL %d DAY)
                     WHERE payout_status = 'pending' AND available_at IS NULL",
                    $holding_days
                )
            );
            
            return true;
        } else {
            error_log('WPDD Migration Error: Failed to add available_at column - ' . $wpdb->last_error);
            return false;
        }
    }
    
    return true; // Column already exists
}

// Run migration if accessed directly (for manual execution)
if (basename($_SERVER['SCRIPT_FILENAME']) === 'wpdd-db-migrate.php') {
    wpdd_migrate_database();
}