<?php
declare(strict_types=1);

// API: Kullanıcının çekim yapacağı hesapları kaydetme/listeleme
// Methods:
// - GET    /api/withdraw_accounts.php[?type=havale]      -> {ok:true, accounts:[...]}
// - POST   body: {type, account, label?}                 -> {ok:true, id}
// - DELETE body: {id}                                     -> {ok:true}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../inc/database.php';

$username = isset($_SESSION['username']) ? (string)$_SESSION['username'] : '';
if ($username === '') {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'not_logged_in']);
    exit;
}

// Kullanıcı ID'sini al
$user_id = 0;
$adsoyad = '';
if (isset($conn) && $conn instanceof mysqli) {
    $stmt = $conn->prepare('SELECT id, first_name, surname FROM kullanicilar WHERE username = ? LIMIT 1');
    if ($stmt) {
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && ($row = $res->fetch_assoc())) {
            $user_id = (int)$row['id'];
            $adsoyad = trim((string)$row['first_name'] . ' ' . (string)$row['surname']);
        }
        $stmt->close();
    }
}
if ($user_id <= 0) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'user_not_found']);
    exit;
}

// Tabloyu oluştur (yoksa)
$conn->query('CREATE TABLE IF NOT EXISTS withdraw_accounts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    type VARCHAR(32) NOT NULL,
    label VARCHAR(100) DEFAULT NULL,
    account VARCHAR(128) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_user_type_account (user_id, type, account)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');

$method = $_SERVER['REQUEST_METHOD'];

function normalize_account(string $type, string $raw): string {
    $t = strtolower($type);
    $a = trim($raw);
    if ($t === 'havale' || $t === 'iban') {
        // Rakamları al, TR prefiksi ekle
        $digits = preg_replace('/[^0-9]/', '', $a);
        if ($digits === '') return '';
        if (strlen($digits) !== 24) return ''; // TR olmadan 24 hane
        return 'TR' . $digits;
    }
    if ($t === 'papara' || $t === 'payfix') {
        // Sadece rakamlar, 10-20 arası bırak
        $digits = preg_replace('/[^0-9]/', '', $a);
        if ($digits === '') return '';
        return $digits;
    }
    if ($t === 'usdt_trc20' || $t === 'usdt' || $t === 'tron' || $t === 'trc20') {
        // TRC20 adresi doğrulaması minimum
        $a = strtoupper($a);
        return $a;
    }
    return $a;
}

if ($method === 'GET') {
    $type = isset($_GET['type']) ? (string)$_GET['type'] : '';
    if ($type !== '') {
        $stmt = $conn->prepare('SELECT id, type, label, account, created_at FROM withdraw_accounts WHERE user_id = ? AND type = ? ORDER BY id DESC');
        $stmt->bind_param('is', $user_id, $type);
    } else {
        $stmt = $conn->prepare('SELECT id, type, label, account, created_at FROM withdraw_accounts WHERE user_id = ? ORDER BY id DESC');
        $stmt->bind_param('i', $user_id);
    }
    $accounts = [];
    if ($stmt) {
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) {
            $accounts[] = $row;
        }
        $stmt->close();
    }
    echo json_encode(['ok' => true, 'accounts' => $accounts]);
    exit;
}

$raw = file_get_contents('php://input');
$payload = json_decode($raw, true);
if (!is_array($payload)) { $payload = []; }

if ($method === 'POST') {
    $type = isset($payload['type']) ? (string)$payload['type'] : '';
    $account_raw = isset($payload['account']) ? (string)$payload['account'] : '';
    $label = isset($payload['label']) ? (string)$payload['label'] : '';

    if ($type === '' || $account_raw === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'missing_fields']);
        exit;
    }
    $normalized = normalize_account($type, $account_raw);
    if ($normalized === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'invalid_account_format']);
        exit;
    }

    $stmt = $conn->prepare('INSERT IGNORE INTO withdraw_accounts (user_id, type, label, account) VALUES (?, ?, ?, ?)');
    if (!$stmt) {
        http_response_code(500);
        echo json_encode(['ok' => false, 'error' => 'stmt_prepare_failed']);
        exit;
    }
    $stmt->bind_param('isss', $user_id, $type, $label, $normalized);
    $stmt->execute();
    $insert_id = $stmt->insert_id;
    $stmt->close();

    echo json_encode(['ok' => true, 'id' => (int)$insert_id]);
    exit;
}

if ($method === 'DELETE') {
    $id = isset($payload['id']) ? (int)$payload['id'] : 0;
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'invalid_id']);
        exit;
    }
    $stmt = $conn->prepare('DELETE FROM withdraw_accounts WHERE id = ? AND user_id = ?');
    if ($stmt) {
        $stmt->bind_param('ii', $id, $user_id);
        $stmt->execute();
        $stmt->close();
    }
    echo json_encode(['ok' => true]);
    exit;
}

http_response_code(405);
echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);