<?php

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

class WPDD_Orders {
    
    public static function create_order($product_id, $customer_data, $payment_method = 'free') {
        global $wpdb;
        
        $product = get_post($product_id);
        if (!$product || $product->post_type !== 'wpdd_product') {
            return false;
        }
        
        $price = get_post_meta($product_id, '_wpdd_price', true);
        $sale_price = get_post_meta($product_id, '_wpdd_sale_price', true);
        $is_free = get_post_meta($product_id, '_wpdd_is_free', true);
        
        $amount = $is_free ? 0 : (($sale_price && $sale_price < $price) ? $sale_price : $price);
        
        $order_number = 'WPDD-' . strtoupper(uniqid());
        
        $customer_id = 0;
        if (is_user_logged_in()) {
            $current_user = wp_get_current_user();
            $customer_id = $current_user->ID;
            $customer_email = $current_user->user_email;
            $customer_name = $current_user->display_name;
        } else {
            $customer_email = $customer_data['email'];
            $customer_name = $customer_data['name'];
        }
        
        $result = $wpdb->insert(
            $wpdb->prefix . 'wpdd_orders',
            array(
                'order_number' => $order_number,
                'product_id' => $product_id,
                'customer_id' => $customer_id,
                'creator_id' => $product->post_author,
                'status' => ($payment_method === 'free' || $amount == 0) ? 'completed' : 'pending',
                'payment_method' => $payment_method,
                'amount' => $amount,
                'currency' => 'USD',
                'customer_email' => $customer_email,
                'customer_name' => $customer_name,
                'purchase_date' => current_time('mysql')
            ),
            array('%s', '%d', '%d', '%d', '%s', '%s', '%f', '%s', '%s', '%s', '%s')
        );
        
        if ($result) {
            $order_id = $wpdb->insert_id;
            
            if ($payment_method === 'free' || $amount == 0) {
                self::complete_order($order_id);
            }
            
            return $order_id;
        }
        
        return false;
    }
    
    public static function complete_order($order_id, $transaction_id = null) {
        global $wpdb;
        
        $order = self::get_order($order_id);
        if (!$order) {
            return false;
        }
        
        $update_data = array(
            'status' => 'completed'
        );
        
        if ($transaction_id) {
            $update_data['transaction_id'] = $transaction_id;
        }
        
        $result = $wpdb->update(
            $wpdb->prefix . 'wpdd_orders',
            $update_data,
            array('id' => $order_id),
            array('%s', '%s'),
            array('%d')
        );
        
        if ($result) {
            self::generate_download_link($order_id);
            
            self::send_order_emails($order_id);
            
            update_post_meta(
                $order->product_id, 
                '_wpdd_sales_count',
                intval(get_post_meta($order->product_id, '_wpdd_sales_count', true)) + 1
            );
            
            do_action('wpdd_order_completed', $order_id);
            
            return true;
        }
        
        return false;
    }
    
