<?php
// Admin Profile Management Page Content
// Note: config.php and AdminAuth are already loaded by admin/index.php

// Set page variables for header
$page_title = 'Admin Profile';
$page_description = 'Manage your admin account details and settings';

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

// Get current admin data
$adminId = $_SESSION['admin_id'];
$stmt = $conn->prepare("SELECT id, username, email, phone, full_name, role, status, last_login, created_at FROM admin_users WHERE id = ?");
$stmt->bind_param("i", $adminId);
$stmt->execute();
$result = $stmt->get_result();
$admin = $result->fetch_assoc();
$stmt->close();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    
    // Validate input
    if (empty($email)) {
        $error_message = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'Please enter a valid email address.';
    } elseif (empty($full_name)) {
        $error_message = 'Full name is required.';
    } else {
        try {
            // Check if email is already used by another admin
            $checkStmt = $conn->prepare("SELECT id FROM admin_users WHERE email = ? AND id != ?");
            $checkStmt->bind_param("si", $email, $adminId);
            $checkStmt->execute();
            $checkResult = $checkStmt->get_result();
            
            if ($checkResult->num_rows > 0) {
                $error_message = 'This email address is already in use by another admin.';
            } else {
                // Update admin profile
                $updateStmt = $conn->prepare("UPDATE admin_users SET email = ?, phone = ?, full_name = ?, updated_at = NOW() WHERE id = ?");
                $updateStmt->bind_param("sssi", $email, $phone, $full_name, $adminId);
                
                if ($updateStmt->execute()) {
                    $success_message = 'Profile updated successfully!';
                    // Refresh admin data
                    $stmt = $conn->prepare("SELECT id, username, email, phone, full_name, role, status, last_login, created_at FROM admin_users WHERE id = ?");
                    $stmt->bind_param("i", $adminId);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $admin = $result->fetch_assoc();
                    $stmt->close();
                } else {
                    $error_message = 'Failed to update profile. Please try again.';
                }
                $updateStmt->close();
            }
            $checkStmt->close();
        } catch (Exception $e) {
            $error_message = 'An error occurred while updating your profile.';
            error_log("Admin profile update error: " . $e->getMessage());
        }
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error_message = 'All password fields are required.';
    } elseif ($new_password !== $confirm_password) {
        $error_message = 'New password and confirmation do not match.';
    } elseif (strlen($new_password) < 8) {
        $error_message = 'New password must be at least 8 characters long.';
    } else {
        try {
            // Verify current password
            $verifyStmt = $conn->prepare("SELECT password_hash FROM admin_users WHERE id = ?");
            $verifyStmt->bind_param("i", $adminId);
            $verifyStmt->execute();
            $verifyResult = $verifyStmt->get_result();
            $verifyData = $verifyResult->fetch_assoc();
            $verifyStmt->close();
            
            if (password_verify($current_password, $verifyData['password_hash'])) {
                // Update password
                $newPasswordHash = password_hash($new_password, PASSWORD_DEFAULT);
                $updateStmt = $conn->prepare("UPDATE admin_users SET password_hash = ?, updated_at = NOW() WHERE id = ?");
                $updateStmt->bind_param("si", $newPasswordHash, $adminId);
                
                if ($updateStmt->execute()) {
                    $success_message = 'Password changed successfully!';
                } else {
                    $error_message = 'Failed to change password. Please try again.';
                }
                $updateStmt->close();
            } else {
                $error_message = 'Current password is incorrect.';
            }
        } catch (Exception $e) {
            $error_message = 'An error occurred while changing your password.';
            error_log("Admin password change error: " . $e->getMessage());
        }
    }
}
?>

<!-- Success/Error Messages -->
<?php if (!empty($success_message)): ?>
<div class="bg-green-900/20 border border-green-700/50 rounded-xl p-4 mb-6">
    <div class="flex items-center">
        <i class="fas fa-check-circle text-green-400 mr-3"></i>
        <span class="text-green-300"><?= htmlspecialchars($success_message) ?></span>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($error_message)): ?>
