<?php

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

// --- User Card Related Queries ---

/**
 * Adds a new (encrypted) card for a user if it doesn't already exist.
 */
function addUserCard(int $user_id, string $cardNumber): bool {
    $cardNumberClean = preg_replace('/\D/', '', $cardNumber);
    if (strlen($cardNumberClean) !== 16) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Attempted to add invalid card format for user {$user_id}.\n", FILE_APPEND);
        return false;
    }

    $encryptedCard = encryptCardNumber($cardNumberClean); // Assumes EncryptionHelpers is loaded
    if ($encryptedCard === null) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Card encryption failed for user {$user_id}. Card not added.\n", FILE_APPEND);
        return false;
    }
    $maskedCard = maskCardNumber($cardNumberClean); // Assumes GeneralHelpers is loaded

    try {
        // Check if this exact masked card already exists and is active for the user
        $stmt_check = pdo()->prepare("SELECT id FROM user_cards WHERE user_id = ? AND card_number_masked = ? AND status = 'active'");
        $stmt_check->execute([$user_id, $maskedCard]);
        if ($stmt_check->fetchColumn()) {
            // Card already exists and is active, consider it a success
            return true;
        }

        // Insert the new card
        $stmt = pdo()->prepare("INSERT INTO user_cards (user_id, card_number_encrypted, card_number_masked, status) VALUES (?, ?, ?, 'active')");
        return $stmt->execute([$user_id, $encryptedCard, $maskedCard]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error adding user card for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        // Check for unique constraint violation if applicable based on schema
        return false;
    }
}

/**
 * Gets a list of active cards (masked numbers) for a user.
 */
function getUserCards(int $user_id, string $status = 'active'): array {
    try {
        $stmt = pdo()->prepare("SELECT id, card_number_masked FROM user_cards WHERE user_id = ? AND status = ? ORDER BY added_at DESC");
        $stmt->execute([$user_id, $status]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting user cards for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

/**
 * Gets the decrypted card number by its ID and user ID.
 * Use with extreme caution and only when absolutely necessary.
 */
function getDecryptedUserCardById(int $user_card_id, int $user_id): ?string {
    try {
        $stmt = pdo()->prepare("SELECT card_number_encrypted FROM user_cards WHERE id = ? AND user_id = ? AND status = 'active'");
        $stmt->execute([$user_card_id, $user_id]);
        $encryptedCard = $stmt->fetchColumn();

        if ($encryptedCard) {
            $decryptedCard = decryptCardNumber($encryptedCard); // Assumes EncryptionHelpers is loaded
            if ($decryptedCard === null) {
                // Log decryption failure but don't expose details
                file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Failed to decrypt card ID {$user_card_id} for user {$user_id}.\n", FILE_APPEND);
                return null;
            }
            return $decryptedCard;
        }
        return null; // Card not found or not active
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting user card by ID ({$user_card_id}) for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return null;
    }
}

/**
 * Deletes (soft deletes) a user's card.
 */
function deleteUserCard(int $user_card_id, int $user_id): bool {
     try {
        // Use soft delete by changing status
        $stmt = pdo()->prepare("UPDATE user_cards SET status = 'deleted' WHERE id = ? AND user_id = ?");
        $deleted = $stmt->execute([$user_card_id, $user_id]);
        return $deleted && $stmt->rowCount() > 0;
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error deleting card {$user_card_id} for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

?>