<?php
require 'db.php';
header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $fullname = $_POST['fullname'];
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $email = $_POST['email'];
    $phone = $_POST['phone'] ?? '';
    $address = $_POST['address'] ?? '';
    $Iller = $_POST['Iller'];
    $Ilceler = $_POST['Ilceler'];
    $fullAddress = "$address, $Iller, $Ilceler"; // Tam adresi birleştir
    $parentReferenceCode = $_POST['parent_reference_code'];

    $stmtUserRefCode = $pdo->prepare("SELECT id FROM users WHERE reference_code = ?");
    $stmtUserRefCode->execute([$parentReferenceCode]);
    $userRefCode = $stmtUserRefCode->fetch();

    $stmtRefCode = $pdo->prepare("SELECT code FROM reference_codes WHERE code = ? AND used = 0");
    $stmtRefCode->execute([$parentReferenceCode]);
    $refCode = $stmtRefCode->fetch();

    if ($userRefCode || $refCode) {
        if ($refCode) {
            $updateStmt = $pdo->prepare("UPDATE reference_codes SET used = 1 WHERE code = ?");
            $updateStmt->execute([$parentReferenceCode]);
        }

        $insertStmt = $pdo->prepare("INSERT INTO users (fullname, username, password, email, phone, address, parent_reference_code, reference_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $newRefCode = substr(md5(uniqid(rand(), true)), 0, 6);
        $success = $insertStmt->execute([$fullname, $username, $password, $email, $phone, $fullAddress, $parentReferenceCode, $newRefCode]);

        if ($success) {
            $response = ['success' => true, 'message' => 'Kayıt başarılı! Giriş yapabilirsiniz.'];
        } else {
            $response = ['success' => false, 'message' => 'Bir hata oluştu. Lütfen tekrar deneyin.'];
        }
    } else {
        $response = ['success' => false, 'message' => 'Geçersiz veya kullanılmış referans kodu.'];
    }

    echo json_encode($response);
} else {
    echo "Bu sayfaya doğrudan erişim yasaktır.";
}
?>