<div class="bg-red-900/20 border border-red-700/50 rounded-xl p-4 mb-6">
    <div class="flex items-center">
        <i class="fas fa-exclamation-circle text-red-400 mr-3"></i>
        <span class="text-red-300"><?= htmlspecialchars($error_message) ?></span>
    </div>
</div>
<?php endif; ?>

<div class="space-y-6">
    <!-- Profile Information Card -->
    <div class="bg-gray-800 rounded-xl shadow-lg p-6 border border-gray-700">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-bold text-gray-100">
                <i class="fas fa-user-cog text-blue-500 mr-3"></i>Profile Information
            </h2>
            <div class="flex items-center space-x-2">
                <span class="px-3 py-1 bg-blue-600 text-white text-sm rounded-full">
                    <?= ucfirst(str_replace('_', ' ', $admin['role'])) ?>
                </span>
                <span class="px-3 py-1 bg-green-600 text-white text-sm rounded-full">
                    <?= ucfirst($admin['status']) ?>
                </span>
            </div>
        </div>

        <!-- Profile Update Form -->
        <form method="POST" action="" class="space-y-6">
            <input type="hidden" name="update_profile" value="1">
            
            <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">Username</label>
                    <input type="text" value="<?= htmlspecialchars($admin['username']) ?>" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-300 cursor-not-allowed" 
                           readonly>
                    <p class="text-xs text-gray-400 mt-1">Username cannot be changed</p>
                </div>
                
                <!-- Full Name -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Full Name *</label>
                    <input type="text" name="full_name" value="<?= htmlspecialchars($admin['full_name']) ?>" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                           required>
                </div>
                
                <!-- Email -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Email Address *</label>
                    <input type="email" name="email" value="<?= htmlspecialchars($admin['email']) ?>" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                           required>
                </div>
                
                <!-- Phone Number -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Phone Number</label>
                    <input type="tel" name="phone" value="<?= htmlspecialchars($admin['phone']) ?>" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                           placeholder="+233XXXXXXXXX">
                    <p class="text-xs text-blue-400 mt-1">Required for SMS notifications</p>
                </div>
            </div>
            
            <!-- Account Information (Read-only) -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 pt-6 border-t border-gray-700">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Account Created</label>
                    <input type="text" value="<?= date('M d, Y H:i', strtotime($admin['created_at'])) ?>" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-300 cursor-not-allowed" 
                           readonly>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Last Login</label>
                    <input type="text" value="<?= $admin['last_login'] ? date('M d, Y H:i', strtotime($admin['last_login'])) : 'Never' ?>" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-300 cursor-not-allowed" 
                           readonly>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Last Updated</label>
                    <input type="text" value="<?= date('M d, Y H:i') ?>" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-300 cursor-not-allowed" 
                           readonly>
                </div>
            </div>
            
            <div class="flex justify-end pt-6">
                <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors">
                    <i class="fas fa-save mr-2"></i>Update Profile
                </button>
            </div>
        </form>
    </div>

    <!-- Change Password Card -->
    <div class="bg-gray-800 rounded-xl shadow-lg p-6 border border-gray-700">
        <h2 class="text-2xl font-bold text-gray-100 mb-6">
            <i class="fas fa-lock text-red-500 mr-3"></i>Change Password
        </h2>

        <form method="POST" action="" class="space-y-6" id="passwordChangeForm">
            <input type="hidden" name="change_password" value="1">
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <!-- Current Password -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Current Password *</label>
                    <input type="password" name="current_password" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-100 placeholder-gray-400 focus:border-red-500 focus:ring-1 focus:ring-red-500" 
                           required>
                </div>
                
                <!-- New Password -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">New Password *</label>
                    <input type="password" name="new_password" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-100 placeholder-gray-400 focus:border-red-500 focus:ring-1 focus:ring-red-500" 
                           required minlength="8">
                    <p class="text-xs text-gray-400 mt-1">Minimum 8 characters</p>
                </div>
                
                <!-- Confirm Password -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Confirm New Password *</label>
                    <input type="password" name="confirm_password" 
                           class="w-full bg-gray-700 border border-gray-600 rounded-lg p-3 text-gray-100 placeholder-gray-400 focus:border-red-500 focus:ring-1 focus:ring-red-500" 
                           required minlength="8">
                </div>
            </div>
            
            <div class="flex justify-end">
                <button type="submit" class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors">
                    <i class="fas fa-key mr-2"></i>Change Password
                </button>
            </div>
        </form>
    </div>

    <!-- Security Information Card -->
    <div class="bg-gray-800 rounded-xl shadow-lg p-6 border border-gray-700">
        <h2 class="text-2xl font-bold text-gray-100 mb-6">
            <i class="fas fa-shield-alt text-yellow-500 mr-3"></i>Security Information
        </h2>
        
        <div class="space-y-4">
            <div class="flex items-center justify-between p-4 bg-gray-700/50 rounded-lg">
                <div class="flex items-center">
                    <i class="fas fa-mobile-alt text-blue-400 mr-3"></i>
                    <div>
                        <h3 class="text-gray-100 font-medium">SMS Notifications</h3>
                        <p class="text-gray-400 text-sm">Login alerts and security notifications</p>
                    </div>
                </div>
                <div class="text-right">
                    <?php if (!empty($admin['phone'])): ?>
                        <span class="text-green-400 text-sm">✓ Enabled</span>
                        <p class="text-gray-400 text-xs"><?= htmlspecialchars($admin['phone']) ?></p>
                    <?php else: ?>
                        <span class="text-red-400 text-sm">✗ Disabled</span>
                        <p class="text-gray-400 text-xs">Add phone number to enable</p>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="flex items-center justify-between p-4 bg-gray-700/50 rounded-lg">
                <div class="flex items-center">
                    <i class="fas fa-envelope text-green-400 mr-3"></i>
                    <div>
                        <h3 class="text-gray-100 font-medium">Email Notifications</h3>
                        <p class="text-gray-400 text-sm">Security alerts and system notifications</p>
                    </div>
                </div>
                <div class="text-right">
                    <?php if (!empty($admin['email'])): ?>
                        <span class="text-green-400 text-sm">✓ Enabled</span>
                        <p class="text-gray-400 text-xs"><?= htmlspecialchars($admin['email']) ?></p>
                    <?php else: ?>
                        <span class="text-red-400 text-sm">✗ Disabled</span>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="flex items-center justify-between p-4 bg-gray-700/50 rounded-lg">
                <div class="flex items-center">
                    <i class="fas fa-history text-purple-400 mr-3"></i>
                    <div>
                        <h3 class="text-gray-100 font-medium">Login History</h3>
                        <p class="text-gray-400 text-sm">Track all admin login attempts</p>
                    </div>
                </div>
                <div class="text-right">
                    <a href="index.php?page=user_activity" class="text-blue-400 text-sm hover:text-blue-300">
                        View History →
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Form validation - Only for password change form
document.addEventListener('DOMContentLoaded', function() {
    const passwordForm = document.getElementById('passwordChangeForm');
    if (passwordForm) {
        passwordForm.addEventListener('submit', function(e) {
            const newPassword = this.querySelector('input[name="new_password"]').value;
            const confirmPassword = this.querySelector('input[name="confirm_password"]').value;
            
            if (newPassword !== confirmPassword) {
                e.preventDefault();
                alert('New password and confirmation do not match.');
                return false;
            }
            
            if (newPassword.length < 8) {
                e.preventDefault();
                alert('New password must be at least 8 characters long.');
                return false;
            }
        });
    }
});
</script>
