<?php
// includes/feedback_lib.php — shared helpers for the Dabil feedback module.
// Provides config defaults, settings loaders, and the scheduling/eligibility
// logic that decides whether a customer should see a feedback sheet.
//
// All read queries are error-suppressed so that, if the schema migration hasn't
// been run yet, the app simply behaves as "no feedback due" instead of erroring.

if (!defined('RF_DEFAULTS')) {
    define('RF_DEFAULTS', json_encode([
        'enabled'        => 1,
        'frequency_n'    => 1,
        'intro_title'    => 'How was your experience?',
        'intro_subtitle' => 'Your feedback helps us improve your dining experience.',
        'categories'     => ['Food Quality', 'Service', 'Wait Time'],
        'tags'           => ['Great food', 'Fast service', 'Friendly staff', 'Packaging issue', 'Delayed order'],
        'allow_comment'  => 1,
    ]));
    define('DF_DEFAULTS', json_encode([
        'enabled'        => 1,
        'frequency_n'    => 5,
        'intro_title'    => 'How was your Dabil experience?',
        'intro_subtitle' => 'Your feedback helps us make everyday transactions faster and more reliable.',
        'tags'           => ['QR Ordering', 'Wallet Payment', 'App Speed', 'UI Design', 'Support'],
        'allow_comment'  => 1,
    ]));
}

