<?php
session_start();
include 'config.php';

// ============================================================
// 0. CEK SESSION LOGIN
// ============================================================
if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit(); 
}

$user_id = $_SESSION['user_id'];
$msg = "";
$msg_type = "";

// ============================================================
// 1. LOGIC UPDATE PROFIL (SEMUA DATA)
// ============================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // A. UPDATE DATA TEKS & BANK
    if (isset($_POST['save_profile'])) {
        $full_name = $conn->real_escape_string($_POST['full_name']);
        $email     = $conn->real_escape_string($_POST['email']);
        $phone     = $conn->real_escape_string($_POST['phone']);
        
        // Bank & Wallet
        $bank_name  = $conn->real_escape_string($_POST['bank_name']);
        $acc_number = $conn->real_escape_string($_POST['acc_number']);
        $acc_name   = $conn->real_escape_string($_POST['acc_name']);
        
        // Crypto
        $trc20 = isset($_POST['wallet_trc20']) ? $conn->real_escape_string($_POST['wallet_trc20']) : '';
        $bep20 = isset($_POST['wallet_bep20']) ? $conn->real_escape_string($_POST['wallet_bep20']) : '';

        // Query Update Dasar
        $sql = "UPDATE users SET 
                full_name = '$full_name', 
                email = '$email', 
                phone = '$phone',
                bank_name = '$bank_name',
                acc_number = '$acc_number',
                acc_name = '$acc_name',
                wallet_trc20 = '$trc20',
                wallet_bep20 = '$bep20'
                WHERE id = $user_id";
        
        if ($conn->query($sql)) {
            $msg = "Profil berhasil disimpan!";
            $msg_type = "success";
        } else {
            $msg = "Gagal menyimpan data: " . $conn->error;
            $msg_type = "error";
        }

        // B. UPDATE PASSWORD (JIKA DIISI)
        if (!empty($_POST['password'])) {
            $new_pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $conn->query("UPDATE users SET password = '$new_pass' WHERE id = $user_id");
            $msg .= " Password berhasil diubah.";
        }
    }

    // C. UPDATE AVATAR (JIKA ADA FILE)
    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
        $target_dir = "uploads/";
        if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }
        
        $file_name = time() . '_' . basename($_FILES["avatar"]["name"]);
        $target_file = $target_dir . $file_name;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        
        // Validasi simpel
        if(in_array($imageFileType, ['jpg','jpeg','png'])) {
            if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $target_file)) {
                $conn->query("UPDATE users SET avatar = '$file_name' WHERE id = $user_id");
            }
        }
    }
}

// ============================================================
// 2. AMBIL DATA USER TERBARU (REFRESH DATA)
// ============================================================
$user = $conn->query("SELECT * FROM users WHERE id = $user_id")->fetch_assoc();
$avatar_path = !empty($user['avatar']) ? "uploads/".$user['avatar'] : null;

// Ambil Username Upline (Sponsor)
$sponsor_name = "-";
if($user['upline_id'] != 0) {
    $qUp = $conn->query("SELECT username FROM users WHERE id = ".$user['upline_id']);
    if($qUp->num_rows > 0) {
        $sponsor_name = $qUp->fetch_assoc()['username'];
    }
}

// Generate Full Referral Link
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$domain = $_SERVER['HTTP_HOST'];
$path = dirname($_SERVER['PHP_SELF']);
$path = rtrim($path, '/');
$full_referral_link = $protocol . "://" . $domain . $path . "/register.php?ref=" . $user['referral_code'];

