<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
requireLogin();

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

// Auto-fix broken Gravatar if it's too short or contains HTML error page
if (empty($user['avatar']) || strlen($user['avatar']) < 2000 || strpos(base64_decode(substr($user['avatar'], 22)), '<html') !== false) {
    $hash = md5(strtolower(trim($user['email'])));
    $monsterUrl = "https://www.gravatar.com/avatar/{$hash}?d=monsterid&s=150";
    $ctx = stream_context_create([
        'http' => [
            'timeout' => 5,
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n"
        ]
    ]);
    $imgData = @file_get_contents($monsterUrl, false, $ctx);
    if ($imgData !== false && strlen($imgData) > 500) {
        $user['avatar'] = 'data:image/png;base64,' . base64_encode($imgData);
        saveUser($user);
    }
}

$message = '';
$messageType = '';

if (isset($_GET['msg']) && $_GET['msg'] === 'linked') {
    $message = 'Google account linked successfully!';
    $messageType = 'success';
}
if (isset($_GET['error'])) {
    $message = htmlspecialchars($_GET['error']);
    $messageType = 'error';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'change_password') {
    csrfVerify();
    $current = $_POST['current_password'] ?? '';
    $new = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    if (!$current || !$new || !$confirm) {
        $message = 'Please fill in all password fields.';
        $messageType = 'error';
    } elseif (!password_verify($current, $user['password_hash'])) {
        $message = 'Current password is incorrect.';
        $messageType = 'error';
    } elseif (strlen($new) < 6) {
        $message = 'New password must be at least 6 characters.';
        $messageType = 'error';
    } elseif ($new !== $confirm) {
        $message = 'New passwords do not match.';
        $messageType = 'error';
    } else {
        $user['password_hash'] = password_hash($new, PASSWORD_DEFAULT);
        saveUser($user);
        $message = 'Password updated successfully!';
        $messageType = 'success';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'upload_avatar') {
    csrfVerify();
    if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
        $message = 'Please choose an image to upload.';
        $messageType = 'error';
    } else {
        $file = $_FILES['avatar'];
        $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp'];
        $mime = mime_content_type($file['tmp_name']);

        if (!isset($allowed[$mime])) {
            $message = 'Only PNG, JPG, GIF or WEBP images are allowed.';
            $messageType = 'error';
        } elseif ($file['size'] > 1.5 * 1024 * 1024) {
            $message = 'Image must be smaller than 1.5MB.';
            $messageType = 'error';
        } else {
            $imgData = file_get_contents($file['tmp_name']);
            $dataUri = 'data:' . $mime . ';base64,' . base64_encode($imgData);
            $user['avatar'] = $dataUri;
            saveUser($user);
            $message = 'Avatar updated!';
            $messageType = 'success';
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'request_email_change') {
    csrfVerify();
    $newEmail = trim($_POST['new_email'] ?? '');
    
    if (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['status'=>'error', 'message'=>'Invalid email format.']); exit;
    } elseif ($newEmail === $user['email']) {
        echo json_encode(['status'=>'error', 'message'=>'This is already your email address.']); exit;
    } elseif (getUserByEmail($newEmail)) {
        echo json_encode(['status'=>'error', 'message'=>'This email is already in use by another account.']); exit;
    } else {
        $otp = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        $_SESSION['email_change'] = [
            'new_email' => $newEmail,
            'otp' => $otp,
            'expires' => time() + 600
        ];
        
        $subject = "Verify Your New Email Address";
        $body = "
            <div style='font-family: Arial, sans-serif; padding: 20px; color: #333;'>
                <h2>Email Update Request</h2>
                <p>Hi {$user['name']},</p>
                <p>You requested to change your FamGateway email address. Your verification code is:</p>
                <h1 style='color: #2563eb; letter-spacing: 4px;'>$otp</h1>
                <p>This code will expire in 10 minutes. If you did not request this, please ignore this email.</p>
            </div>
        ";
        sendSMTPMail($newEmail, $subject, $body, true);
        echo json_encode(['status'=>'otp_required']); exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'verify_email_change') {
    csrfVerify();
    $otp = trim($_POST['otp'] ?? '');
    
    if (!isset($_SESSION['email_change']) || time() > $_SESSION['email_change']['expires']) {
        echo json_encode(['status'=>'error', 'message'=>'OTP expired or session invalid. Try again.']); exit;
    } elseif ($otp !== $_SESSION['email_change']['otp']) {
        echo json_encode(['status'=>'error', 'message'=>'Invalid OTP.']); exit;
    } else {
        $user['email'] = $_SESSION['email_change']['new_email'];
        saveUser($user);
        unset($_SESSION['email_change']);
        echo json_encode(['status'=>'success', 'message'=>'Email updated successfully!']); exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update_profile') {
    csrfVerify();
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $supportLink = trim($_POST['support_link'] ?? '');

    if (empty($name)) {
        echo json_encode(['status'=>'error', 'message'=>'Name cannot be empty.']); exit;
    } else {
        $user['name'] = $name;
        $user['phone'] = $phone;
        $user['support_link'] = $supportLink;
        saveUser($user);
        echo json_encode(['status'=>'success', 'message'=>'Profile details updated successfully!']); exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'unlink_google') {
    csrfVerify();
    $user['google_linked'] = 0;
    saveUser($user);
    $message = 'Google account unlinked successfully.';
    $messageType = 'success';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "My Profile — FamGateway";
include 'includes/header.php'; 
?>
<style>
    .avatar-row { display: flex; align-items: center; gap: 24px; }
    .avatar-preview {
        width: 88px; height: 88px; border-radius: 50%; object-fit: cover;
        border: 2px solid var(--color-primary); background: var(--surface-page);
        box-shadow: 0 4px 12px rgba(37,99,235,0.15);
    }
    .avatar-placeholder {
        width: 88px; height: 88px; border-radius: 50%;
        background: var(--surface-page); display: flex; align-items: center; justify-content: center;
        color: var(--color-ink-mute); border: 2px dashed var(--color-hairline);
    }
</style>
</head>
<body>
<?php include 'includes/nav.php'; ?>
    
<main class="main-content">
    <div class="wrap" style="max-width: 720px;">

    <?php if ($message): ?>
        <div class="callout callout-<?= $messageType === 'success' ? 'success' : 'error' ?>"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <!-- Page Title -->
    <div class="dash-anim-right" style="margin-top: 24px; margin-bottom: 24px;">
      <h1 style="font-size: 22px; font-weight: 700; color: var(--color-ink); letter-spacing: -0.5px;">
        Profile Settings
      </h1>
      <p style="font-size: 13px; color: var(--color-ink-mute); margin-top: 4px;">Manage your account details and custom brand QR avatar.</p>
    </div>

    <!-- PERSONAL DETAILS CARD -->
    <div class="card dash-anim-up" style="margin-bottom: 24px;">
        <div class="card-header" style="margin-bottom: 18px;">
            <div class="card-title"><i data-lucide="user" style="width:18px;height:18px;color:var(--color-primary);"></i> Personal Details</div>
        </div>
        <div class="form-row" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; margin-bottom: 12px;">
            <div class="form-group">
                <label class="form-label" style="font-size: 12px; color: var(--color-ink-mute); margin-bottom: 4px; display: block;">Full Name</label>
                <div style="font-weight: 500; font-size: 14px; color: var(--color-ink); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
                    <span id="currentNameDisplay" style="word-break: break-word;"><?= htmlspecialchars($user['name']) ?></span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label" style="font-size: 12px; color: var(--color-ink-mute); margin-bottom: 4px; display: block;">Email Address</label>
                <div style="font-weight: 500; font-size: 14px; color: var(--color-ink); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
                    <span id="currentEmailDisplay" style="word-break: break-all;"><?= htmlspecialchars($user['email']) ?></span>
                    <button type="button" onclick="showEmailChange()" class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px; white-space: nowrap;">Change</button>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label" style="font-size: 12px; color: var(--color-ink-mute); margin-bottom: 4px; display: block;">Phone Number</label>
                <div style="font-weight: 500; font-size: 14px; color: var(--color-ink); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
                    <span id="currentPhoneDisplay" style="word-break: break-word;"><?= !empty($user['phone']) ? htmlspecialchars($user['phone']) : '<span style="color:#9ca3af;font-size:13px;font-style:italic;">Not provided</span>' ?></span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label" style="font-size: 12px; color: var(--color-ink-mute); margin-bottom: 4px; display: block;">Support / Contact Link</label>
                <div style="font-weight: 500; font-size: 14px; color: var(--color-ink); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
                    <span id="currentSupportLinkDisplay" style="word-break: break-word;"><?= !empty($user['support_link']) ? htmlspecialchars($user['support_link']) : '<span style="color:#9ca3af;font-size:13px;font-style:italic;">Not provided</span>' ?></span>
                    <button type="button" onclick="showProfileEdit()" class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px; white-space: nowrap;">Edit Details</button>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label" style="font-size: 12px; color: var(--color-ink-mute); margin-bottom: 4px; display: block;">Google Sign-In</label>
                <div style="font-weight: 500; font-size: 14px; color: var(--color-ink); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
                    <?php if (!empty($user['google_linked'])): ?>
                        <span style="display:flex; align-items:center; gap:6px;"><i data-lucide="check-circle-2" style="width:14px;height:14px;color:var(--color-success);"></i> Linked</span>
                        <form method="POST" style="margin:0;" onsubmit="return confirm('Are you sure you want to unlink your Google account? Make sure you know your password to login.');">
                            <input type="hidden" name="action" value="unlink_google">
                            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                            <button type="submit" class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px; white-space: nowrap; color: #dc2626;">Unlink</button>
                        </form>
                    <?php else: ?>
                        <span style="display:flex; align-items:center; gap:6px;"><i data-lucide="x-circle" style="width:14px;height:14px;color:var(--color-danger);"></i> Not Linked</span>
                        <a href="auth-google.php" class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px; white-space: nowrap; text-decoration:none;">Link Account</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- PROFILE EDIT FORM (INLINE) -->
        <div id="profileEditContainer" style="display: none; padding-top: 16px; border-top: 1px solid var(--color-border); margin-top: 8px;">
            <div id="profileEditAlert" style="display:none; margin-bottom:12px; padding:10px; border-radius:6px; font-size:13px; font-weight:500;"></div>
            
            <form id="updateProfileForm" style="display:flex; flex-wrap:wrap; gap:16px; align-items:flex-end;">
                <input type="hidden" name="action" value="update_profile">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <div style="flex:1; min-width: 220px;">
                    <label class="form-label" style="font-size: 13px; font-weight: 600; color: var(--color-ink); margin-bottom: 6px; display: block;">Full Name</label>
                    <input type="text" name="name" class="form-input" style="font-size: 14px;" required value="<?= htmlspecialchars($user['name']) ?>">
                </div>
                <div style="flex:1; min-width: 220px;">
                    <label class="form-label" style="font-size: 13px; font-weight: 600; color: var(--color-ink); margin-bottom: 6px; display: block;">Phone Number</label>
                    <div style="display: flex;">
                        <span style="background: #f8fafc; border: 1px solid var(--color-border); border-right: none; border-radius: 8px 0 0 8px; padding: 10px 14px; color: var(--color-ink-secondary); font-weight: 600; font-size: 13px; display: flex; align-items: center;">+91</span>
                        <input type="text" name="phone" class="form-input" style="border-radius: 0 8px 8px 0; border-left: 1px solid var(--color-border); font-size: 14px;" value="<?= htmlspecialchars($user['phone'] ?? '') ?>" placeholder="9876543210" pattern="[0-9]{10}">
                    </div>
                </div>
                <div style="flex:1; min-width: 220px;">
                    <label class="form-label" style="font-size: 13px; font-weight: 600; color: var(--color-ink); margin-bottom: 6px; display: block;">Support Link</label>
                    <input type="url" name="support_link" class="form-input" style="font-size: 14px;" value="<?= htmlspecialchars($user['support_link'] ?? '') ?>" placeholder="https://t.me/yourusername">
                </div>
                <div style="display: flex; gap: 8px; flex: 1; min-width: 200px;">
                    <button type="submit" class="btn btn-primary" id="updateProfileBtn" style="flex: 1; font-weight: 600; padding: 10px 14px;">Save</button>
                    <button type="button" class="btn btn-secondary" onclick="hideProfileEdit()" style="flex: 1; font-weight: 600; padding: 10px 14px;">Cancel</button>
                </div>
            </form>
        </div>

        <!-- EMAIL CHANGE FORM (HIDDEN) -->
        <div id="emailChangeContainer" style="display: none; padding-top: 16px; border-top: 1px solid var(--color-border); margin-top: 8px;">
            <div id="emailChangeAlert" style="display:none; margin-bottom:12px; padding:10px; border-radius:6px; font-size:13px;"></div>
            
            <form id="requestEmailForm" style="display:flex; flex-wrap:wrap; gap:10px; align-items:flex-end;">
                <input type="hidden" name="action" value="request_email_change">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <div style="flex:1; min-width:200px;">
                    <label class="form-label" style="font-size: 12px; color: var(--color-ink-mute); margin-bottom: 4px; display: block;">New Email Address</label>
                    <input type="email" name="new_email" class="form-input" required placeholder="new@example.com">
                </div>
                <div style="display: flex; gap: 8px; flex: 1; min-width: 200px;">
                    <button type="submit" class="btn btn-primary" id="requestEmailBtn" style="flex: 1; padding: 10px 14px;">Send OTP</button>
                    <button type="button" class="btn btn-secondary" onclick="hideEmailChange()" style="flex: 1; padding: 10px 14px;">Cancel</button>
                </div>
            </form>

            <form id="verifyEmailForm" style="display:none; flex-wrap:wrap; gap:10px; align-items:flex-end;">
                <input type="hidden" name="action" value="verify_email_change">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <div style="flex:1; min-width:200px;">
                    <label class="form-label" style="font-size: 12px; color: var(--color-ink-mute); margin-bottom: 4px; display: block;">Enter 6-Digit OTP</label>
                    <input type="text" name="otp" class="form-input" required placeholder="123456" maxlength="6" style="letter-spacing: 2px;">
                </div>
                <div style="display: flex; gap: 8px; flex: 1; min-width: 200px;">
                    <button type="submit" class="btn btn-primary" id="verifyEmailBtn" style="flex: 1; padding: 10px 14px;">Verify & Update</button>
                    <button type="button" class="btn btn-secondary" onclick="hideEmailChange()" style="flex: 1; padding: 10px 14px;">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- AVATAR CARD -->
    <div class="card dash-anim-up" style="animation-delay: 0.05s;">
        <div class="card-header" style="margin-bottom: 18px;">
            <div class="card-title"><i data-lucide="image" style="width:18px;height:18px;color:var(--color-primary);"></i> Profile Avatar</div>
            <div class="card-sub">This avatar automatically embeds in the center of your generated QR codes.</div>
        </div>

        <div class="avatar-row" style="margin-top: 14px;">
            <?php if (!empty($user['avatar'])): ?>
                <img src="<?= htmlspecialchars($user['avatar']) ?>" class="avatar-preview" alt="Avatar">
            <?php else: ?>
                <div class="avatar-placeholder"><i data-lucide="user" style="width:32px;height:32px;"></i></div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" style="flex:1;">
                <input type="hidden" name="action" value="upload_avatar">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <input type="file" name="avatar" accept="image/png,image/jpeg,image/gif,image/webp" required style="display: block; margin-bottom: 14px; color: var(--color-ink-mute); font-size: 13px; font-family: var(--font);">
                <button type="submit" class="btn btn-secondary"><i data-lucide="upload" style="width:15px;height:15px;"></i> Upload New Avatar</button>
            </form>
        </div>
    </div>

    <!-- PASSWORD CARD -->
    <div class="card dash-anim-up" style="animation-delay: 0.12s;">
        <div class="card-header" style="margin-bottom: 18px;">
            <div class="card-title"><i data-lucide="lock" style="width:18px;height:18px;color:var(--color-primary);"></i> Change Password</div>
            <div class="card-sub">Update your account login credentials.</div>
        </div>

        <form method="POST">
            <input type="hidden" name="action" value="change_password">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">

            <div class="form-group">
                <label class="form-label">Current Password</label>
                <input type="password" name="current_password" class="form-input" placeholder="Enter current password" required>
            </div>

            <div class="form-group">
                <label class="form-label">New Password</label>
                <input type="password" name="new_password" class="form-input" placeholder="At least 6 characters" required>
            </div>

            <div class="form-group">
                <label class="form-label">Confirm New Password</label>
                <input type="password" name="confirm_password" class="form-input" placeholder="Re-enter new password" required>
            </div>

            <button type="submit" class="btn btn-primary" style="width: 100%; padding: 12px; margin-top: 8px;"><i data-lucide="shield-check" style="width:16px;height:16px;"></i> Update Password</button>
        </form>
    </div>

    <!-- SOCIAL LOGINS CARD -->
    <div class="card dash-anim-up" style="animation-delay: 0.18s; margin-top: 24px;">
        <div class="card-header" style="margin-bottom: 18px;">
            <div class="card-title">
                <svg viewBox="0 0 48 48" style="width:18px; height:18px; margin-right:6px;">
                    <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
                    <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
                    <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
                    <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
                </svg>
                Google Sign-In
            </div>
            <div class="card-sub">Enable or disable 1-click login with your Google account.</div>
        </div>

        <div style="display: flex; align-items: center; justify-content: space-between; background: var(--surface-page); border: 1px solid var(--color-hairline); border-radius: 12px; padding: 16px 20px;">
            <div style="display: flex; align-items: center; gap: 14px;">
                <?php if (!empty($user['google_linked'])): ?>
                    <div style="width: 42px; height: 42px; border-radius: 50%; background: #dcfce7; display: flex; align-items: center; justify-content: center; color: #16a34a;">
                        <i data-lucide="check" style="width: 24px; height: 24px;"></i>
                    </div>
                    <div>
                        <div style="font-weight: 600; font-size: 14px; color: var(--color-ink);">Linked</div>
                        <div style="font-size: 13px; color: var(--color-ink-mute);">You can log in via Google</div>
                    </div>
                <?php else: ?>
                    <div style="width: 42px; height: 42px; border-radius: 50%; background: #f1f5f9; display: flex; align-items: center; justify-content: center; color: #64748b;">
                        <i data-lucide="link" style="width: 20px; height: 20px;"></i>
                    </div>
                    <div>
                        <div style="font-weight: 600; font-size: 14px; color: var(--color-ink);">Not Linked</div>
                        <div style="font-size: 13px; color: var(--color-ink-mute);">Sign-in with Google is disabled</div>
                    </div>
                <?php endif; ?>
            </div>
            <div>
                <?php if (!empty($user['google_linked'])): ?>
                    <form method="POST" style="margin: 0;" onsubmit="return confirm('Are you sure you want to unlink your Google account? You will have to use your email and password to log in.');">
                        <input type="hidden" name="action" value="unlink_google">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                        <button type="submit" class="btn btn-secondary" style="color: #dc2626; border-color: #fee2e2; background: #fef2f2;">Unlink Account</button>
                    </form>
                <?php else: ?>
                    <a href="auth-google.php" class="btn btn-secondary" style="display: flex; align-items: center; gap: 8px;">
                        <i data-lucide="link" style="width: 14px; height: 14px;"></i> Link Account
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    </div>
</main>
</div>

<script>
  if (window.lucide) lucide.createIcons();

  function showEmailChange() {
      document.getElementById('emailChangeContainer').style.display = 'block';
      document.getElementById('requestEmailForm').style.display = 'flex';
      document.getElementById('verifyEmailForm').style.display = 'none';
      document.getElementById('emailChangeAlert').style.display = 'none';
  }

  function hideEmailChange() {
      document.getElementById('emailChangeContainer').style.display = 'none';
  }

  function showEmailAlert(msg, type) {
      const alert = document.getElementById('emailChangeAlert');
      alert.style.display = 'block';
      alert.innerHTML = msg;
      alert.style.backgroundColor = type === 'error' ? '#fee2e2' : '#dcfce7';
      alert.style.color = type === 'error' ? '#dc2626' : '#166534';
      alert.style.border = type === 'error' ? '1px solid #fca5a5' : '1px solid #bbf7d0';
  }

  function showProfileEdit() {
      document.getElementById('profileEditContainer').style.display = 'block';
      document.getElementById('emailChangeContainer').style.display = 'none';
      document.getElementById('profileEditAlert').style.display = 'none';
  }

  function hideProfileEdit() {
      document.getElementById('profileEditContainer').style.display = 'none';
  }

  function showProfileAlert(msg, type) {
      const alert = document.getElementById('profileEditAlert');
      alert.style.display = 'block';
      alert.innerHTML = msg;
      alert.style.backgroundColor = type === 'error' ? '#fee2e2' : '#dcfce7';
      alert.style.color = type === 'error' ? '#dc2626' : '#166534';
      alert.style.border = type === 'error' ? '1px solid #fca5a5' : '1px solid #bbf7d0';
  }

  document.getElementById('updateProfileForm')?.addEventListener('submit', async function(e) {
      e.preventDefault();
      const btn = document.getElementById('updateProfileBtn');
      const originalText = btn.innerHTML;
      btn.innerHTML = 'Saving...'; btn.disabled = true;

      try {
          const res = await fetch('', { method: 'POST', body: new FormData(this) });
          const data = await res.json();
          if (data.status === 'success') {
              showProfileAlert(data.message, 'success');
              const newName = document.querySelector('input[name="name"]').value;
              const newPhone = document.querySelector('input[name="phone"]').value;
              const newSupport = document.querySelector('input[name="support_link"]').value;
              document.getElementById('currentNameDisplay').innerText = newName;
              document.getElementById('currentPhoneDisplay').innerHTML = newPhone ? newPhone : '<span style="color:#9ca3af;font-size:13px;font-style:italic;">Not provided</span>';
              document.getElementById('currentSupportLinkDisplay').innerHTML = newSupport ? newSupport.replace(/</g, "&lt;").replace(/>/g, "&gt;") : '<span style="color:#9ca3af;font-size:13px;font-style:italic;">Not provided</span>';
              setTimeout(hideProfileEdit, 2000);
          } else {
              showProfileAlert(data.message || 'Error occurred', 'error');
          }
      } catch (err) {
          showProfileAlert('Network Error', 'error');
      } finally {
          btn.innerHTML = originalText; btn.disabled = false;
      }
  });

  document.getElementById('requestEmailForm')?.addEventListener('submit', async function(e) {
      e.preventDefault();
      const btn = document.getElementById('requestEmailBtn');
      const originalText = btn.innerHTML;
      btn.innerHTML = 'Sending...'; btn.disabled = true;

      try {
          const res = await fetch('', { method: 'POST', body: new FormData(this) });
          const data = await res.json();
          if (data.status === 'otp_required') {
              this.style.display = 'none';
              document.getElementById('verifyEmailForm').style.display = 'flex';
              showEmailAlert('OTP sent to your new email address. Please enter it below.', 'success');
          } else {
              showEmailAlert(data.message || 'Error occurred', 'error');
          }
      } catch (err) {
          showEmailAlert('Network Error', 'error');
      } finally {
          btn.innerHTML = originalText; btn.disabled = false;
      }
  });

  document.getElementById('verifyEmailForm')?.addEventListener('submit', async function(e) {
      e.preventDefault();
      const btn = document.getElementById('verifyEmailBtn');
      const originalText = btn.innerHTML;
      btn.innerHTML = 'Verifying...'; btn.disabled = true;

      try {
          const res = await fetch('', { method: 'POST', body: new FormData(this) });
          const data = await res.json();
          if (data.status === 'success') {
              showEmailAlert(data.message, 'success');
              document.getElementById('currentEmailDisplay').innerText = document.querySelector('input[name="new_email"]').value;
              setTimeout(hideEmailChange, 2000);
          } else {
              showEmailAlert(data.message || 'Error occurred', 'error');
          }
      } catch (err) {
          showEmailAlert('Network Error', 'error');
      } finally {
          btn.innerHTML = originalText; btn.disabled = false;
      }
  });
</script>


</body>
</html>
