<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once file_exists(__DIR__ . '/config.php') ? 'config.php' : 'config/config.php';

// Agar already login hai toh home page pe bhej do
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

// ==========================================
// BACKEND: AJAX REGISTER & WALLET CREATION
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'register') {
    header('Content-Type: application/json');
    
    $mobile = trim($_POST['mobile'] ?? '');
    $password = $_POST['password'] ?? '';
    $cpassword = $_POST['cpassword'] ?? '';
    $referral = trim($_POST['referral'] ?? ''); // Optional

    // Basic Validation
    if (empty($mobile) || empty($password) || empty($cpassword)) {
        echo json_encode(['success' => false, 'message' => 'Please fill all required fields.']);
        exit;
    }
    if (strlen($mobile) < 10 || !is_numeric($mobile)) {
        echo json_encode(['success' => false, 'message' => 'Enter a valid 10-digit mobile number.']);
        exit;
    }
    if ($password !== $cpassword) {
        echo json_encode(['success' => false, 'message' => 'Passwords do not match.']);
        exit;
    }

    try {
        global $pdo;
        
        // 1. Check if mobile number already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE mobile = ?");
        $stmt->execute([$mobile]);
        if ($stmt->fetch()) {
            echo json_encode(['success' => false, 'message' => 'Mobile number is already registered.']);
            exit;
        }

        // 2. Start Database Transaction (Taaki agar Wallet fail ho toh User bhi delete ho jaye)
        $pdo->beginTransaction();

        // 3. Referrer (for spin: when this user's first recharge is approved, referrer gets 1 spin)
        $referredBy = null;
        if (!empty($referral)) {
            $refStmt = $pdo->prepare("SELECT id FROM users WHERE referral_code = ?");
            $refStmt->execute([strtoupper(trim($referral))]);
            $referredBy = $refStmt->fetchColumn();
        }

        // 4. Insert New User
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $username = 'Mem' . rand(10000, 99999);
        $myRefCode = strtoupper(substr(md5(uniqid()), 0, 8));

        $stmt = $pdo->prepare("INSERT INTO users (username, mobile, password, referral_code, referred_by, status) VALUES (?, ?, ?, ?, ?, 'active')");
        $stmt->execute([$username, $mobile, $hashedPassword, $myRefCode, $referredBy ?: null]);
        $newUserId = $pdo->lastInsertId();

        // 5. Create Wallet for the New User (With ₹50 Sign-up Bonus)
        $stmt = $pdo->prepare("INSERT INTO wallets (user_id, main_balance, bonus_balance) VALUES (?, 50.00, 0.00)");
        $stmt->execute([$newUserId]);

        // 6. Commit Transaction
        $pdo->commit();

        // 7. Auto-Login after Registration
        $_SESSION['user_id'] = $newUserId;
        
        echo json_encode(['success' => true, 'message' => 'Account created! ₹50 Bonus added. Redirecting...']);
        exit;

    } catch (PDOException $e) {
        // Agar kuch error aaya toh transaction cancel kar do
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Register - <?= defined('APP_NAME') ? APP_NAME : 'GameHub' ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #ff4a4a; --primary-dark: #e03e3e; --bg: #0f0f1a; --card: #1a1a2e; --text: #e4e4e7; --muted: #71717a; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; -webkit-tap-highlight-color: transparent; }
        body { min-height: 100vh; background: var(--bg); background-image: radial-gradient(ellipse 80% 50% at 50% -20%, rgba(255,74,74,0.15), transparent); max-width: 480px; margin: 0 auto; color: var(--text); }
        .auth-header { display: flex; align-items: center; padding: 18px 20px; }
        .back-btn { font-size: 20px; color: var(--text); text-decoration: none; }
        .auth-title { flex: 1; text-align: center; font-size: 17px; font-weight: 800; padding-right: 30px; }
        .auth-body { padding: 20px 24px; }
        .logo-area { text-align: center; margin-bottom: 28px; }
        .logo-area .icon-wrap { width: 64px; height: 64px; margin: 0 auto 14px; background: linear-gradient(135deg, var(--primary), var(--primary-dark)); border-radius: 18px; display: flex; align-items: center; justify-content: center; box-shadow: 0 10px 28px rgba(255,74,74,0.35); }
        .logo-area .icon-wrap i { font-size: 28px; color: #fff; }
        .logo-area h1 { font-size: 22px; font-weight: 900; letter-spacing: -0.5px; }
        .logo-area p { color: var(--muted); font-size: 12px; margin-top: 6px; font-weight: 500; }
        .auth-card { background: var(--card); border-radius: 20px; padding: 26px 24px; border: 1px solid rgba(255,255,255,0.06); box-shadow: 0 8px 32px rgba(0,0,0,0.2); }
        .input-group { display: flex; align-items: center; background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08); border-radius: 14px; margin-bottom: 14px; padding: 0 16px; transition: 0.2s; }
        .input-group:focus-within { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(255,74,74,0.15); }
        .input-group i { color: var(--muted); font-size: 16px; width: 24px; text-align: center; }
        .country-code { font-weight: 700; color: var(--muted); padding: 0 10px; border-right: 1px solid rgba(255,255,255,0.08); margin-right: 10px; font-size: 14px; }
        .form-control { flex: 1; padding: 14px 0; border: none; background: transparent; outline: none; font-size: 15px; color: var(--text); font-weight: 500; }
        .form-control::placeholder { color: var(--muted); }
        .agree-row { display: flex; gap: 10px; margin-top: 8px; margin-bottom: 20px; font-size: 12px; color: var(--muted); align-items: flex-start; }
        .agree-row input { width: 16px; height: 16px; accent-color: var(--primary); margin-top: 2px; flex-shrink: 0; }
        .agree-row a { color: var(--primary); font-weight: 600; text-decoration: none; }
        .submit-btn { width: 100%; background: linear-gradient(135deg, var(--primary), var(--primary-dark)); color: #fff; border: none; padding: 16px; border-radius: 14px; font-size: 16px; font-weight: 800; cursor: pointer; box-shadow: 0 8px 24px rgba(255,74,74,0.35); transition: transform 0.2s; }
        .submit-btn:active { transform: scale(0.98); }
        .submit-btn:disabled { opacity: 0.7; cursor: not-allowed; }
        .auth-footer { text-align: center; margin-top: 26px; font-size: 14px; color: var(--muted); font-weight: 500; }
        .auth-footer a { color: var(--primary); font-weight: 700; text-decoration: none; margin-left: 4px; }
        .toast { position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%) translateY(100px); background: var(--card); color: var(--text); padding: 14px 24px; border-radius: 14px; font-size: 14px; font-weight: 600; box-shadow: 0 12px 40px rgba(0,0,0,0.4); z-index: 9999; display: flex; align-items: center; gap: 10px; opacity: 0; transition: all 0.35s; border: 1px solid rgba(255,255,255,0.06); }
        .toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
        .toast.success i { color: #22c55e; }
        .toast.error i { color: #ef4444; }
    </style>
</head>
<body>

    <div id="toastBox" class="toast">
        <i class="fas fa-info-circle"></i>
        <span id="toastMsg">Message here</span>
    </div>

    <div class="auth-header">
        <a href="login.php" class="back-btn"><i class="fas fa-chevron-left"></i></a>
        <div class="auth-title">Register</div>
    </div>

    <div class="auth-body">
        
        <div class="logo-area">
            <div class="icon-wrap"><i class="fas fa-gem"></i></div>
            <h1>Join <?= defined('APP_NAME') ? APP_NAME : 'GameHub' ?></h1>
            <p>Create account & get ₹50 Welcome Bonus!</p>
        </div>

        <div class="auth-card">
        <form id="registerForm" onsubmit="executeRegister(event)">
            
            <div class="input-group">
                <i class="fas fa-mobile-alt"></i>
                <div class="country-code">+91</div>
                <input type="tel" name="mobile" class="form-control" placeholder="Mobile Number" required maxlength="10" pattern="[0-9]{10}" autocomplete="off">
            </div>

            <div class="input-group">
                <i class="fas fa-lock"></i>
                <input type="password" name="password" class="form-control" placeholder="Set Password" required autocomplete="new-password">
            </div>

            <div class="input-group">
                <i class="fas fa-check-circle"></i>
                <input type="password" name="cpassword" class="form-control" placeholder="Confirm Password" required autocomplete="new-password">
            </div>

            <div class="input-group">
                <i class="fas fa-user-tag"></i>
                <input type="text" name="referral" class="form-control" placeholder="Invite Code (Optional)" autocomplete="off">
            </div>

            <label class="agree-row">
                <input type="checkbox" required checked>
                <span>I agree to the <a href="#">Terms</a> & <a href="#">Privacy Policy</a></span>
            </label>

            <button type="submit" class="submit-btn" id="regBtn">Create Account</button>
        </form>
        </div>

        <div class="auth-footer">
            Already have an account? <a href="login.php">Log In</a>
        </div>

    </div>

    <script>
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toastBox');
            const msgSpan = document.getElementById('toastMsg');
            const icon = toast.querySelector('i');
            
            msgSpan.innerText = message;
            toast.className = 'toast show ' + type;
            icon.className = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';

            setTimeout(() => { toast.classList.remove('show'); }, 3000);
        }

        function executeRegister(e) {
            e.preventDefault(); 
            
            const btn = document.getElementById('regBtn');
            const form = document.getElementById('registerForm');
            const formData = new FormData(form);
            formData.append('action', 'register'); 

            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
            btn.disabled = true;

            fetch('register.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => { window.location.href = 'index.php'; }, 1500);
                } else {
                    showToast(data.message, 'error');
                    btn.innerHTML = 'Register';
                    btn.disabled = false;
                }
            })
            .catch(error => {
                showToast('Network error! Please try again.', 'error');
                btn.innerHTML = 'Register';
                btn.disabled = false;
            });
        }
    </script>
</body>
</html>