<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/header.php';

global $db, $translations;
$user_id = $_SESSION['user_id'];

$packages = [];
$current_package = null;
$message = null;
$message_type = 'info'; // 'success' or 'error' or 'info'

// Paket satın alma işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buy_package'])) {
    $package_id = filter_input(INPUT_POST, 'package_id', FILTER_VALIDATE_INT);
    $csrf_token = $_POST['csrf_token'] ?? '';

    if (!verify_csrf_token($csrf_token)) {
        $message = __('error_occurred', $translations);
        $message_type = 'error';
    } elseif (!$package_id) {
        $message = __('invalid_package', $translations); // Çeviri ekle
        $message_type = 'error';
    } elseif (!$db) { // Veritabanı bağlantısı kontrolü
        $message = __('db_error', $translations);
        $message_type = 'error';
    } else {
        try {
            $db->beginTransaction();

            // Kullanıcı bilgilerini ve bakiyesini al (kilitle)
            $stmt = $db->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();

            // Paket bilgilerini al
            $stmt = $db->prepare("SELECT price, duration FROM packages WHERE id = ? AND status = 1");
            $stmt->execute([$package_id]);
            $package_to_buy = $stmt->fetch();

            if (!$user || !$package_to_buy) {
                $message = __('package_or_user_not_found', $translations); // Çeviri ekle
                $message_type = 'error';
                $db->rollBack();
            } elseif ($user['balance'] < $package_to_buy['price']) {
                $message = __('insufficient_balance', $translations);
                $message_type = 'error';
                $db->rollBack();
            } else {
                // Kullanıcı bakiyesini düş
                $new_balance = $user['balance'] - $package_to_buy['price'];
                $stmt = $db->prepare("UPDATE users SET balance = ? WHERE id = ?");
                $stmt->execute([$new_balance, $user_id]);

                // Kullanıcının mevcut paket bilgilerini al
                $stmt = $db->prepare("SELECT package_id, package_expires_at FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $user_package = $stmt->fetch();
                
                // Bitiş tarihini hesapla
                // Eğer mevcut paket ile alınan paket aynıysa ve bitiş tarihi geçmemişse, süreyi uzat
                if ($user_package['package_id'] == $package_id && $user_package['package_expires_at'] > date('Y-m-d H:i:s')) {
                    $expires_at = date('Y-m-d H:i:s', strtotime($user_package['package_expires_at'] . " +{$package_to_buy['duration']} days"));
                    $message = __('package_extended', $translations);
                } else {
                    // Farklı paket veya süresi geçmiş paket ise yeni süre başlat
                    $expires_at = date('Y-m-d H:i:s', strtotime("+{$package_to_buy['duration']} days"));
                    $message = __('package_purchased', $translations);
                    
                    // Eski paket ile yeni paket farklıysa, kullanıcının bugün yaptığı indirmeleri sıfırlama hakkı verelim
                    if ($user_package['package_id'] != $package_id) {
                        // Bugünkü ve bu ayki indirme kayıtlarını silmiyoruz, çünkü geçmiş kayıtlar önemli
                        // check_download_limits fonksiyonu indirme sayılarını downloads tablosundan hesaplıyor
                        // Bu yüzden kullanıcının indirme limitlerini sıfırlamak yerine bir sonraki indirmesinde
                        // yeni paketinin limitlerini kullanacağı için ek bir işlem yapmaya gerek yok
                    }
                }
                
                // Kullanıcının paketini güncelle
                $stmt = $db->prepare("UPDATE users SET package_id = ?, package_expires_at = ? WHERE id = ?");
                $stmt->execute([$package_id, $expires_at, $user_id]);
                
                // Ödeme kaydı oluştur (Opsiyonel - Bakiye ile alım için)
                // $stmt = $db->prepare("INSERT INTO payments (user_id, amount, status, created_at) VALUES (?, ?, 'completed_balance', NOW())");
                // $stmt->execute([$user_id, $package_to_buy['price']]);

                $db->commit();
                $message_type = 'success';
                // Sayfayı yenileyerek güncel bilgileri göster
                echo "<script>window.location.href = 'packages.php';</script>"; 
                exit;
            }
        } catch (PDOException $e) {
            $db->rollBack();
            $message = __('db_error', $translations);
            $message_type = 'error';
            // error_log("Package purchase error: " . $e->getMessage());
        }
    }
}

