<?php

namespace App\Controllers;

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

class BillingController extends Controller {
    private $db;

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

    public function verify() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        
        $this->validate($input, [
            'tier' => 'required', // 'weekly', 'monthly', 'quarterly'
        ]);

        $tier = $input['tier'];
        
        // Süre hesapla
        $daysMap = [
            'weekly' => 7,
            'monthly' => 30,
            'quarterly' => 90,
        ];
        
        if (!isset($daysMap[$tier])) {
            $this->json(['error' => 'Geçersiz paket'], 400);
            return;
        }

        $days = $daysMap[$tier];
        $expiresAt = date('Y-m-d H:i:s', time() + (60 * 60 * 24 * $days));

        // subscriptions tablosuna kaydet
        $transactionId = uniqid('plus_');
        $platform = $input['platform'] ?? 'android';
        $productId = $input['product_id'] ?? 'plus_' . $tier;

        $stmt = $this->db->prepare("INSERT INTO subscriptions (user_id, platform, product_id, status, started_at, expires_at, original_transaction_id, created_at, updated_at) VALUES (?, ?, ?, 'active', NOW(), ?, ?, NOW(), NOW()) ON DUPLICATE KEY UPDATE status = 'active', expires_at = ?, updated_at = NOW()");
        $stmt->execute([
            $userId, 
            $platform, 
            $productId, 
            $expiresAt, 
            $transactionId,
            $expiresAt
        ]);

        // users tablosunu güncelle
        $stmt = $this->db->prepare("UPDATE users SET is_plus_subscriber = 1, subscription_tier = ?, plus_expires_at = ? WHERE id = ?");
        $stmt->execute([$tier, $expiresAt, $userId]);

        $this->json([
            'success' => true, 
            'tier' => $tier,
            'expires_at' => $expiresAt,
            'is_plus_subscriber' => true
        ]);
    }

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

        // Önce süresi geçmiş abonelikleri deaktive et
        $stmt = $this->db->prepare("UPDATE users SET is_plus_subscriber = 0, subscription_tier = NULL, plus_expires_at = NULL WHERE id = ? AND plus_expires_at IS NOT NULL AND plus_expires_at < NOW()");
        $stmt->execute([$userId]);

        $stmt = $this->db->prepare("SELECT is_plus_subscriber, subscription_tier, plus_expires_at FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        $this->json([
            'is_plus_subscriber' => (bool)($user['is_plus_subscriber'] ?? 0),
            'subscription_tier' => $user['subscription_tier'] ?? null,
            'plus_expires_at' => $user['plus_expires_at'] ?? null,
        ]);
    }

    public function boost() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        
        $this->validate($input, [
            'duration_minutes' => 'required',
        ]);

        $minutes = (int)$input['duration_minutes'];
        
        // Mevcut boost süresi varsa üstüne ekle, yoksa NOW() üstüne ekle
        $stmt = $this->db->prepare("SELECT boosted_until FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $currentBoost = $stmt->fetchColumn();
        
        $baseTime = (strtotime($currentBoost) > time()) ? strtotime($currentBoost) : time();
        $newBoostTime = date('Y-m-d H:i:s', $baseTime + ($minutes * 60));

        $stmt = $this->db->prepare("UPDATE users SET boosted_until = ?, active_frame = 'kings_crown' WHERE id = ?");
        $stmt->execute([$newBoostTime, $userId]);

        $this->json([
            'success' => true,
            'boosted_until' => $newBoostTime,
            'minutes_added' => $minutes
        ]);
    }

    public function restore() {
        $this->verify();
    }
}

