<?php
session_start();

// Sadece admin oturumu açıkken çalıştır
if (!isset($_SESSION['admin_logged_in'])) {
    http_response_code(401);
    echo 'Unauthorized';
    exit;
}

require_once __DIR__ . '/dblive.php';

try {
    $pdo = new PDO("mysql:host=$user_db_servername;dbname=$user_db_name;charset=utf8", $user_db_username, $user_db_password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo 'DB connect error: ' . htmlspecialchars($e->getMessage());
    exit;
}

$results = [];

try {
    // affiliate_applications tablosunu oluştur
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS affiliate_applications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            first_name VARCHAR(100) NOT NULL,
            last_name VARCHAR(100) NOT NULL,
            email VARCHAR(255) NOT NULL,
            phone_number VARCHAR(50) NULL,
            username VARCHAR(100) NOT NULL,
            company VARCHAR(255) NULL,
            website VARCHAR(255) NULL,
            status VARCHAR(50) NOT NULL DEFAULT 'Beklemede',
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");
    $results[] = 'affiliate_applications table OK';

    // Durum sütunu yoksa eklemeyi dene (MySQL 8 öncesi IF NOT EXISTS yok)
    try {
        $pdo->exec("ALTER TABLE affiliate_applications ADD COLUMN status VARCHAR(50) NOT NULL DEFAULT 'Beklemede'");
        $results[] = 'affiliate_applications.status added';
    } catch (PDOException $e) {
        // Duplicate column ise yok say
        if (strpos($e->getMessage(), 'Duplicate column') !== false) {
            $results[] = 'affiliate_applications.status exists';
        } else {
            throw $e;
        }
    }

    // Tablo boşsa örnek kayıt ekle
    $count = (int)$pdo->query("SELECT COUNT(*) FROM affiliate_applications")->fetchColumn();
    if ($count === 0) {
        $ins = $pdo->prepare("INSERT INTO affiliate_applications (first_name, last_name, email, phone_number, username, company, website, status) VALUES (:first_name, :last_name, :email, :phone_number, :username, :company, :website, :status)");
        $ins->execute([
            ':first_name' => 'Ali',
            ':last_name' => 'Veli',
            ':email' => 'ali.veli@example.com',
            ':phone_number' => '+905551112233',
            ':username' => 'aliveli',
            ':company' => 'Örnek A.Ş.',
            ':website' => 'https://ornek.com',
            ':status' => 'Beklemede',
        ]);
        $results[] = 'affiliate_applications seeded (1 row)';
    } else {
        $results[] = 'affiliate_applications already has data';
    }

    // kullanici2 tablosunu oluştur
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS kullanici2 (
            id INT AUTO_INCREMENT PRIMARY KEY,
            kullanici_adi VARCHAR(100) NOT NULL,
            sifre VARCHAR(255) NOT NULL,
            email VARCHAR(255) NOT NULL,
            referans_kodu VARCHAR(100) NULL,
            role VARCHAR(50) NOT NULL DEFAULT 'affiliate',
            durum VARCHAR(50) NOT NULL DEFAULT 'Beklemede',
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");
    $results[] = 'kullanici2 table OK';

    // Gerekli sütunları eklemeyi dene
    foreach ([
        "ALTER TABLE kullanici2 ADD COLUMN durum VARCHAR(50) NOT NULL DEFAULT 'Beklemede'",
        "ALTER TABLE kullanici2 ADD COLUMN updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
    ] as $alterSql) {
        try {
            $pdo->exec($alterSql);
            $results[] = 'kullanici2 altered: ' . $alterSql;
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate column') !== false) {
                // already exists
            } else {
                throw $e;
            }
        }
    }

    // Tablo boşsa örnek kayıt ekle
    $count2 = (int)$pdo->query("SELECT COUNT(*) FROM kullanici2")->fetchColumn();
    if ($count2 === 0) {
        $ins2 = $pdo->prepare("INSERT INTO kullanici2 (kullanici_adi, sifre, email, referans_kodu, role, durum) VALUES (?, ?, ?, ?, ?, ?)");
        $ins2->execute(['affuser', password_hash('Aff123!','PASSWORD_DEFAULT'), 'affuser@example.com', 'REF123', 'affiliate', 'Beklemede']);
        $results[] = 'kullanici2 seeded (1 row)';
    } else {
        $results[] = 'kullanici2 already has data';
    }

    echo 'OK\n' . implode("\n", $results);
} catch (PDOException $e) {
    http_response_code(500);
    echo 'Migration error: ' . htmlspecialchars($e->getMessage());
}