<?php
// Get user information
$stmt = $conn->prepare("SELECT id, username, email, phone, balance, role, created_at FROM agents WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if (!$user) {
    header('Location: logout.php');
    exit();
}

$success_message = '';
$error_message = '';

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $new_email = trim($_POST['email']);
    $new_phone = trim($_POST['phone']);
    
    // Validate email
    if (!filter_var($new_email, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'Please enter a valid email address.';
    } else {
        // Check if email is already taken by another user
        $stmt = $conn->prepare("SELECT id FROM agents WHERE email = ? AND id != ?");
        $stmt->bind_param("si", $new_email, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error_message = 'This email address is already in use by another account.';
        } else {
            // Validate phone number - must be exactly 10 digits starting with 0
            if (!empty($new_phone)) {
                // Remove any non-digit characters
                $clean_phone = preg_replace('/\D/', '', $new_phone);
                
                // Check if it's a valid phone number
                if (strlen($clean_phone) !== 10 || substr($clean_phone, 0, 1) !== '0') {
                    $error_message = 'Please enter a valid phone number. Must be exactly 10 digits starting with 0 (e.g., 0247965501).';
                }
            }
            
            if (empty($error_message)) {
                // Update profile
                $update_phone = !empty($new_phone) ? $clean_phone : $user['phone'];
                $stmt = $conn->prepare("UPDATE agents SET email = ?, phone = ? WHERE id = ?");
                $stmt->bind_param("ssi", $new_email, $update_phone, $user_id);
                
                if ($stmt->execute()) {
                    $success_message = 'Profile updated successfully!';
                    // Update the user array with new values
                    $user['email'] = $new_email;
                    $user['phone'] = $clean_phone;
                } else {
                    $error_message = 'Failed to update profile. Please try again.';
                }
                $stmt->close();
            }
        }
    }
}
?>

<!-- Profile Management Section -->
<div class="glass-card rounded-2xl p-6 mb-6 shadow-lg border border-slate-600/50">
    <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-bold text-white">
            <i class="fas fa-user-circle mr-2 text-amber-400"></i>Profile Management
        </h2>
        <div class="flex items-center space-x-2">
            <span class="px-3 py-1 bg-amber-500/20 text-amber-400 rounded-full text-sm font-medium border border-amber-500/30">
                <?php echo ucfirst(str_replace('_', ' ', $role)); ?>
            </span>
            <span class="px-3 py-1 bg-green-500/20 text-green-400 rounded-full text-sm font-medium border border-green-500/30">
                ID: <?php echo $user['id']; ?>
            </span>
        </div>
    </div>

    <!-- User Information Card -->
    <div class="glass-card-light rounded-xl p-6 mb-6 border border-slate-600/50">
        <div class="flex items-center space-x-4">
            <div class="w-16 h-16 bg-gradient-to-r from-amber-500 to-yellow-600 rounded-full flex items-center justify-center shadow-lg golden-glow">
                <i class="fas fa-user text-white text-2xl icon-glow"></i>
            </div>
            <div>
                <h3 class="text-lg font-bold text-white"><?php echo htmlspecialchars($user['username']); ?></h3>
                <p class="text-sm text-gray-400">Member since <?php echo date('M Y', strtotime($user['created_at'])); ?></p>
                <p class="text-sm text-gray-400">Current Balance: <span class="font-semibold text-green-400"><?php echo number_format($user['balance'], 2); ?> GHS</span></p>
            </div>
        </div>
    </div>

    <!-- Profile Update Form -->
    <form method="POST" class="space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Username (Read-only) -->
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">
                    <i class="fas fa-user mr-2 text-amber-400"></i>Username
                </label>
                <input type="text" value="<?php echo htmlspecialchars($user['username']); ?>" 
                       class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-gray-400" 
                       readonly>
                <p class="text-xs text-gray-500 mt-1">Username cannot be changed</p>
            </div>

            <!-- Role (Read-only) -->
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">
                    <i class="fas fa-user-tag mr-2 text-amber-400"></i>Role
                </label>
                <input type="text" value="<?php echo ucfirst(str_replace('_', ' ', $user['role'])); ?>" 
                       class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-gray-400" 
                       readonly>
                <p class="text-xs text-gray-500 mt-1">Role is assigned by administrators</p>
            </div>

            <!-- Email -->
            <div>
                <label for="email" class="block text-sm font-medium text-gray-300 mb-2">
                    <i class="fas fa-envelope mr-2 text-amber-400"></i>Email Address
                </label>
                <input type="email" id="email" name="email" 
                       value="<?php echo htmlspecialchars($user['email']); ?>" 
                       class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500" 
                       required>
                <p class="text-xs text-gray-500 mt-1">Used for notifications and account recovery</p>
            </div>

            <!-- Phone -->
            <div>
                <label for="phone" class="block text-sm font-medium text-gray-300 mb-2">
                    <i class="fas fa-phone mr-2 text-amber-400"></i>Phone Number
                </label>
                <input type="tel" id="phone" name="phone" 
                       value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" 
                       placeholder="0247965501"
                       pattern="[0-9]{10}"
                       maxlength="10"
                       class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500 placeholder-gray-500">
                <p class="text-xs text-gray-500 mt-1">Enter 10-digit phone number (e.g., 0247965501)</p>
            </div>
        </div>

        <!-- Account Statistics -->
        <div class="glass-card-light rounded-xl p-4 border border-slate-600/50">
            <h4 class="text-sm font-medium text-gray-300 mb-3">
                <i class="fas fa-chart-bar mr-2 text-amber-400"></i>Account Statistics
            </h4>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-amber-400"><?php echo number_format($user['balance'], 2); ?></p>
                    <p class="text-xs text-gray-400">Current Balance (GHS)</p>
                </div>
                <div class="text-center">
                    <p class="text-2xl font-bold text-green-400"><?php echo date('d', strtotime($user['created_at'])); ?></p>
                    <p class="text-xs text-gray-400">Account Day</p>
                </div>
                <div class="text-center">
                    <p class="text-2xl font-bold text-purple-400"><?php echo date('Y', strtotime($user['created_at'])); ?></p>
                    <p class="text-xs text-gray-400">Member Since</p>
                </div>
                <div class="text-center">
                    <p class="text-2xl font-bold text-orange-400"><?php echo ucfirst($user['role']); ?></p>
                    <p class="text-xs text-gray-400">Account Type</p>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="flex flex-col sm:flex-row gap-3 pt-4">
            <button type="submit" name="update_profile" 
                    class="flex-1 bg-gradient-to-r from-amber-500 to-yellow-600 text-white py-3 px-6 rounded-lg font-medium hover:from-amber-600 hover:to-yellow-700 transition-all hover-glow">
                <i class="fas fa-save mr-2"></i>Update Profile
            </button>
            <a href="?page=change_password" 
               class="flex-1 border border-slate-600 text-gray-300 py-3 px-6 rounded-lg font-medium hover:bg-slate-700/50 hover:text-white transition-colors text-center">
                <i class="fas fa-key mr-2"></i>Change Password
            </a>
        </div>
    </form>
