<?php
require_once '../config/config.php';
require_once '../classes/Database.php';
require_once '../classes/Auth.php';
require_once '../classes/User.php';
require_once '../classes/OTPManager.php';

$db = Database::getInstance();
$auth = new Auth($db);

if (!$auth->isLoggedIn()) {
    header('Location: ../login.php');
    exit();
}

$userClass = new User($db);
$currentUser = $auth->getCurrentUser();

// Get full user data including email_verified status
$userDetails = $db->fetch(
    'SELECT * FROM users WHERE id = ?',
    [$currentUser['id']]
);

$message = '';
$saveSuccess = false;
$emailChanged = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');

    // Check if email changed
    $oldEmail = $userDetails['email'] ?? '';
    $emailChanged = ($email !== $oldEmail);

    if ($userClass->updateProfile($currentUser['id'], $name, $email)) {
        $message = '✅ Profile updated successfully';
        $saveSuccess = true;
        $_SESSION['user_name'] = $name;
        $_SESSION['user_email'] = $email;
        
        // If email changed, generate OTP and mark as unverified
        if ($emailChanged) {
            $db->update(
                'users',
                ['email_verified' => 0, 'email_verified_at' => NULL],
                'id = ?',
                [$currentUser['id']]
            );
            
            // Delete old OTP if exists
            $db->query('DELETE FROM email_otps WHERE email = ?', [$oldEmail]);
            
            // Generate and send OTP to new email
            $otp = new OTPManager($db);
            $otpSent = $otp->generateAndSendOTP($email, $name);
            
            if ($otpSent) {
                $message = '✅ Profile updated! OTP sent to new email. Please verify it.';
            } else {
                $message = '✅ Profile updated but failed to send OTP. Please try again.';
            }
        }
        
        // Refresh user details
        $userDetails = $db->fetch(
            'SELECT * FROM users WHERE id = ?',
            [$currentUser['id']]
        );
    } else {
        $message = '❌ Failed to update profile. Please try again.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Profile - <?php echo APP_NAME; ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<style>
body {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    padding: 20px 0;
}
.container {
    max-width: 600px;
}
.card {
    border: none;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0,0,0,0.15);
}
.card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 16px 16px 0 0 !important;
    padding: 24px;
}
.card-header h4 {
    margin: 0;
    font-weight: 600;
}
.form-control {
    border-radius: 8px;
    border: 1px solid #e0e0e0;
    padding: 12px 16px;
}
.form-control:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}
.alert {
    border-radius: 12px;
    border: none;
}
.btn {
    border-radius: 8px;
    padding: 10px 24px;
    font-weight: 600;
}
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 600;
}
.status-verified {
    background-color: #d4edda;
    color: #155724;
}
.status-pending {
    background-color: #fff3cd;
    color: #856404;
}
</style>
</head>
<body>
<div class="container mt-5">
    <div class="card">
        <div class="card-header">
            <h4><i class="bi bi-person-circle"></i> My Profile</h4>
        </div>
        <div class="card-body p-4">
            <!-- Quick User ID Display -->
            <div class="mb-3" style="text-align:center; padding:8px; background:#f8f9fa; border-radius:8px;">
                <small class="text-muted d-block mb-1">Your Account ID</small>
                <div style="font-size:18px; font-weight:700; color:#667eea; font-family:monospace;">SSNT<?php echo htmlspecialchars($userDetails['id']); ?></div>
            </div>

            <!-- ⭐ PREMIUM USER ID BLOCK (UPDATED WITH SSNT PREFIX) -->
            <div class="mb-4 p-3" 
                style="background: linear-gradient(135deg, #ffb347 0%, #ffcc33 100%);
                    border-radius: 16px;
                    color:#4a3c00;
                    font-weight:600;
                    box-shadow:0 4px 12px rgba(0,0,0,0.15);
                    display:flex;
                    align-items:center;
                    gap:12px;">
                <i class="bi bi-shield-lock-fill" style="font-size:24px;"></i>
                <div>
                    <div style="font-size:14px;opacity:0.9;">Premium Account ID</div>
                    <div style="font-size:20px;">SSNT00<?php echo $userDetails['id']; ?></div>
                </div>
            </div>

            <?php if ($message): ?>
                <div class="alert <?php echo $saveSuccess ? 'alert-success' : 'alert-danger'; ?>" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <form method="post">
                <div class="mb-3">
                    <label class="form-label fw-semibold">Full Name</label>
                    <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($userDetails['name'] ?? ''); ?>" required>
                </div>

             <div class="mb-3">
    <label class="form-label fw-semibold">Email Address</label>

    <div class="input-group" 
         style="background:#f3f4f6; border:1px solid #e0e0e0; border-radius:10px; overflow:hidden;">

        <!-- Email (Read Only, Styled) -->
        <span class="input-group-text" 
              style="background:#eef0f3; border:none; color:#6c757d;">
            <i class="bi bi-lock-fill"></i>
        </span>

        <input type="email" name="email" 
               class="form-control" 
               value="<?php echo htmlspecialchars($userDetails['email'] ?? ''); ?>" 
               readonly
               style="background:#f9fafb; border:none; font-weight:500;">

        <!-- Email Status Icon -->
        <span class="input-group-text" style="background:#eef0f3; border:none;">
            <?php if ($userDetails['email_verified']): ?>
                <i class="bi bi-check-circle-fill text-success"></i>
            <?php else: ?>
                <i class="bi bi-exclamation-circle-fill text-warning"></i>
            <?php endif; ?>
        </span>
    </div>

    <small class="text-muted ms-1">
        This email cannot be changed.
    </small>