/** Make sure all feedback tables exist (used by pages that write). */
function feedback_ensure_tables($conn) {
    @$conn->query("CREATE TABLE IF NOT EXISTS `restaurant_feedback_settings` (
        `restaurant_id` INT NOT NULL, `enabled` TINYINT(1) NOT NULL DEFAULT 1,
        `frequency_n` INT NOT NULL DEFAULT 1,
        `intro_title` VARCHAR(160) NOT NULL DEFAULT 'How was your experience?',
        `intro_subtitle` VARCHAR(255) NOT NULL DEFAULT 'Your feedback helps us improve your dining experience.',
        `categories` TEXT NULL, `tags` TEXT NULL, `allow_comment` TINYINT(1) NOT NULL DEFAULT 1,
        `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`restaurant_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci");
    @$conn->query("CREATE TABLE IF NOT EXISTS `restaurant_feedback` (
        `id` INT NOT NULL AUTO_INCREMENT, `restaurant_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL,
        `status` ENUM('submitted','skipped') NOT NULL DEFAULT 'submitted', `overall_rating` TINYINT NULL,
        `category_ratings` TEXT NULL, `tags` TEXT NULL, `comment` TEXT NULL,
        `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`), UNIQUE KEY `uniq_order` (`order_id`), KEY `idx_rest` (`restaurant_id`), KEY `idx_user` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci");
    @$conn->query("CREATE TABLE IF NOT EXISTS `dabil_feedback_settings` (
        `id` TINYINT NOT NULL DEFAULT 1, `enabled` TINYINT(1) NOT NULL DEFAULT 1, `frequency_n` INT NOT NULL DEFAULT 5,
        `intro_title` VARCHAR(160) NOT NULL DEFAULT 'How was your Dabil experience?',
        `intro_subtitle` VARCHAR(255) NOT NULL DEFAULT 'Your feedback helps us make everyday transactions faster and more reliable.',
        `tags` TEXT NULL, `allow_comment` TINYINT(1) NOT NULL DEFAULT 1,
        `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci");
    @$conn->query("INSERT IGNORE INTO `dabil_feedback_settings` (`id`) VALUES (1)");
    @$conn->query("CREATE TABLE IF NOT EXISTS `dabil_feedback` (
        `id` INT NOT NULL AUTO_INCREMENT, `user_id` INT NOT NULL, `order_id` INT NULL,
        `status` ENUM('submitted','skipped') NOT NULL DEFAULT 'submitted', `sentiment` ENUM('smooth','okay','issues') NULL,
        `tags` TEXT NULL, `comment` TEXT NULL, `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`), UNIQUE KEY `uniq_order` (`order_id`), KEY `idx_user` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci");
}

/** Load a restaurant's feedback settings merged over defaults. */
function rf_get_settings($conn, $rid) {
    $s = json_decode(RF_DEFAULTS, true);
    $rid = (int)$rid;
    if ($res = @$conn->query("SELECT * FROM restaurant_feedback_settings WHERE restaurant_id=$rid LIMIT 1")) {
        if ($row = $res->fetch_assoc()) {
            $s['enabled']        = (int)$row['enabled'];
            $s['frequency_n']    = max(1, (int)$row['frequency_n']);
            $s['intro_title']    = $row['intro_title'] ?: $s['intro_title'];
            $s['intro_subtitle'] = $row['intro_subtitle'] ?: $s['intro_subtitle'];
            $s['allow_comment']  = (int)$row['allow_comment'];
            $cats = json_decode($row['categories'] ?? '', true);
            $tags = json_decode($row['tags'] ?? '', true);
            if (is_array($cats) && $cats) $s['categories'] = $cats;
            if (is_array($tags)) $s['tags'] = $tags;
        }
    }
    return $s;
}

/** Load the platform (Dabil) feedback settings merged over defaults. */
function df_get_settings($conn) {
    $s = json_decode(DF_DEFAULTS, true);
    if ($res = @$conn->query("SELECT * FROM dabil_feedback_settings WHERE id=1 LIMIT 1")) {
        if ($row = $res->fetch_assoc()) {
            $s['enabled']        = (int)$row['enabled'];
            $s['frequency_n']    = max(1, (int)$row['frequency_n']);
            $s['intro_title']    = $row['intro_title'] ?: $s['intro_title'];
            $s['intro_subtitle'] = $row['intro_subtitle'] ?: $s['intro_subtitle'];
            $s['allow_comment']  = (int)$row['allow_comment'];
            $tags = json_decode($row['tags'] ?? '', true);
            if (is_array($tags)) $s['tags'] = $tags;
        }
    }
    return $s;
}

/** Has this order already been responded to / skipped for restaurant feedback? */
function rf_already_handled($conn, $order_id) {
    $order_id = (int)$order_id;
    $r = @$conn->query("SELECT 1 FROM restaurant_feedback WHERE order_id=$order_id LIMIT 1");
    return $r && $r->num_rows > 0;
}
function df_already_handled($conn, $order_id) {
    $order_id = (int)$order_id;
    if (!$order_id) return false;
    $r = @$conn->query("SELECT 1 FROM dabil_feedback WHERE order_id=$order_id LIMIT 1");
    return $r && $r->num_rows > 0;
}

/**
 * Is restaurant feedback due for this specific (completed) order?
 * $order must be an assoc array with id, restaurant_id, order_status.
 */
function rf_due_for_order($conn, $uid, $order) {
    if (($order['order_status'] ?? '') !== 'completed') return false;
    $rid = (int)($order['restaurant_id'] ?? 0);
    $oid = (int)($order['id'] ?? 0);
    if (!$rid || !$oid) return false;

    $s = rf_get_settings($conn, $rid);
    if (!$s['enabled']) return false;
    if (rf_already_handled($conn, $oid)) return false;

    $n = max(1, (int)$s['frequency_n']);
    // Rank = how many completed orders this customer has had at this restaurant up to (and including) this one.
    $uid = (int)$uid;
    $rank = 0;
    if ($res = @$conn->query("SELECT COUNT(*) c FROM orders WHERE user_id=$uid AND restaurant_id=$rid AND order_status='completed' AND id<=$oid")) {
        $rank = (int)($res->fetch_row()[0] ?? 0);
    }
    return $rank > 0 && ($rank % $n === 0);
}

/**
 * Is Dabil (platform) feedback due? Looks at the customer's most recent served
 * order and applies the global frequency. Sets &$order_id to that order.
 */
function df_due($conn, $uid, &$order_id) {
    $order_id = 0;
    $s = df_get_settings($conn);
    if (!$s['enabled']) return false;

    $uid = (int)$uid;
    $res = @$conn->query("SELECT id FROM orders WHERE user_id=$uid AND order_status='completed' ORDER BY updated_at DESC, id DESC LIMIT 1");
    if (!$res || !($r = $res->fetch_row())) return false;
    $order_id = (int)$r[0];
    if (df_already_handled($conn, $order_id)) return false;

    $n = max(1, (int)$s['frequency_n']);
    $rank = 0;
    if ($c = @$conn->query("SELECT COUNT(*) c FROM orders WHERE user_id=$uid AND order_status='completed' AND id<=$order_id")) {
        $rank = (int)($c->fetch_row()[0] ?? 0);
    }
    return $rank > 0 && ($rank % $n === 0);
}

/** Is Dabil feedback due for one specific (completed) order? Used by the sheet's guard. */
function df_due_for_order($conn, $uid, $order_id) {
    $order_id = (int)$order_id;
    if (!$order_id) return false;
    $s = df_get_settings($conn);
    if (!$s['enabled']) return false;
    if (df_already_handled($conn, $order_id)) return false;

    $uid = (int)$uid;
    // Must be a served order that belongs to this customer.
    $chk = @$conn->query("SELECT 1 FROM orders WHERE id=$order_id AND user_id=$uid AND order_status='completed' LIMIT 1");
    if (!$chk || !$chk->num_rows) return false;

    $n = max(1, (int)$s['frequency_n']);
    $rank = 0;
    if ($c = @$conn->query("SELECT COUNT(*) c FROM orders WHERE user_id=$uid AND order_status='completed' AND id<=$order_id")) {
        $rank = (int)($c->fetch_row()[0] ?? 0);
    }
    return $rank > 0 && ($rank % $n === 0);
}
