<?php
/**
 * Loyalty Points Class
 * Handles loyalty points system
 */

require_once __DIR__ . '/Database.php';

class Loyalty {
    private $db;

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

    /**
     * Get user loyalty points balance
     */
    public function getUserPoints($userId) {
        $result = $this->db->fetchOne(
            "SELECT loyalty_points FROM users WHERE id = ?",
            [$userId]
        );
        return $result['loyalty_points'] ?? 0;
    }

    /**
     * Add loyalty points to user
     */
    public function addPoints($userId, $points, $orderId = null, $description = null) {
        // Add to user balance
        $this->db->execute(
            "UPDATE users SET loyalty_points = loyalty_points + ? WHERE id = ?",
            [$points, $userId]
        );

        // Log transaction
        $this->db->execute(
            "INSERT INTO loyalty_points (user_id, points, type, order_id, description)
             VALUES (?, ?, 'earned', ?, ?)",
            [$userId, $points, $orderId, $description]
        );

        return true;
    }

    /**
     * Use loyalty points
     */
    public function usePoints($userId, $points, $orderId = null, $description = null) {
        $currentPoints = $this->getUserPoints($userId);

        if ($currentPoints < $points) {
            return ['success' => false, 'message' => 'Insufficient points'];
        }

        // Deduct from user balance
        $this->db->execute(
            "UPDATE users SET loyalty_points = loyalty_points - ? WHERE id = ?",
            [$points, $userId]
        );

        // Log transaction
        $this->db->execute(
            "INSERT INTO loyalty_points (user_id, points, type, order_id, description)
             VALUES (?, ?, 'used', ?, ?)",
            [$userId, $points, $orderId, $description]
        );

        return ['success' => true];
    }

    /**
     * Calculate points from order total
     */
    public function calculatePointsFromOrder($orderTotal) {
        return floor($orderTotal * LOYALTY_POINTS_PER_RON);
    }

    /**
     * Get loyalty points history
     */
    public function getPointsHistory($userId, $limit = 50) {
        return $this->db->fetchAll(
            "SELECT * FROM loyalty_points
             WHERE user_id = ?
             ORDER BY created_at DESC
             LIMIT ?",
            [$userId, $limit]
        );
    }

    /**
     * Get user history (alias for getPointsHistory)
     */
    public function getUserHistory($userId, $limit = 50) {
        return $this->getPointsHistory($userId, $limit);
    }

    /**
     * Convert points to discount amount
     */
    public function pointsToDiscount($points) {
        // 1 point = 1 RON discount
        return $points;
    }
}
?>

