<?php
/**
 * Cart Display Data Handler
 * Handles cart-related data operations for cart display widget
 */

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

// Include the main cart class
require_once plugin_dir_path(__FILE__) . '../../includes/cart.php';

class GGM_Commerce_Cart_Display_Data_Handler {
    
    private $cart;
    
    public function __construct() {
        $this->cart = GGM_Commerce_Cart::get_instance();
    }
    
    /**
     * Get cart instance
     */
    public function get_cart() {
        return $this->cart;
    }
    
    /**
     * Get all cart items with product data
     */
    public function get_cart_items() {
        return $this->cart->get_cart_items_with_products();
    }
    
    /**
     * Check if cart is empty
     */
    public function is_cart_empty() {
        $items = $this->get_cart_items();
        return empty($items);
    }
    
    /**
     * Get cart total
     */
    public function get_cart_total() {
        return $this->cart->get_cart_total();
    }
    
    /**
     * Get cart item count
     */
    public function get_cart_count() {
        return $this->cart->get_cart_count();
    }
    
    /**
     * Update cart item quantity
     */
    public function update_cart_item_quantity($cart_key, $quantity) {
        return $this->cart->update_quantity($cart_key, $quantity);
    }
    
    /**
     * Remove item from cart
     */
    public function remove_cart_item($cart_key) {
        return $this->cart->remove_item($cart_key);
    }
    
    /**
     * Clear entire cart
     */
    public function clear_cart() {
        return $this->cart->clear_cart();
    }
    
    /**
     * Get cart item data by cart key
     */
    public function get_cart_item($cart_key) {
        $items = $this->get_cart_items();
        foreach ($items as $item) {
            if ($item->cart_key === $cart_key) {
                return $item;
            }
        }
        return null;
    }
    
    /**
     * Calculate line total for an item
     */
    public function calculate_line_total($price, $quantity) {
        return floatval($price) * intval($quantity);
    }
    
    /**
     * Format price for display
     */
    public function format_price($price) {
        return '$' . number_format(floatval($price), 2);
    }
    
    /**
     * Get product image for cart item
     */
    public function get_product_image($image_id, $size = 'thumbnail') {
        if (empty($image_id)) {
            return $this->get_placeholder_image();
        }
        
        return wp_get_attachment_image($image_id, $size, false, [
            'style' => 'width: 60px; height: 60px; object-fit: cover;'
        ]);
    }
    
    /**
     * Get placeholder image when no product image exists
     */
    public function get_placeholder_image() {
        return '<div class="product-image placeholder">
                    <div style="width: 60px; height: 60px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border-radius: 4px;">
                        <span style="font-size: 12px; color: #666;">No Image</span>
                    </div>
                </div>';
    }
    
    /**
     * Validate cart item quantity
     */
    public function validate_quantity($quantity, $max_stock = null) {
        $quantity = intval($quantity);
        
        // Minimum quantity is 0 (for removal)
        if ($quantity < 0) {
            $quantity = 0;
        }
        
        // Check against maximum stock if provided
        if ($max_stock !== null && $quantity > $max_stock) {
            $quantity = $max_stock;
        }
        
        // Maximum quantity limit
        if ($quantity > 999) {
            $quantity = 999;
        }
        
        return $quantity;
    }
    
    /**
     * Get cart summary data
     */
    public function get_cart_summary() {
        $items = $this->get_cart_items();
        $total_items = count($items);
        $total_quantity = 0;
        $subtotal = 0;
        
        foreach ($items as $item) {
            $total_quantity += intval($item->quantity);
            $subtotal += floatval($item->line_total);
        }
        
        return [
            'total_items' => $total_items,
            'total_quantity' => $total_quantity,
            'subtotal' => $subtotal,
            'formatted_subtotal' => $this->format_price($subtotal)
        ];
    }
    
    /**
     * Check if cart needs update
     */
    public function cart_needs_update() {
        // You could implement logic here to check if cart data has changed
        // since last load, for cache invalidation purposes
        return false;
    }
    
    /**
     * Get default continue shopping URL
     */
    public function get_default_continue_shopping_url() {
        // Try common shop page URLs
        $shop_urls = [
            home_url('/shop'),
            home_url('/products'),
            home_url('/store'),
            home_url()
        ];
        
        foreach ($shop_urls as $url) {
            if ($this->url_exists($url)) {
                return $url;
            }
        }
        
        return home_url();
    }
    
    /**
     * Check if URL exists (simple check)
     */
    private function url_exists($url) {
        // Simple check - in a real implementation you might want to
        // check if the page actually exists
        return !empty($url);
    }
    
    /**
     * Get checkout URL
     */
    public function get_checkout_url() {
        // Return checkout page URL - customize based on your setup
        return home_url('/checkout');
    }
    
    /**
     * Get cart update data for AJAX responses
     */
    public function get_cart_update_data() {
        $summary = $this->get_cart_summary();
        
        return [
            'cart_count' => $summary['total_quantity'],
            'cart_total' => $summary['formatted_subtotal'],
            'cart_items' => $this->get_cart_items(),
            'needs_update' => $this->cart_needs_update(),
            'timestamp' => current_time('timestamp')
        ];
    }
    
    /**
     * Sanitize cart item data
     */
    public function sanitize_cart_item_data($data) {
        if (!is_object($data)) {
            return null;
        }
        
        return (object) [
            'cart_key' => sanitize_text_field($data->cart_key ?? ''),
            'product_id' => intval($data->product_id ?? 0),
            'name' => sanitize_text_field($data->name ?? ''),
            'price' => floatval($data->price ?? 0),
            'quantity' => intval($data->quantity ?? 1),
            'line_total' => floatval($data->line_total ?? 0),
            'image_id' => intval($data->image_id ?? 0)
        ];
    }
    
    /**
     * Get cart errors or validation messages
     */
    public function get_cart_messages() {
        // Implement cart message system if needed
        return [];
    }
    
    /**
     * Apply cart discount or coupon
     */
    public function apply_discount($coupon_code) {
        // Implement discount/coupon functionality if needed
        return false;
    }
    
    /**
     * Get shipping options
     */
    public function get_shipping_options() {
        // Implement shipping calculation if needed
        return [];
    }
    
    /**
     * Get tax amount
     */
    public function get_tax_amount() {
        // Implement tax calculation if needed
        return 0;
    }

    /**
     * Get cart totals with per-product tax breakdown
     * Returns gross (inc VAT), net (ex VAT), and tax amounts
     */
    public function get_cart_totals_with_tax() {
        $tax = ggm_commerce_tax();
        $items = $this->get_cart_items();

        $gross_total = 0;
        $net_total = 0;
        $tax_total = 0;

        foreach ($items as $item) {
            $product_id = isset($item->id) ? (int) $item->id : 0;
            $line_total = floatval($item->line_total);

            // Prices are stored inclusive of VAT, calculate the breakdown
            $product_tax = $tax->calculate_product_tax($line_total, $product_id);

            $gross_total += $product_tax['gross'];
            $net_total += $product_tax['net'];
            $tax_total += $product_tax['tax'];
        }

        return [
            'gross' => round($gross_total, 2),
            'net' => round($net_total, 2),
            'tax' => round($tax_total, 2),
        ];
    }
}