</div>

<!-- Security Information -->
<div class="glass-card rounded-2xl p-6 shadow-lg border border-slate-600/50">
    <h3 class="text-lg font-bold text-white mb-4">
        <i class="fas fa-shield-alt mr-2 text-amber-400"></i>Security Information
    </h3>
    
    <div class="space-y-4">
        <div class="flex items-start space-x-3">
            <div class="w-8 h-8 bg-green-500/20 rounded-full flex items-center justify-center flex-shrink-0 border border-green-500/30">
                <i class="fas fa-check text-green-400 text-sm"></i>
            </div>
            <div>
                <h4 class="text-sm font-medium text-white">Account Security</h4>
                <p class="text-sm text-gray-400">Your account is secured with industry-standard encryption and authentication.</p>
            </div>
        </div>
        
        <div class="flex items-start space-x-3">
            <div class="w-8 h-8 bg-blue-500/20 rounded-full flex items-center justify-center flex-shrink-0 border border-blue-500/30">
                <i class="fas fa-info-circle text-blue-400 text-sm"></i>
            </div>
            <div>
                <h4 class="text-sm font-medium text-white">Data Privacy</h4>
                <p class="text-sm text-gray-400">Your personal information is protected and will never be shared with third parties.</p>
            </div>
        </div>
        
        <div class="flex items-start space-x-3">
            <div class="w-8 h-8 bg-yellow-500/20 rounded-full flex items-center justify-center flex-shrink-0 border border-yellow-500/30">
                <i class="fas fa-exclamation-triangle text-yellow-400 text-sm"></i>
            </div>
            <div>
                <h4 class="text-sm font-medium text-white">Important Notice</h4>
                <p class="text-sm text-gray-400">Keep your email and phone number updated to receive important notifications about your account.</p>
            </div>
        </div>
    </div>
</div>

<script>
    // Phone number formatting
    document.getElementById('phone').addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        
        // Limit to 10 digits
        if (value.length > 10) {
            value = value.substring(0, 10);
        }
        
        e.target.value = value;
        
        // Validate format
        const phone = value.trim();
        e.target.classList.remove('border-red-500', 'border-green-500');
        
        if (phone.length === 10 && phone.charAt(0) === '0') {
            e.target.classList.add('border-green-500');
        } else if (phone.length > 0) {
            e.target.classList.add('border-red-500');
        }
    });
