<?php

// Prevent direct script access
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

// --- Discount Code Related Queries ---

/**
 * Creates a new discount code.
 */
function createDiscountCode(string $code, string $type, string $value, ?int $max_uses, ?string $expires_at): bool {
    if (!in_array($type, ['percentage', 'fixed_amount'])) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Invalid discount type '{$type}' provided for code '{$code}'.\n", FILE_APPEND);
        return false;
    }
    try {
        $stmt = pdo()->prepare("INSERT INTO discount_codes (code, type, value, max_uses, expires_at, is_active) VALUES (?, ?, ?, ?, ?, TRUE)");
        return $stmt->execute([strtoupper($code), $type, $value, $max_uses, $expires_at]);
    } catch (PDOException $e) {
        // Catch duplicate code error
        if ($e->errorInfo[1] == 1062) { // 1062 = Duplicate entry
             file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Info: Attempted to create duplicate discount code '{$code}'.\n", FILE_APPEND);
        } else {
             file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error creating discount code '{$code}': " . $e->getMessage() . "\n", FILE_APPEND);
        }
        return false;
    }
}

/**
 * Fetches an active discount code by its code string.
 */
function getDiscountCode(string $code): ?array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM discount_codes WHERE code = ? AND is_active = TRUE");
        $stmt->execute([strtoupper($code)]);
        return $stmt->fetch() ?: null;
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting discount code '{$code}': " . $e->getMessage() . "\n", FILE_APPEND);
        return null;
    }
}

/**
 * Validates a discount code based on existence, expiry, and usage limits.
 */
function validateDiscountCode(string $code): array {
    $discount = getDiscountCode($code);
    if (!$discount) {
        return ['valid' => false, 'message' => 'کد تخفیف وارد شده معتبر نیست.'];
    }
    // Check expiry date (only if set)
    if ($discount['expires_at'] !== null && strtotime($discount['expires_at']) < time()) {
        return ['valid' => false, 'message' => 'این کد تخفیف منقضی شده است.'];
    }
    // Check usage limit (only if set)
    if ($discount['max_uses'] !== null && $discount['use_count'] >= $discount['max_uses']) {
        return ['valid' => false, 'message' => 'ظرفیت استفاده از این کد تخفیف به اتمام رسیده است.'];
    }
    return ['valid' => true, 'discount' => $discount];
}

/**
 * Applies a discount to a total amount.
 */
function applyDiscountToTotal(string $total, array $discount): array {
    $discount_amount = '0.00';
    $new_total = $total;

    try {
        $discount_value_str = (string)($discount['value'] ?? '0');

        if ($discount['type'] === 'percentage' && bccomp($discount_value_str, '0', BC_SCALE) > 0) {
            $percentage = bcdiv($discount_value_str, '100', 4); // Use higher precision
            $calculated_discount = bcmul($percentage, $total, BC_SCALE);
            // Discount cannot exceed the total
            $discount_amount = (bccomp($calculated_discount, $total, BC_SCALE) > 0) ? $total : $calculated_discount;
        } elseif ($discount['type'] === 'fixed_amount' && bccomp($discount_value_str, '0', BC_SCALE) > 0) {
            // Discount cannot exceed the total
            $discount_amount = (bccomp($discount_value_str, $total, BC_SCALE) > 0) ? $total : $discount_value_str;
        }

        $new_total = bcsub($total, $discount_amount, BC_SCALE);
        // Ensure total doesn't go below zero
        if (bccomp($new_total, '0', BC_SCALE) < 0) {
            $new_total = '0.00';
        }

    } catch(Exception $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error applying discount logic: " . $e->getMessage() . "\n", FILE_APPEND);
        // Return original total if calculation fails
        return ['new_total' => $total, 'discount_amount' => '0.00'];
    }
    return ['new_total' => $new_total, 'discount_amount' => $discount_amount];
}

/**
 * Increments the usage count of a discount code.
 */
function incrementDiscountUseCount(string $code): bool {
    try {
        $stmt = pdo()->prepare("UPDATE discount_codes SET use_count = use_count + 1 WHERE code = ?");
        return $stmt->execute([strtoupper($code)]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error incrementing discount '{$code}' use: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

/**
 * Gets a paginated list of all discount codes.
 */
function getAllDiscountCodes(int $offset = 0, int $limit = 10): array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM discount_codes ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting discount codes: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

/**
 * Counts all discount codes.
 */
function countAllDiscountCodes(): int {
    try {
        return (int)pdo()->query("SELECT COUNT(*) FROM discount_codes")->fetchColumn();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error counting discount codes: " . $e->getMessage() . "\n", FILE_APPEND);
        return 0;
    }
}

/**
 * Toggles the active status of a discount code.
 */
function toggleDiscountCodeStatus(int $code_id): bool {
    try {
        // Use a subquery to toggle based on current value
        $stmt = pdo()->prepare("UPDATE discount_codes SET is_active = NOT is_active WHERE id = ?");
        return $stmt->execute([$code_id]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error toggling discount status for ID {$code_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

/**
 * Checks if a discount code already exists.
 */
function discountCodeExists(string $code): bool {
    try {
        $stmt = pdo()->prepare("SELECT COUNT(*) FROM discount_codes WHERE code = ?");
        $stmt->execute([strtoupper($code)]);
        return (int)$stmt->fetchColumn() > 0;
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error checking if discount code exists ('{$code}'): " . $e->getMessage() . "\n", FILE_APPEND);
        return true; // Assume exists on error to prevent duplicates
    }
}

?>
