<?php
class Transaction {
    private $db;
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    // Create transaction
    public function create($userId, $items, $subtotal, $tax, $discount, $paymentMethod) {
        try {
            $invoiceNumber = $this->generateInvoiceNumber($userId);
            $totalAmount = $subtotal + $tax - $discount;
            
            // Insert transaction
            $transactionId = $this->db->insert('transactions', [
                'user_id' => $userId,
                'invoice_number' => $invoiceNumber,
                'subtotal' => $subtotal,
                'tax_amount' => $tax,
                'discount_amount' => $discount,
                'total_amount' => $totalAmount,
                'payment_method' => $paymentMethod,
                'payment_status' => 'paid',
                'cashier_name' => $_SESSION['name'] ?? 'System'
            ]);
            
            // Insert transaction items
            foreach ($items as $item) {
                $this->db->insert('transaction_items', [
                    'transaction_id' => $transactionId,
                    'product_id' => $item['product_id'],
                    'product_name' => $item['product_name'],
                    'sku' => $item['sku'],
                    'quantity' => $item['quantity'],
                    'unit_price' => $item['unit_price'],
                    'subtotal' => $item['quantity'] * $item['unit_price']
                ]);
                
                // Update stock
                $this->updateProductStock($userId, $item['product_id'], -$item['quantity'], 'Transaction #' . $invoiceNumber);
            }
            
            return ['success' => true, 'transaction_id' => $transactionId, 'invoice_number' => $invoiceNumber];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    // Get transaction
    public function getTransaction($transactionId) {
        return $this->db->selectOne(
            "SELECT * FROM transactions WHERE id = ?",
            [$transactionId]
        );
    }
    
    // Get transaction items
    public function getTransactionItems($transactionId) {
        return $this->db->select(
            "SELECT * FROM transaction_items WHERE transaction_id = ? ORDER BY id ASC",
            [$transactionId]
        );
    }
    
    // Get user transactions
    public function getUserTransactions($userId, $limit = 20, $offset = 0) {
        $limit = intval($limit);
        $offset = intval($offset);
        return $this->db->select(
            "SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT $limit OFFSET $offset",
            [$userId]
        );
    }
    
    // Generate invoice number
    private function generateInvoiceNumber($userId) {
        $date = date('dmY');
        $random = strtoupper(substr(md5(time()), 0, 4));
        return "INV-$date-$random";
    }
    
    // Update product stock
    private function updateProductStock($userId, $productId, $quantityChange, $reference) {
        $product = $this->db->selectOne(
            "SELECT quantity FROM products WHERE id = ? AND user_id = ?",
            [$productId, $userId]
        );
        
        if ($product) {
            $oldQty = $product['quantity'];
            $newQty = $oldQty + $quantityChange;
            
            $this->db->update('products', [
                'quantity' => max(0, $newQty)
            ], ['id' => $productId]);
            
            // Record stock history
            $this->db->insert('stock_history', [
                'user_id' => $userId,
                'product_id' => $productId,
                'operation_type' => $quantityChange < 0 ? 'out' : 'in',
                'quantity_change' => abs($quantityChange),
                'old_quantity' => $oldQty,
                'new_quantity' => max(0, $newQty),
                'notes' => $reference
            ]);
        }
    }
    
    // Get daily sales
    public function getDailySales($userId, $date) {
        $stats = $this->db->select(
            "SELECT COUNT(*) as total_transactions, SUM(total_amount) as total_sales, 
                    AVG(total_amount) as average_sale FROM transactions 
             WHERE user_id = ? AND DATE(created_at) = ?",
            [$userId, $date]
        );
        
        return $stats[0] ?? ['total_transactions' => 0, 'total_sales' => 0, 'average_sale' => 0];
    }
    
    // Get transaction count
    public function getTransactionCount($userId) {
        return $this->db->count('transactions', ['user_id' => $userId]);
    }
}