$active_menu = 'profile'; 
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Profile</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = { darkMode: 'class', theme: { extend: { colors: { primary: '#10b981', darkbg: '#0f172a' } } } }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .bank-radio:checked + label { border-color: #10b981; background-color: rgba(16, 185, 129, 0.1); }
        .bank-radio:checked + label .check-icon { display: block; }
    </style>
</head>
<body class="bg-gray-100 dark:bg-darkbg text-gray-800 dark:text-gray-200 transition-colors duration-300 font-sans">

    <div class="max-w-md mx-auto min-h-screen relative shadow-2xl bg-white dark:bg-slate-900 pb-32">
        
        <div class="bg-slate-800 text-white p-6 pb-12 rounded-b-[3rem] shadow-lg text-center relative">
            <h1 class="font-bold text-lg mb-4">Edit Profile</h1>
            
            <div class="relative w-24 h-24 mx-auto mb-3 group">
                <div class="w-24 h-24 rounded-full border-4 border-white/20 bg-slate-700 overflow-hidden shadow-xl flex items-center justify-center">
                    <?php if($avatar_path && file_exists($avatar_path)): ?>
                        <img src="<?php echo $avatar_path; ?>" class="w-full h-full object-cover">
                    <?php else: ?>
                        <span class="text-3xl font-bold"><?php echo strtoupper(substr($user['username'], 0, 1)); ?></span>
                    <?php endif; ?>
                </div>
                <form id="formAvatar" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="save_profile" value="1"> 
                    <label for="uploadBtn" class="absolute bottom-0 right-0 bg-primary w-8 h-8 rounded-full flex items-center justify-center cursor-pointer hover:bg-emerald-600 border-2 border-slate-800 transition transform hover:scale-110">
                        <i class="fas fa-camera text-xs"></i>
                    </label>
                    <input type="file" name="avatar" id="uploadBtn" class="hidden" onchange="document.getElementById('formAvatar').submit()">
                </form>
            </div>

            <h2 class="text-xl font-bold mb-1"><?php echo $user['username']; ?></h2>

            <p class="text-xs text-gray-400">Member since <?php echo date('M Y', strtotime($user['created_at'])); ?></p>
            
            <?php 
                $role = isset($user['role']) ? strtoupper($user['role']) : 'STARTER';
                if(empty($role)) $role = 'STARTER';
                
                $badgeClass = ($role === 'PREMIUM') 
                    ? 'bg-yellow-500 text-yellow-900 border-yellow-400 shadow-[0_0_10px_rgba(234,179,8,0.5)]' 
                    : 'bg-gray-600 text-gray-200 border-gray-500';
            ?>
            <span class="mt-2 mb-3 inline-block px-3 py-0.5 rounded-full text-[10px] font-bold border <?php echo $badgeClass; ?>">
                <i class="fas fa-crown mr-1"></i> <?php echo $role; ?>
            </span>

            <div class="flex items-center justify-center gap-2 mt-2 px-6">
                <div class="bg-slate-900/50 rounded-full px-3 py-1.5 flex items-center gap-2 max-w-full overflow-hidden border border-slate-600 w-full justify-between">
                    <div class="flex items-center gap-2 overflow-hidden">
                        <i class="fas fa-link text-[10px] text-gray-400"></i>
                        <span class="text-[10px] text-gray-300 font-mono truncate" id="refText"><?php echo $full_referral_link; ?></span>
                    </div>
                    <button onclick="copyLink()" class="w-6 h-6 bg-primary rounded-full flex items-center justify-center text-white hover:bg-emerald-600 transition active:scale-95 shadow-md flex-shrink-0">
                        <i class="fas fa-copy text-[10px]"></i>
                    </button>
                </div>
            </div>

        </div>

        <form action="" method="POST" class="px-6 mt-6 space-y-6">
            <input type="hidden" name="save_profile" value="1">

            <div class="bg-white dark:bg-slate-800 rounded-xl p-4 shadow-sm border border-gray-100 dark:border-slate-700">
                <div class="flex items-center gap-2 mb-3 border-b dark:border-slate-700 pb-2">
                    <i class="fas fa-info-circle text-blue-500"></i>
                    <p class="font-bold text-sm">Account Info</p>
                </div>
                <div class="grid grid-cols-2 gap-4 text-xs">
                    <div>
                        <p class="text-gray-500">Referral Code</p>
                        <p class="font-mono font-bold text-primary"><?php echo $user['referral_code']; ?></p>
                    </div>
                    <div>
                        <p class="text-gray-500">Sponsor</p>
                        <p class="font-bold text-blue-400"><?php echo $sponsor_name; ?></p>
                    </div>
                </div>
            </div>

            <div class="bg-white dark:bg-slate-800 rounded-xl p-4 shadow-sm border border-gray-100 dark:border-slate-700">
                <div class="flex items-center gap-2 mb-4 border-b dark:border-slate-700 pb-2">
                    <i class="fas fa-user-edit text-purple-500"></i>
                    <p class="font-bold text-sm">Data Pribadi</p>
                </div>
                <div class="space-y-3">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-gray-500">Nama Lengkap</label>
                        <input type="text" name="full_name" value="<?php echo $user['full_name']; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-sm focus:border-primary focus:outline-none">
                    </div>
                    <div>
                        <label class="text-[10px] uppercase font-bold text-gray-500">Email</label>
                        <input type="email" name="email" value="<?php echo $user['email']; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-sm focus:border-primary focus:outline-none">
                    </div>
                    <div>
                        <label class="text-[10px] uppercase font-bold text-gray-500">No. WhatsApp</label>
                        <input type="number" name="phone" value="<?php echo $user['phone']; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-sm focus:border-primary focus:outline-none">
                    </div>
                </div>
            </div>

            <div class="bg-white dark:bg-slate-800 rounded-xl p-4 shadow-sm border border-gray-100 dark:border-slate-700">
                <div class="flex items-center gap-2 mb-4 border-b dark:border-slate-700 pb-2">
                    <i class="fas fa-lock text-red-500"></i>
                    <p class="font-bold text-sm">Ganti Password</p>
                </div>
                <div>
                    <input type="password" name="password" placeholder="Isi password baru jika ingin mengganti" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-sm focus:border-primary focus:outline-none">
                </div>
            </div>

            <div class="bg-white dark:bg-slate-800 rounded-xl p-4 shadow-sm border border-gray-100 dark:border-slate-700">
                <div class="flex items-center gap-2 mb-4 border-b dark:border-slate-700 pb-2">
                    <i class="fas fa-wallet text-green-500"></i>
                    <p class="font-bold text-sm">Metode Pencairan (Withdraw)</p>
                </div>
                
                <div class="grid grid-cols-3 gap-2 mb-4">
                    <?php 
                    $banks = [
                        ['id'=>'BCA', 'img'=>'https://upload.wikimedia.org/wikipedia/commons/5/5c/Bank_Central_Asia.svg'],
                        ['id'=>'BRI', 'img'=>'https://upload.wikimedia.org/wikipedia/commons/6/68/BANK_BRI_logo.svg'],
                        ['id'=>'MANDIRI', 'img'=>'https://upload.wikimedia.org/wikipedia/commons/a/ad/Bank_Mandiri_logo_2016.svg'],
                        ['id'=>'DANA', 'img'=>'https://upload.wikimedia.org/wikipedia/commons/7/72/Logo_dana_blue.svg'],
                        ['id'=>'OVO', 'img'=>'https://upload.wikimedia.org/wikipedia/commons/e/eb/Logo_ovo_purple.svg'],
                        ['id'=>'GOPAY', 'img'=>'https://upload.wikimedia.org/wikipedia/commons/8/86/Gopay_logo.svg'],
                        ['id'=>'SHOPEEPAY', 'img'=>'https://upload.wikimedia.org/wikipedia/commons/f/fe/Shopee.svg']
                    ];
                    foreach($banks as $b):
                        $checked = ($user['bank_name'] == $b['id']) ? 'checked' : '';
                    ?>
                    <div class="relative">
                        <input type="radio" name="bank_name" value="<?php echo $b['id']; ?>" id="b_<?php echo $b['id']; ?>" class="hidden bank-radio" <?php echo $checked; ?>>
                        <label for="b_<?php echo $b['id']; ?>" class="flex flex-col items-center justify-center p-2 rounded-lg border border-gray-200 dark:border-slate-600 cursor-pointer h-16 bg-white hover:bg-gray-50 transition relative overflow-hidden">
                            <img src="<?php echo $b['img']; ?>" class="h-6 object-contain mb-1">
                            <span class="text-[9px] font-bold text-gray-500"><?php echo $b['id']; ?></span>
                            <div class="check-icon hidden absolute top-1 right-1 text-emerald-500"><i class="fas fa-check-circle text-xs"></i></div>
                        </label>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="space-y-3">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-gray-500">Nomor Rekening / E-Wallet</label>
                        <input type="number" name="acc_number" value="<?php echo $user['acc_number']; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-sm focus:border-primary focus:outline-none" placeholder="Contoh: 08123456789 (DANA)">
                    </div>
                    <div>
                        <label class="text-[10px] uppercase font-bold text-gray-500">Atas Nama (Sesuai Akun)</label>
                        <input type="text" name="acc_name" value="<?php echo $user['acc_name']; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-sm focus:border-primary focus:outline-none" placeholder="Nama Pemilik Rekening">
                    </div>
                </div>
            </div>

            <div class="bg-white dark:bg-slate-800 rounded-xl p-4 shadow-sm border border-gray-100 dark:border-slate-700">
                <div class="flex items-center gap-2 mb-4 border-b dark:border-slate-700 pb-2">
                    <i class="fab fa-bitcoin text-orange-500"></i>
                    <p class="font-bold text-sm">Crypto Wallet Address</p>
                </div>
                <div class="space-y-3">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-gray-500 flex justify-between">
                            <span>USDT (TRC20)</span> <span class="text-red-500">Tron Network</span>
                        </label>
                        <input type="text" name="wallet_trc20" value="<?php echo isset($user['wallet_trc20']) ? $user['wallet_trc20'] : ''; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-xs font-mono focus:border-primary focus:outline-none" placeholder="Dimulai dengan T...">
                    </div>
                    <div>
                        <label class="text-[10px] uppercase font-bold text-gray-500 flex justify-between">
                            <span>USDT (BEP20)</span> <span class="text-yellow-500">BNB Chain</span>
                        </label>
                        <input type="text" name="wallet_bep20" value="<?php echo isset($user['wallet_bep20']) ? $user['wallet_bep20'] : ''; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 rounded p-2 text-xs font-mono focus:border-primary focus:outline-none" placeholder="Dimulai dengan 0x...">
                    </div>
                </div>
            </div>

            <div class="pt-2 space-y-3">
                <button type="submit" class="w-full bg-primary hover:bg-emerald-600 text-white font-bold py-3.5 rounded-xl shadow-lg transition transform active:scale-95 flex items-center justify-center gap-2">
                    <i class="fas fa-save"></i> Simpan Perubahan
                </button>
                
                <a href="logout.php" onclick="return confirm('Yakin ingin logout?')" class="block w-full text-center bg-red-50 dark:bg-red-900/20 text-red-500 py-3 rounded-xl font-bold text-sm hover:bg-red-100 dark:hover:bg-red-900/40 transition">
                    Logout
                </a>
            </div>
        </form>

        <?php if(file_exists('footer_nav.php')) include 'footer_nav.php'; ?>
        
    </div>

    <script>
        function copyLink() {
            var copyText = document.getElementById("refText").innerText;
            navigator.clipboard.writeText(copyText).then(function() {
                Swal.fire({
                    icon: 'success',
                    title: 'Disalin!',
                    text: 'Link referral berhasil disalin',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 1500
                });
            }, function(err) {
                console.error('Async: Could not copy text: ', err);
            });
        }
    </script>

    <?php if($msg): ?>
    <script>
        Swal.fire({
            icon: '<?php echo $msg_type; ?>',
            title: '<?php echo $msg_type == "success" ? "Berhasil" : "Gagal"; ?>',
            text: '<?php echo $msg; ?>',
            timer: 2000, showConfirmButton: false
        });
    </script>
    <?php endif; ?>
</body>
</html>