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

class Promotion {
    private $db;
    private $conn;
    
    public function __construct() {
        $this->db = new Database();
        $this->conn = $this->db->getConnection();
    }
    
    public function getAllPromotions() {
        $query = "SELECT * FROM promotions ORDER BY start_date DESC";
        $result = $this->conn->query($query);
        $promotions = $result->fetch_all(MYSQLI_ASSOC);
        
        // Get applicable products for each promotion
        foreach ($promotions as &$promo) {
            $promo['applicable_products'] = $this->getPromotionProducts($promo['id']);
        }
        
        return $promotions;
    }
    
    public function getActivePromotions() {
        $query = "SELECT * FROM promotions 
                  WHERE is_active = 1 AND CURDATE() BETWEEN start_date AND end_date 
                  ORDER BY start_date DESC";
        
        $result = $this->conn->query($query);
        $promotions = $result->fetch_all(MYSQLI_ASSOC);
        
        foreach ($promotions as &$promo) {
            $promo['applicable_products'] = $this->getPromotionProducts($promo['id']);
        }
        
        return $promotions;
    }
    
    public function getPromotion($promotionId) {
        $query = "SELECT * FROM promotions WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("s", $promotionId);
        $stmt->execute();
        
        $promo = $stmt->get_result()->fetch_assoc();
        if ($promo) {
            $promo['applicable_products'] = $this->getPromotionProducts($promotionId);
        }
        
        return $promo;
    }
    
    public function getPromotionProducts($promotionId) {
        $query = "SELECT pp.product_id, p.name FROM promotion_products pp 
                  LEFT JOIN products p ON pp.product_id = p.id 
                  WHERE pp.promotion_id = ?";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("s", $promotionId);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }
    
    public function createPromotion($data) {
        $this->conn->begin_transaction();
        
        try {
            $query = "INSERT INTO promotions (id, name, type, discount_type, discount_value, 
                      start_date, end_date, is_active, description, bogo_buy, bogo_get) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $this->conn->prepare($query);
            $stmt->bind_param("ssssdssssii", $data['id'], $data['name'], $data['type'], 
                              $data['discount_type'], $data['discount_value'], $data['start_date'], 
                              $data['end_date'], $data['is_active'], $data['description'], 
                              $data['bogo_buy'], $data['bogo_get']);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create promotion");
            }
            
            // Insert applicable products
            if (isset($data['applicable_products']) && is_array($data['applicable_products'])) {
                $productQuery = "INSERT INTO promotion_products (promotion_id, product_id) VALUES (?, ?)";
                
                foreach ($data['applicable_products'] as $productId) {
                    $productStmt = $this->conn->prepare($productQuery);
                    $productStmt->bind_param("si", $data['id'], $productId);
                    if (!$productStmt->execute()) {
                        throw new Exception("Failed to link product to promotion");
                    }
                }
            }
            
            $this->conn->commit();
            return ['success' => true];
        } catch (Exception $e) {
            $this->conn->rollback();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    public function getAppliedDiscount($productId, $quantity = 1, $totalAmount = 0) {
        $query = "SELECT * FROM promotions p 
                  LEFT JOIN promotion_products pp ON p.id = pp.promotion_id 
                  WHERE p.is_active = 1 AND CURDATE() BETWEEN p.start_date AND p.end_date 
                  AND (pp.product_id = ? OR pp.product_id IS NULL) 
                  ORDER BY p.discount_value DESC LIMIT 1";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $productId);
        $stmt->execute();
        $promo = $stmt->get_result()->fetch_assoc();
        
        if (!$promo) return 0;
        
        if ($promo['discount_type'] == 'percentage') {
            return ($totalAmount * $promo['discount_value']) / 100;
        } elseif ($promo['discount_type'] == 'fixed') {
            return $promo['discount_value'];
        }
        
        return 0;
    }
}
?>
