<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Config\Database;
use App\Middleware\AuthMiddleware;
use PDO;

class DiscoveryController extends Controller {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }

    public function shuffle() {
        $userId = AuthMiddleware::authenticate();
        $online = isset($_GET['online']) ? (bool)$_GET['online'] : true;
        $includeSeed = isset($_GET['include_seed']) ? (bool)$_GET['include_seed'] : true;
        $queryText = isset($_GET['q']) ? trim($_GET['q']) : null;

        // Plus üyeler için sınırsız (100), normal kullanıcılar için 20
        $isPlus = false;
        try {
            $chk = $this->db->prepare("SELECT is_plus_subscriber FROM users WHERE id = ?");
            $chk->execute([$userId]);
            $isPlus = (int)($chk->fetchColumn() ?: 0) === 1;
        } catch (\Exception $e) {}

        // Sunucu yükünü korumak için varsayılan 20, Plus için max 100
        $defaultLimit = 20;
        $maxLimit = $isPlus ? 100 : 20;
        $limit = isset($_GET['limit']) ? min((int)$_GET['limit'], $maxLimit) : $defaultLimit;

        $gender = isset($_GET['gender']) ? trim($_GET['gender']) : null;
        $minAge = isset($_GET['min_age']) ? (int)$_GET['min_age'] : null;
        $maxAge = isset($_GET['max_age']) ? (int)$_GET['max_age'] : null;

        $sql = "SELECT 
            id, username, display_name, full_name, city, country, bio, avatar_url, link_slug,
            status, is_seed, seed_label, gender,
            CASE WHEN boosted_until IS NOT NULL AND boosted_until > NOW() THEN active_frame ELSE NULL END AS active_frame,
            is_plus_subscriber, subscription_tier, plus_expires_at,
            (boosted_until IS NOT NULL AND boosted_until > NOW()) AS is_boosted,
            CASE WHEN boosted_until IS NOT NULL AND boosted_until > NOW()
                 THEN TIMESTAMPDIFF(MINUTE, NOW(), boosted_until)
                 ELSE 0 END AS boost_remaining,
            CASE WHEN birth_date IS NOT NULL 
                 THEN TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) 
                 ELSE NULL END AS age
        FROM users 
        WHERE id != :id 
          AND is_banned = 0";

        if ($queryText) {
            $sql .= " AND (username LIKE :q1 OR bio LIKE :q2 OR display_name LIKE :q3 OR city LIKE :q4 OR country LIKE :q5 OR full_name LIKE :q6)";
        }

        // Plus filtreler
        if ($gender && in_array($gender, ['male', 'female'])) {
            $sql .= " AND gender = :gender";
        }

        if ($minAge !== null) {
            $sql .= " AND birth_date IS NOT NULL AND TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) >= :min_age";
        }

        if ($maxAge !== null) {
            $sql .= " AND birth_date IS NOT NULL AND TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) <= :max_age";
        }

        // Boosted kullanıcılar her zaman önce ve bitiş süresine göre sabit sırada, diğerleri ise her seferinde rastgele gelsin.
        $sql .= " ORDER BY (boosted_until IS NOT NULL AND boosted_until > NOW()) DESC, boosted_until DESC, RAND()";
        $sql .= " LIMIT :limit";

        try {
            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':id', $userId);
            if ($queryText) {
                $q = '%' . $queryText . '%';
                $stmt->bindValue(':q1', $q);
                $stmt->bindValue(':q2', $q);
                $stmt->bindValue(':q3', $q);
                $stmt->bindValue(':q4', $q);
                $stmt->bindValue(':q5', $q);
                $stmt->bindValue(':q6', $q);
            }
            $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
            if ($gender && in_array($gender, ['male', 'female'])) {
                $stmt->bindValue(':gender', $gender);
            }
            if ($minAge !== null) {
                $stmt->bindValue(':min_age', $minAge, PDO::PARAM_INT);
            }
            if ($maxAge !== null) {
                $stmt->bindValue(':max_age', $maxAge, PDO::PARAM_INT);
            }
            $stmt->execute();

            $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($users as &$u) {
                $u['status'] = 'online';
                $u['is_online']          = true;
                $u['is_boosted']         = (int)$u['is_boosted'] === 1;
                $u['boost_remaining']    = (int)($u['boost_remaining'] ?? 0);
                $u['is_plus_subscriber'] = (int)($u['is_plus_subscriber'] ?? 0) === 1;
                $u['is_seed']            = (int)($u['is_seed'] ?? 0) === 1;
                $u['age']                = $u['age'] !== null ? (int)$u['age'] : null;
            }

            $this->json($users);
        } catch (\PDOException $e) {
            $this->json(['error' => 'Database error: ' . $e->getMessage()], 500);
        }
    }
}
