<?php
/**
 * Gift Products Class
 * Handles gift product rules and eligibility
 */

require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/Product.php';

class Gift {
    private $db;
    private $product;

    public function __construct() {
        $this->db = Database::getInstance();
        $this->product = new Product();
    }

    /**
     * Get active gift rules
     */
    public function getActiveGiftRules() {
        return $this->db->fetchAll(
            "SELECT * FROM gift_products
             WHERE is_active = 1
             AND (valid_from IS NULL OR valid_from <= NOW())
             AND (valid_until IS NULL OR valid_until >= NOW())
             ORDER BY created_at DESC"
        );
    }

    /**
     * Check if cart is eligible for gift products
     */
    public function checkEligibility($cartItems) {
        $eligibleGifts = [];
        $rules = $this->getActiveGiftRules();

        foreach ($rules as $rule) {
            $eligible = false;

            if ($rule['purchase_product_id']) {
                // Check if specific product is in cart with required quantity
                foreach ($cartItems as $item) {
                    if ($item['product_id'] == $rule['purchase_product_id'] 
                        && $item['quantity'] >= $rule['purchase_quantity']) {
                        $eligible = true;
                        break;
                    }
                }
            } elseif ($rule['purchase_min_amount']) {
                // Check if cart total meets minimum amount
                $cartTotal = 0;
                foreach ($cartItems as $item) {
                    $cartTotal += ($item['price_at_add'] * $item['quantity']);
                }
                if ($cartTotal >= $rule['purchase_min_amount']) {
                    $eligible = true;
                }
            }

            if ($eligible) {
                $giftProduct = $this->product->getProductById($rule['gift_product_id']);
                if ($giftProduct && $giftProduct['is_active']) {
                    $eligibleGifts[] = [
                        'rule' => $rule,
                        'product' => $giftProduct,
                        'quantity' => $rule['gift_quantity']
                    ];
                }
            }
        }

        return $eligibleGifts;
    }

    /**
     * Add gift product to cart
     */
    public function addGiftToCart($cartId, $giftProductId, $quantity = 1) {
        // Check if gift already in cart
        $existing = $this->db->fetchOne(
            "SELECT * FROM cart_items WHERE cart_id = ? AND product_id = ?",
            [$cartId, $giftProductId]
        );

        if ($existing) {
            // Update quantity
            $this->db->execute(
                "UPDATE cart_items SET quantity = ? WHERE id = ?",
                [$quantity, $existing['id']]
            );
        } else {
            // Add new gift item
            $product = $this->product->getProductById($giftProductId);
            $price = 0; // Gift products are free

            $this->db->execute(
                "INSERT INTO cart_items (cart_id, product_id, quantity, price_at_add)
                 VALUES (?, ?, ?, ?)",
                [$cartId, $giftProductId, $quantity, $price]
            );
        }

        return true;
    }

    /**
     * Create gift rule
     */
    public function createGiftRule($data) {
        $this->db->execute(
            "INSERT INTO gift_products (name, purchase_product_id, purchase_quantity, purchase_min_amount, 
                                        gift_product_id, gift_quantity, is_active, valid_from, valid_until)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            [
                $data['name'],
                $data['purchase_product_id'] ?? null,
                $data['purchase_quantity'] ?? 1,
                $data['purchase_min_amount'] ?? null,
                $data['gift_product_id'],
                $data['gift_quantity'] ?? 1,
                $data['is_active'] ?? 1,
                $data['valid_from'] ?? null,
                $data['valid_until'] ?? null
            ]
        );
        return $this->db->lastInsertId();
    }

    /**
     * Update gift rule
     */
    public function updateGiftRule($ruleId, $data) {
        return $this->db->execute(
            "UPDATE gift_products
             SET name = ?, purchase_product_id = ?, purchase_quantity = ?, purchase_min_amount = ?,
                 gift_product_id = ?, gift_quantity = ?, is_active = ?, valid_from = ?, valid_until = ?
             WHERE id = ?",
            [
                $data['name'],
                $data['purchase_product_id'] ?? null,
                $data['purchase_quantity'] ?? 1,
                $data['purchase_min_amount'] ?? null,
                $data['gift_product_id'],
                $data['gift_quantity'] ?? 1,
                $data['is_active'] ?? 1,
                $data['valid_from'] ?? null,
                $data['valid_until'] ?? null,
                $ruleId
            ]
        );
    }

    /**
     * Delete gift rule
     */
    public function deleteGiftRule($ruleId) {
        return $this->db->execute(
            "DELETE FROM gift_products WHERE id = ?",
            [$ruleId]
        );
    }
}
?>

