<?php
// Generated by setup_mariadb_project.sh — edit as needed.
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'app_38443');
define('DB_USER', 'app_38443');
define('DB_PASS', '888f6481-a87b-421a-a4bd-c80fa3c5a57b');

function db() {
  static $pdo;
  if (!$pdo) {
    $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4', DB_USER, DB_PASS, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
  }
  return $pdo;
}

function enforceChannelLimit($channel_id) {
    $stmt = db()->prepare("SELECT message_limit FROM channels WHERE id = ?");
    $stmt->execute([$channel_id]);
    $channel = $stmt->fetch();
    if ($channel && !empty($channel['message_limit'])) {
        $limit = (int)$channel['message_limit'];
        // Delete oldest messages that exceed the limit
        $stmt = db()->prepare("
            DELETE FROM messages 
            WHERE channel_id = ? 
            AND id NOT IN (
                SELECT id FROM (
                    SELECT id FROM messages 
                    WHERE channel_id = ? 
                    ORDER BY created_at DESC, id DESC 
                    LIMIT " . $limit . "
                ) as tmp
            )
        ");
        $stmt->execute([$channel_id, $channel_id]);
    }
}
