<?php

namespace App\Controllers;

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

class ProfileController extends Controller {
    private $db;

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

    public function shareLanding($slug) {
        header('Content-Type: text/html; charset=utf-8');
        $storeUrl = "https://play.google.com/store/apps/details?id=com.example.anon_chat";
        $appUrl = "anonchat://u/" . htmlspecialchars($slug);
        
        echo <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AnonChat - Profili Görüntüle</title>
    <style>
        body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; background: #f5f5f5; margin: 0; text-align: center; color: #333; }
        .btn { background: #6200ee; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: bold; margin-top: 20px; box-shadow: 0 4px 12px rgba(98,0,238,0.3); }
        .logo { width: 80px; height: 80px; background: #6200ee; border-radius: 20px; margin-bottom: 20px; display: flex; align-items: center; justify-content: center; color: white; font-size: 40px; font-weight: bold; }
        h1 { margin: 0; font-size: 20px; }
        p { color: #666; margin-top: 8px; }
    </style>
</head>
<body>
    <div class="logo">A</div>
    <h1>AnonChat Profili</h1>
    <p>Uygulama açılıyor...</p>
    <a href="{$storeUrl}" class="btn">Google Play'den İndir</a>

    <script>
        // Try to open app immediately
        window.location.href = "{$appUrl}";
        
        // Fallback to store after 2 seconds
        setTimeout(function() {
            window.location.href = "{$storeUrl}";
        }, 3000);
    </script>
</body>
</html>
HTML;
        exit;
    }

    public function me() {
        $userId = AuthMiddleware::authenticate();

        $stmt = $this->db->prepare("
            SELECT 
                id, username, display_name, bio, avatar_url, link_slug,
                status, is_seed, seed_label, gender, birth_date,
                full_name, city, country,
                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, daily_message_count, message_ad_credits,
                (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
            FROM users WHERE id = ?
        ");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $this->json(['error' => 'User not found'], 404);
            return;
        }

        $user['is_boosted']         = (int)($user['is_boosted'] ?? 0) === 1;
        $user['boost_remaining']    = (int)($user['boost_remaining'] ?? 0);
        $user['is_plus_subscriber'] = (int)($user['is_plus_subscriber'] ?? 0) === 1;
        $user['status']             = 'online';
        $user['is_online']          = true;
        $user['is_seed']            = (int)($user['is_seed'] ?? 0) === 1;
        $user['daily_message_count'] = (int)($user['daily_message_count'] ?? 0);
        $user['message_ad_credits']  = (int)($user['message_ad_credits'] ?? 0);

        $this->json($user);
    }

    public function rewardMessages() {
        $userId = AuthMiddleware::authenticate();
        
        // Add 15 messages as specified
        $stmt = $this->db->prepare("UPDATE users SET message_ad_credits = message_ad_credits + 15 WHERE id = ?");
        $stmt->execute([$userId]);

        $this->json(['success' => true, 'added' => 15]);
    }

    public function update() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();

        $allowedFields = ['display_name', 'bio', 'avatar_url', 'link_slug', 'active_frame', 'boosted_until', 'full_name', 'city', 'country'];
        $updates = [];
        $params = [];

        foreach ($allowedFields as $field) {
            if (array_key_exists($field, $input)) {
                $value = $input[$field];
                if ($field === 'bio' && $value !== null && strlen($value) > 155) {
                    $value = substr($value, 0, 155);
                }
                if ($field === 'active_frame' && $value !== null) {
                    $validFrames = ['silver', 'holiday', 'love', 'diamond', 'angel_wings', 'cactus', 'kings_crown', 'queens_crown'];
                    if (!in_array($value, $validFrames)) {
                        $this->json(['error' => 'Invalid frame'], 422);
                        return;
                    }
                }
                $updates[] = "$field = ?";
                $params[] = $value;
            }
        }

        if (empty($updates)) {
            $this->json(['message' => 'No changes']);
            return;
        }

        if (isset($input['link_slug'])) {
            $stmt = $this->db->prepare("SELECT id FROM users WHERE link_slug = ? AND id != ?");
            $stmt->execute([$input['link_slug'], $userId]);
            if ($stmt->fetch()) {
                $this->json(['error' => 'Slug already taken'], 409);
                return;
            }
        }

        $params[] = $userId;
        $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);

        $this->json(['message' => 'Profile updated']);
    }

    public function getUser($id) {
        $stmt = $this->db->prepare("
            SELECT 
                id, username, display_name, bio, avatar_url, link_slug,
                status, last_seen_at, is_seed, seed_label, gender,
                full_name, city, country,
                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
            FROM users WHERE id = ?
        ");
        $stmt->execute([$id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $this->json(['error' => 'User not found'], 404);
            return;
        }

        if ((int)($user['is_seed'] ?? 0) === 1) {
            $user['status'] = 'online';
            $user['last_seen_at'] = date('Y-m-d H:i:s');
        }

        $user['is_boosted']         = (int)($user['is_boosted'] ?? 0) === 1;
        $user['boost_remaining']    = (int)($user['boost_remaining'] ?? 0);
        $user['is_plus_subscriber'] = (int)($user['is_plus_subscriber'] ?? 0) === 1;
        $user['status']             = 'online';
        $user['is_online']          = true;
        $user['is_seed']            = (int)($user['is_seed'] ?? 0) === 1;

        $this->json($user);
    }

    public function getUserBySlug($slug) {
        $stmt = $this->db->prepare("
            SELECT 
                id, username, display_name, bio, avatar_url, link_slug,
                status, last_seen_at, is_seed, seed_label, gender,
                full_name, city, country,
                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
            FROM users WHERE link_slug = ?
        ");
        $stmt->execute([$slug]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $this->json(['error' => 'User not found'], 404);
            return;
        }

        $user['is_boosted']         = (int)($user['is_boosted'] ?? 0) === 1;
        $user['boost_remaining']    = (int)($user['boost_remaining'] ?? 0);
        $user['is_plus_subscriber'] = (int)($user['is_plus_subscriber'] ?? 0) === 1;
        $user['status']             = 'online';
        $user['is_online']          = true;
        $user['is_seed']            = (int)($user['is_seed'] ?? 0) === 1;

        $this->json($user);
    }

    public function updateOnboarding() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();

        $this->validate($input, [
            'bio'        => 'required',
            'gender'     => 'required',
            'birth_date' => 'required',
        ]);

        $allowedGenders = ['male', 'female', 'other'];
        if (!in_array($input['gender'], $allowedGenders)) {
             $this->json(['error' => 'Invalid gender'], 422);
             return;
        }

        $stmt = $this->db->prepare("SELECT avatar_url FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $u = $stmt->fetch(PDO::FETCH_ASSOC);

        if (empty($u['avatar_url'])) {
             $this->json(['error' => 'Avatar is required. Please upload one first.'], 400);
             return;
        }

        $stmt = $this->db->prepare("UPDATE users SET bio = ?, gender = ?, birth_date = ?, full_name = ?, city = ?, country = ? WHERE id = ?");
        $stmt->execute([
            $input['bio'], 
            $input['gender'], 
            $input['birth_date'], 
            $input['full_name'] ?? null,
            $input['city'] ?? null,
            $input['country'] ?? null,
            $userId
        ]);

        $this->json(['success' => true]);
    }
}
