<?php
/**
 * Order management for Subscription System
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/includes
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

/**
 * Order management class
 */
class Subs_Sys_Order {

    /**
     * Create a new order
     *
     * @param array $order_data Order data
     * @return int|false Order ID or false on failure
     */
    public static function create_order($order_data) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_orders';
        
        // Generate order number if not provided
        if (empty($order_data['order_number'])) {
            $order_data['order_number'] = self::generate_order_number();
        }
        
        // Set default values
        $order_data = wp_parse_args($order_data, [
            'status' => 'completed',
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql'),
        ]);
        
        // Insert order
        $result = $wpdb->insert($table_name, $order_data);
        
        if ($result === false) {
            Subscription_System::debug_log('Failed to create order: ' . $wpdb->last_error);
            return false;
        }
        
        $order_id = $wpdb->insert_id;
        Subscription_System::debug_log('Order created with ID: ' . $order_id);
        
        // Trigger action for other plugins
        do_action('subs_sys_order_created', $order_id, $order_data);
        
        return $order_id;
    }
    
    /**
     * Get order by ID
     *
     * @param int $order_id Order ID
     * @return object|null Order object or null if not found
     */
    public static function get_order($order_id) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_orders';
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE id = %d",
            $order_id
        ));
    }
    
    /**
     * Get orders by user ID
     *
     * @param int $user_id User ID
     * @param int $limit Number of orders to return (0 for all)
     * @param int $offset Offset for pagination
     * @return array Array of order objects
     */
    public static function get_user_orders($user_id, $limit = 0, $offset = 0) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_orders';
        
        $sql = $wpdb->prepare(
            "SELECT * FROM $table_name WHERE user_id = %d ORDER BY created_at DESC",
            $user_id
        );
        
        if ($limit > 0) {
            $sql .= $wpdb->prepare(" LIMIT %d, %d", $offset, $limit);
        }
        
        return $wpdb->get_results($sql);
    }
    
    /**
     * Get orders by subscription ID
     *
     * @param int $subscription_id Subscription ID
     * @return array Array of order objects
     */
    public static function get_subscription_orders($subscription_id) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_orders';
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table_name WHERE subscription_id = %d ORDER BY created_at DESC",
            $subscription_id
        ));
    }
    
    /**
     * Update order status
     *
     * @param int $order_id Order ID
     * @param string $status New status
     * @return bool True on success, false on failure
     */
    public static function update_order_status($order_id, $status) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_orders';
        
        $result = $wpdb->update(
            $table_name,
            ['status' => $status, 'updated_at' => current_time('mysql')],
            ['id' => $order_id]
        );
        
        if ($result === false) {
            Subscription_System::debug_log('Failed to update order status: ' . $wpdb->last_error);
            return false;
        }
        
        // Trigger action for other plugins
        do_action('subs_sys_order_status_updated', $order_id, $status);
        
        return true;
    }
    
    /**
     * Generate a unique order number
     *
     * @return string Order number
     */
    private static function generate_order_number() {
        $prefix = 'ORD-';
        $timestamp = time();
        $random = mt_rand(1000, 9999);
        
        return $prefix . $timestamp . '-' . $random;
    }
    
    /**
     * Get order count by status
     *
     * @param string $status Order status
     * @return int Number of orders
     */
    public static function get_order_count_by_status($status) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_orders';
        
        return $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE status = %s",
            $status
        ));
    }
    
    /**
     * Get total revenue
     *
     * @param string $period Period (all, today, this_month, this_year)
     * @return float Total revenue
     */
    public static function get_total_revenue($period = 'all') {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_orders';
        
        $where = "WHERE status = 'completed'";
        
        switch ($period) {
            case 'today':
                $where .= " AND DATE(transaction_date) = CURDATE()";
                break;
            case 'this_month':
                $where .= " AND MONTH(transaction_date) = MONTH(CURDATE()) AND YEAR(transaction_date) = YEAR(CURDATE())";
                break;
            case 'this_year':
                $where .= " AND YEAR(transaction_date) = YEAR(CURDATE())";
                break;
        }
        
        return $wpdb->get_var("SELECT SUM(amount) FROM $table_name $where");
    }
} 