</script>

<!-- Enhanced Notification System -->
<?php if (isset($success_message) && !empty($success_message)): ?>
<div id="notification-success" class="notification-toast notification-success">
    <div class="notification-content">
        <div class="notification-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="notification-body">
            <h4 class="notification-title">Success!</h4>
            <p class="notification-message"><?php echo htmlspecialchars($success_message); ?></p>
        </div>
        <button class="notification-close" onclick="closeNotification(this)">
            <i class="fas fa-times"></i>
        </button>
    </div>
    <div class="notification-progress"></div>
</div>
<?php endif; ?>

<?php if (isset($error_message) && !empty($error_message)): ?>
<div id="notification-error" class="notification-toast notification-error">
    <div class="notification-content">
        <div class="notification-icon">
            <i class="fas fa-exclamation-triangle"></i>
        </div>
        <div class="notification-body">
            <h4 class="notification-title">Error!</h4>
            <p class="notification-message"><?php echo htmlspecialchars($error_message); ?></p>
        </div>
        <button class="notification-close" onclick="closeNotification(this)">
            <i class="fas fa-times"></i>
        </button>
    </div>
    <div class="notification-progress"></div>
</div>
<?php endif; ?>

<script>
    // Enhanced notification system
    function closeNotification(button) {
        const notification = button.closest('.notification-toast');
        notification.classList.add('notification-hide');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }

    // Auto-hide notifications with progress bar
    document.addEventListener('DOMContentLoaded', function() {
        const notifications = document.querySelectorAll('.notification-toast');
        
        notifications.forEach(notification => {
            // Show notification with animation
            setTimeout(() => {
                notification.classList.add('notification-show');
            }, 100);
            
            // Start progress bar animation
            const progressBar = notification.querySelector('.notification-progress');
            if (progressBar) {
                progressBar.style.animation = 'notification-progress 5s linear forwards';
            }
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                if (notification.classList.contains('notification-show')) {
                    notification.classList.add('notification-hide');
                    setTimeout(() => {
                        notification.remove();
                    }, 300);
                }
            }, 5000);
        });
    });
</script>

<style>
    /* Enhanced Notification Styles */
    .notification-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        min-width: 320px;
        max-width: 400px;
        background: white;
        border-radius: 12px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        z-index: 9999;
        transform: translateX(100%);
        opacity: 0;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border-left: 4px solid;
        overflow: hidden;
    }

    .notification-toast.notification-show {
        transform: translateX(0);
        opacity: 1;
    }

    .notification-toast.notification-hide {
        transform: translateX(100%);
        opacity: 0;
    }

    .notification-success {
        border-left-color: #10b981;
    }

    .notification-error {
        border-left-color: #ef4444;
    }

    .notification-content {
        display: flex;
        align-items: flex-start;
        padding: 16px;
        gap: 12px;
    }

    .notification-icon {
        flex-shrink: 0;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
    }

    .notification-success .notification-icon {
        background: #d1fae5;
        color: #10b981;
    }

    .notification-error .notification-icon {
        background: #fee2e2;
        color: #ef4444;
    }

    .notification-body {
        flex: 1;
        min-width: 0;
    }

    .notification-title {
        font-size: 14px;
        font-weight: 600;
        margin: 0 0 4px 0;
        color: #1f2937;
    }

    .notification-message {
        font-size: 13px;
        color: #6b7280;
        margin: 0;
        line-height: 1.4;
    }

    .notification-close {
        flex-shrink: 0;
        background: none;
        border: none;
        color: #9ca3af;
        cursor: pointer;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.2s;
        font-size: 12px;
    }

    .notification-close:hover {
        background: #f3f4f6;
        color: #374151;
    }

    .notification-progress {
        position: absolute;
        bottom: 0;
        left: 0;
        height: 3px;
        background: #e5e7eb;
        width: 100%;
    }

    .notification-success .notification-progress {
        background: linear-gradient(90deg, #10b981, #34d399);
    }

    .notification-error .notification-progress {
        background: linear-gradient(90deg, #ef4444, #f87171);
    }

    @keyframes notification-progress {
        from {
            width: 100%;
        }
        to {
            width: 0%;
        }
    }

    /* Mobile responsiveness */
    @media (max-width: 640px) {
        .notification-toast {
            top: 10px;
            right: 10px;
            left: 10px;
            min-width: auto;
            max-width: none;
        }
    }

    /* Hover effects */
    .notification-toast:hover {
        transform: translateX(0) scale(1.02);
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
    }

    .notification-toast:hover .notification-progress {
        animation-play-state: paused;
    }
</style>