    public static function get_order($order_id) {
        global $wpdb;
        
        if (is_numeric($order_id)) {
            return $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}wpdd_orders WHERE id = %d",
                $order_id
            ));
        } else {
            return $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}wpdd_orders WHERE order_number = %s",
                $order_id
            ));
        }
    }
    
    public static function get_orders($args = array()) {
        global $wpdb;
        
        $defaults = array(
            'status' => '',
            'customer_id' => 0,
            'creator_id' => 0,
            'product_id' => 0,
            'limit' => 20,
            'offset' => 0,
            'orderby' => 'purchase_date',
            'order' => 'DESC'
        );
        
        $args = wp_parse_args($args, $defaults);
        
        $where = array('1=1');
        
        if ($args['status']) {
            $where[] = $wpdb->prepare("status = %s", $args['status']);
        }
        
        if ($args['customer_id']) {
            $where[] = $wpdb->prepare("customer_id = %d", $args['customer_id']);
        }
        
        if ($args['creator_id']) {
            $where[] = $wpdb->prepare("creator_id = %d", $args['creator_id']);
        }
        
        if ($args['product_id']) {
            $where[] = $wpdb->prepare("product_id = %d", $args['product_id']);
        }
        
        $where_clause = implode(' AND ', $where);
        
        $query = $wpdb->prepare(
            "SELECT o.*, p.post_title as product_name, 
                    u.display_name as customer_display_name,
                    c.display_name as creator_display_name
             FROM {$wpdb->prefix}wpdd_orders o
             LEFT JOIN {$wpdb->posts} p ON o.product_id = p.ID
             LEFT JOIN {$wpdb->users} u ON o.customer_id = u.ID
             LEFT JOIN {$wpdb->users} c ON o.creator_id = c.ID
             WHERE {$where_clause}
             ORDER BY {$args['orderby']} {$args['order']}
             LIMIT %d OFFSET %d",
            $args['limit'],
            $args['offset']
        );
        
        return $wpdb->get_results($query);
    }
    
    private static function generate_download_link($order_id) {
        global $wpdb;
        
        $token = wp_hash(uniqid() . $order_id . time());
        $expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));
        
        $wpdb->insert(
            $wpdb->prefix . 'wpdd_download_links',
            array(
                'order_id' => $order_id,
                'token' => $token,
                'expires_at' => $expires_at,
                'max_downloads' => 5,
                'created_at' => current_time('mysql')
            ),
            array('%d', '%s', '%s', '%d', '%s')
        );
        
        return $token;
    }
    
    private static function send_order_emails($order_id) {
        $order = self::get_order($order_id);
        if (!$order) {
            return;
        }
        
        self::send_customer_email($order);
        
        self::send_creator_email($order);
        
        self::send_admin_email($order);
    }
    
    private static function send_customer_email($order) {
        global $wpdb;
        
        $product = get_post($order->product_id);
        $download_link = $wpdb->get_var($wpdb->prepare(
            "SELECT token FROM {$wpdb->prefix}wpdd_download_links 
             WHERE order_id = %d ORDER BY id DESC LIMIT 1",
            $order->id
        ));
        
        $download_url = add_query_arg(array(
            'wpdd_download_token' => $download_link
        ), home_url());
        
        $subject = sprintf(
            __('Your purchase of %s from %s', 'wp-digital-download'),
            $product->post_title,
            get_bloginfo('name')
        );
        
        $message = sprintf(
            __("Hi %s,\n\nThank you for your purchase!\n\n", 'wp-digital-download'),
            $order->customer_name
        );
        $message .= sprintf(__("Order Number: %s\n", 'wp-digital-download'), $order->order_number);
        $message .= sprintf(__("Product: %s\n", 'wp-digital-download'), $product->post_title);
        
        if ($order->amount > 0) {
            $message .= sprintf(__("Amount: $%s\n", 'wp-digital-download'), number_format($order->amount, 2));
        }
        
        $message .= "\n" . __("Download your product here:\n", 'wp-digital-download');
        $message .= $download_url . "\n\n";
        $message .= __("This download link will expire in 7 days.\n\n", 'wp-digital-download');
        
        if ($order->customer_id) {
            $purchases_url = get_permalink(get_option('wpdd_purchases_page_id'));
            $message .= sprintf(
                __("You can also access your downloads anytime from your account:\n%s\n\n", 'wp-digital-download'),
                $purchases_url
            );
        }
        
        $message .= sprintf(__("Best regards,\n%s", 'wp-digital-download'), get_bloginfo('name'));
        
        wp_mail($order->customer_email, $subject, $message);
    }
    
    private static function send_creator_email($order) {
        $creator = get_userdata($order->creator_id);
        if (!$creator) {
            return;
        }
        
        $product = get_post($order->product_id);
        
        $subject = sprintf(
            __('New sale: %s', 'wp-digital-download'),
            $product->post_title
        );
        
        $message = sprintf(
            __("Hi %s,\n\nYou have a new sale!\n\n", 'wp-digital-download'),
            $creator->display_name
        );
        $message .= sprintf(__("Product: %s\n", 'wp-digital-download'), $product->post_title);
        $message .= sprintf(__("Customer: %s\n", 'wp-digital-download'), $order->customer_name);
        $message .= sprintf(__("Amount: $%s\n", 'wp-digital-download'), number_format($order->amount, 2));
        $message .= sprintf(__("Order Number: %s\n", 'wp-digital-download'), $order->order_number);
        $message .= "\n" . sprintf(
            __("View your sales dashboard:\n%s\n", 'wp-digital-download'),
            admin_url()
        );
        
        wp_mail($creator->user_email, $subject, $message);
    }
    
    private static function send_admin_email($order) {
        $admin_email = get_option('wpdd_admin_email', get_option('admin_email'));
        
        if (!$admin_email) {
            return;
        }
        
        $product = get_post($order->product_id);
        
        $subject = sprintf(
            __('[%s] New Digital Download Sale', 'wp-digital-download'),
            get_bloginfo('name')
        );
        
        $message = __("A new digital download sale has been completed.\n\n", 'wp-digital-download');
        $message .= sprintf(__("Order Number: %s\n", 'wp-digital-download'), $order->order_number);
        $message .= sprintf(__("Product: %s\n", 'wp-digital-download'), $product->post_title);
        $message .= sprintf(__("Customer: %s (%s)\n", 'wp-digital-download'), $order->customer_name, $order->customer_email);
        $message .= sprintf(__("Amount: $%s\n", 'wp-digital-download'), number_format($order->amount, 2));
        $message .= sprintf(__("Payment Method: %s\n", 'wp-digital-download'), $order->payment_method);
        
        if ($order->transaction_id) {
            $message .= sprintf(__("Transaction ID: %s\n", 'wp-digital-download'), $order->transaction_id);
        }
        
        wp_mail($admin_email, $subject, $message);
    }
}