<?php
require_once __DIR__ . '/../config.php';

class Order {
    private $pdo;
    
    public function __construct() {
        $this->pdo = getDBConnection();
    }
    
    // Create order
    public function create($userId, $items, $shippingAddress, $paymentMethod, $notes = '') {
        try {
            $this->pdo->beginTransaction();
            
            // Generate order number
            $orderNumber = 'RSC-' . date('Ymd') . '-' . strtoupper(uniqid());
            
            // Calculate total
            $totalAmount = 0;
            foreach ($items as $item) {
                $totalAmount += $item['price'] * $item['quantity'];
            }
            
            // Insert order
            $stmt = $this->pdo->prepare("
                INSERT INTO orders (user_id, order_number, total_amount, shipping_address, payment_method, notes)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$userId, $orderNumber, $totalAmount, $shippingAddress, $paymentMethod, $notes]);
            $orderId = $this->pdo->lastInsertId();
            
            // Insert order items
            $stmt = $this->pdo->prepare("
                INSERT INTO order_items (order_id, product_id, product_name, product_price, quantity, size, color, subtotal)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            foreach ($items as $item) {
                $subtotal = $item['price'] * $item['quantity'];
                $stmt->execute([
                    $orderId,
                    $item['id'],
                    $item['name'],
                    $item['price'],
                    $item['quantity'],
                    $item['size'],
                    $item['color'],
                    $subtotal
                ]);
            }
            
            $this->pdo->commit();
            
            return ['success' => true, 'order_id' => $orderId, 'order_number' => $orderNumber];
        } catch (Exception $e) {
            $this->pdo->rollBack();
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    // Get orders by user
    public function getByUser($userId) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC
        ");
        $stmt->execute([$userId]);
        return $stmt->fetchAll();
    }
    
    // Get order by ID
    public function getById($orderId) {
        $stmt = $this->pdo->prepare("SELECT * FROM orders WHERE id = ?");
        $stmt->execute([$orderId]);
        $order = $stmt->fetch();
        
        if ($order) {
            $stmt = $this->pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
            $stmt->execute([$orderId]);
            $order['items'] = $stmt->fetchAll();
        }
        
        return $order;
    }
    
    // Get order by order number
    public function getByOrderNumber($orderNumber) {
        $stmt = $this->pdo->prepare("SELECT * FROM orders WHERE order_number = ?");
        $stmt->execute([$orderNumber]);
        $order = $stmt->fetch();
        
        if ($order) {
            $stmt = $this->pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
            $stmt->execute([$order['id']]);
            $order['items'] = $stmt->fetchAll();
        }
        
        return $order;
    }
    
    // Get all orders (admin)
    public function getAll($status = null, $search = null, $limit = 50, $offset = 0) {
        $sql = "SELECT o.*, u.full_name, u.email FROM orders o LEFT JOIN users u ON o.user_id = u.id";
        $params = [];
        
        $conditions = [];
        if ($status) {
            $conditions[] = "o.status = ?";
            $params[] = $status;
        }
        if ($search) {
            $conditions[] = "(o.order_number LIKE ? OR u.full_name LIKE ? OR u.email LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        
        if (!empty($conditions)) {
            $sql .= " WHERE " . implode(" AND ", $conditions);
        }
        
        $sql .= " ORDER BY o.created_at DESC LIMIT ? OFFSET ?";
        $params[] = $limit;
        $params[] = $offset;
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        
        return $stmt->fetchAll();
    }
    
    // Update order status
    public function updateStatus($orderId, $status) {
        $stmt = $this->pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
        $stmt->execute([$status, $orderId]);
        return ['success' => true, 'message' => 'Order status updated'];
    }
    
    // Update payment status
    public function updatePaymentStatus($orderId, $paymentStatus) {
        $stmt = $this->pdo->prepare("UPDATE orders SET payment_status = ? WHERE id = ?");
        $stmt->execute([$paymentStatus, $orderId]);
        
        if ($paymentStatus === 'paid') {
            $this->updateStatus($orderId, 'processing');
        }
        
        return ['success' => true, 'message' => 'Payment status updated'];
    }
    
    // Get order count
    public function getCount($status = null) {
        $sql = "SELECT COUNT(*) FROM orders";
        $params = [];
        
        if ($status) {
            $sql .= " WHERE status = ?";
            $params[] = $status;
        }
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchColumn();
    }
    
    // Get revenue
    public function getRevenue($startDate = null, $endDate = null) {
        $sql = "SELECT SUM(total_amount) FROM orders WHERE payment_status = 'paid'";
        $params = [];
        
        if ($startDate) {
            $sql .= " AND created_at >= ?";
            $params[] = $startDate;
        }
        if ($endDate) {
            $sql .= " AND created_at <= ?";
            $params[] = $endDate;
        }
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchColumn() ?: 0;
    }
    
    // Get recent orders
    public function getRecent($limit = 10) {
        $stmt = $this->pdo->prepare("
            SELECT o.*, u.full_name FROM orders o 
            LEFT JOIN users u ON o.user_id = u.id 
            ORDER BY o.created_at DESC LIMIT ?
        ");
        $stmt->execute([$limit]);
        return $stmt->fetchAll();
    }

    // Get detailed revenue records (for table)
    public function getRevenueDetails() {
        $stmt = $this->pdo->prepare("
            SELECT o.order_number, u.full_name, o.total_amount, o.status, o.created_at
            FROM orders o
            LEFT JOIN users u ON o.user_id = u.id
            WHERE o.payment_status = 'paid'
            ORDER BY o.created_at DESC
        ");
        
        $stmt->execute();
        return $stmt->fetchAll();
    }

    // Get revenue grouped by date (for chart)
    public function getRevenueByDate() {
        $stmt = $this->pdo->prepare("
            SELECT DATE(created_at) as date, SUM(total_amount) as total
            FROM orders
            WHERE payment_status = 'paid'
            GROUP BY DATE(created_at)
            ORDER BY date ASC
        ");
        
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