// Mevcut paketleri ve kullanıcının mevcut paketini listele
if ($db) { // Veritabanı bağlantısı varsa listele
    try {
        // Aktif paketleri al
        $stmt = $db->query("SELECT id, name, price, duration, daily_limit, monthly_limit, supports_envato, supports_freepik FROM packages WHERE status = 1 ORDER BY price ASC");
        $packages = $stmt->fetchAll();

        // Kullanıcının mevcut paketini al
        $stmt = $db->prepare("SELECT p.name, u.package_expires_at 
                             FROM users u 
                             JOIN packages p ON u.package_id = p.id 
                             WHERE u.id = ? AND (u.package_expires_at IS NULL OR u.package_expires_at > NOW())");
        $stmt->execute([$user_id]);
        $current_package = $stmt->fetch();

    } catch (PDOException $e) {
        $message = __('db_error', $translations);
        $message_type = 'error';
         // error_log("Package listing error: " . $e->getMessage());
    }
} else {
     $message = __('db_error', $translations);
     $message_type = 'error';
}

?>

<h1 class="text-2xl font-semibold text-gray-800 dark:text-white mb-6"><?php echo __('packages', $translations); ?></h1>

<?php if ($message): ?>
    <div class="<?php echo $message_type === 'success' ? 'bg-primary-100 border-primary-400 text-primary-700' : ($message_type === 'error' ? 'bg-red-100 border-red-400 text-red-700' : 'bg-primary-100 border-primary-400 text-primary-700'); ?> border px-4 py-3 rounded relative mb-6" role="alert">
        <span class="block sm:inline"><?php echo e($message); ?></span>
    </div>
<?php endif; ?>

<!-- Mevcut Paket Bilgisi -->
<?php if ($current_package): ?>
<div class="bg-primary-100 dark:bg-primary-900 border border-primary-400 dark:border-primary-700 text-primary-700 dark:text-primary-200 px-4 py-3 rounded relative mb-6">
    <strong class="font-bold"><?php echo __('current_package', $translations); ?>:</strong>
    <span class="block sm:inline ml-2"><?php echo e($current_package['name']); ?> (<?php echo __('expires_at', $translations); ?>: <?php echo date('d.m.Y', strtotime($current_package['package_expires_at'])); ?>)</span>
</div>
<?php endif; ?>

<!-- Paket Listesi -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
    <?php if (empty($packages)): ?>
        <p class="text-gray-500 dark:text-gray-400 md:col-span-2 lg:col-span-3"><?php echo __('no_packages_available', $translations); // Çeviri ekle ?></p>
    <?php else: ?>
        <?php foreach ($packages as $package): ?>
            <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-6 flex flex-col justify-between">
                <div>
                    <h2 class="text-xl font-semibold text-gray-800 dark:text-white mb-2"><?php echo e($package['name']); ?></h2>
                    <p class="text-3xl font-bold text-primary-600 dark:text-primary-400 mb-4">₺<?php echo number_format($package['price'], 2); ?></p>
                    <ul class="text-sm text-gray-600 dark:text-gray-400 space-y-1 mb-4">
                        <li><i class="fas fa-check-circle text-primary-500 mr-2"></i><?php echo e($package['duration']); ?> <?php echo __('days', $translations); // çeviri ekle ?></li>
                        <li><i class="fas fa-check-circle text-primary-500 mr-2"></i><?php echo __('daily_limit', $translations); ?>: <?php echo e($package['daily_limit']); ?></li>
                        <li><i class="fas fa-check-circle text-primary-500 mr-2"></i><?php echo __('monthly_limit', $translations); ?>: <?php echo e($package['monthly_limit']); ?></li>
                        <li class="font-medium pt-2"><?php echo __('supports', $translations); ?>:</li>
                        <li>
                            <?php if ($package['supports_freepik']): ?>
                                <span class="inline-block bg-primary-100 text-primary-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-primary-900 dark:text-primary-300">Freepik</span>
                            <?php endif; ?>
                            <?php if ($package['supports_envato']): ?>
                                <span class="inline-block bg-primary-100 text-primary-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-primary-900 dark:text-primary-300">Envato Elements</span>
                            <?php endif; ?>
                        </li>
                    </ul>
                </div>
                <form action="packages.php" method="POST" class="mt-auto">
                     <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <input type="hidden" name="package_id" value="<?php echo $package['id']; ?>">
                    <button type="submit" name="buy_package" class="w-full bg-primary-600 hover:bg-primary-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
                        <?php echo __('buy_package', $translations); ?>
                    </button>
                    <p class="text-xs text-center text-gray-500 dark:text-gray-400 mt-2"><?php echo __('buy_with_balance', $translations); // Çeviri ekle ?></p>
                </form>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<?php
require_once __DIR__ . '/includes/footer.php';
?> 