CREATE VIEW cards_data AS
SELECT
    cards.card_id AS card_id,
    cards.desk_id AS desk_id,
    cards.last_timing AS last_timing,
    cards.next_timing AS next_timing,
    cards.record_question AS record_question,
    cards.Hint AS Hint,
    cards.skip AS skip,
    cards.level AS level,
    ifnull(cards_rep.countRep, 0) as countRep,
    avgRep AS avgRep,
    IF(
        (cards.record_question = 1),
        cards.card_id,
        cards.import_source
    ) AS source_question,
    IF(
        (cards.record_answer = 1),
        cards.card_id,
        cards.import_source
    ) AS source_answer,
    IF(
        cards.Hint,
        IF(
            (cards.record_hint = 1),
            cards.card_id,
            cards.import_source
        ),
        NULL
    ) AS source_hint,
    desks.user_id AS user_id,
    desks.tree AS tree,
    desks.import_open as import_open,
    cards.next_timing <= CAST((NOW() + INTERVAL -(5) HOUR) AS DATE)
    OR cards.next_timing IS NULL as Repetition,
    cards.last_timing IS NULL
    AND cards.import_source IS NULL as News,
    cards.last_timing IS NULL
    AND NOT cards.import_source IS NULL as imports,
    cards.next_timing < CAST((NOW() + INTERVAL -(5) HOUR) AS DATE)
    AND cards.next_timing IS NOT NULL as Olds,
    cards.next_timing = CAST((NOW() + INTERVAL -(5) HOUR) AS DATE)
    AND cards.next_timing IS NOT NULL as toDay
FROM
    cards
    JOIN desks ON cards.desk_id = desks.desk_id
    LEFT JOIN (
        -- reps_data
        SELECT
            replog.card_id,
            count(replog.card_id) as countRep,
            avg(Grade) as avgRep
        FROM
            replog
        where
            Grade < 4
        GROUP BY
            replog.card_id
    ) cards_rep on cards.card_id = cards_rep.card_id