</div>


                <!-- Email Verification Status -->
                <div class="mb-4">
                    <label class="form-label fw-semibold">Email Verification</label>
                    <?php if ($userDetails['email_verified']): ?>
                        <div class="status-badge status-verified">
                            <i class="bi bi-check-circle-fill"></i>
                            <span>Email Verified</span>
                        </div>
                    <?php else: ?>
                        <div class="status-badge status-pending">
                            <i class="bi bi-exclamation-circle-fill"></i>
                            <span>Email Not Verified</span>
                        </div>
                        <p class="text-muted small mt-2">Verify your email to unlock full features</p>
                        <button type="button" class="btn btn-warning btn-sm mt-2" data-bs-toggle="modal" data-bs-target="#verifyEmailModal">
                            <i class="bi bi-envelope-check"></i> Verify Email Now
                        </button>
                    <?php endif; ?>
                </div>

                <div class="d-flex gap-2 justify-content-between">
                    <a href="dashboard.php" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left"></i> Back to Dashboard
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check-lg"></i> Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<!-- Email Verification Modal -->
<div class="modal fade" id="verifyEmailModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius: 16px;">
            <div class="modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <h5 class="modal-title"><i class="bi bi-envelope-check"></i> Verify Email Address</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div id="verify-message"></div>

                <p class="text-muted mb-3">
                    We have sent an OTP to: <strong><?php echo htmlspecialchars($userDetails['email']); ?></strong>
                </p>

                <form id="otpForm" onsubmit="verifyOTP(event)">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Enter OTP Code</label>
                        <input type="text" id="otp-input" class="form-control" maxlength="6" placeholder="000000" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Verify OTP</button>
                </form>

                <hr>
                <div class="text-center">
                    <small class="text-muted">Didn't receive OTP?</small><br>
                    <button class="btn btn-link btn-sm" onclick="resendOTP()">Resend OTP</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// User data available in JavaScript
const userId = <?php echo json_encode($userDetails['id']); ?>;
const userEmail = '<?php echo htmlspecialchars($userDetails['email']); ?>';
const userName = '<?php echo htmlspecialchars($userDetails['name']); ?>';

// Verify OTP via AJAX
async function verifyOTP(e) {
    e.preventDefault();

    const otp = document.getElementById('otp-input').value.trim();
    const messageDiv = document.getElementById('verify-message');

    if (otp.length !== 6) {
        messageDiv.innerHTML = '<div class="alert alert-danger">Invalid OTP</div>';
        return;
    }

    const res = await fetch('../api/verify_otp_modal.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            otp,
            email: '<?php echo htmlspecialchars($userDetails['email']); ?>'
        })
    });

    const data = await res.json();

    if (data.success) {
        messageDiv.innerHTML = '<div class="alert alert-success">' + data.message + '</div>';
        setTimeout(() => location.reload(), 1500);
    } else {
        messageDiv.innerHTML = '<div class="alert alert-danger">' + data.message + '</div>';
    }
}

async function resendOTP() {
    const messageDiv = document.getElementById('verify-message');

    const res = await fetch('../api/resend_otp_modal.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            email: '<?php echo htmlspecialchars($userDetails['email']); ?>'
        })
    });

    const data = await res.json();

    if (data.success) {
        messageDiv.innerHTML = '<div class="alert alert-success">' + data.message + '</div>';
    } else {
        messageDiv.innerHTML = '<div class="alert alert-danger">' + data.message + '</div>';
    }
}
</script>
</body>
</html>
