<?php
// Include config and authentication
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

if (!$adminAuth->isAuthenticated()) {
    header('Location: admin_login.php');
    exit;
}

$message = '';
$message_type = '';

// Handle password reset form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'reset_password') {
    $agent_id = (int)$_POST['agent_id'];
    $new_password = trim($_POST['new_password']);
    $confirm_password = trim($_POST['confirm_password']);
    
    // Validation
    if (empty($agent_id) || empty($new_password) || empty($confirm_password)) {
        $message = "Please fill in all fields.";
        $message_type = "error";
    } elseif ($new_password !== $confirm_password) {
        $message = "Passwords do not match.";
        $message_type = "error";
    } elseif (strlen($new_password) < 8) {
        $message = "Password must be at least 8 characters long.";
        $message_type = "error";
    } else {
        // Check if agent exists
        $check_stmt = $conn->prepare("SELECT id, username, email FROM agents WHERE id = ?");
        $check_stmt->bind_param("i", $agent_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        $agent = $result->fetch_assoc();
        $check_stmt->close();
        
        if ($agent) {
            // Hash the new password
            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
            
            // Update agent's password
            $update_stmt = $conn->prepare("UPDATE agents SET password_hash = ? WHERE id = ?");
            $update_stmt->bind_param("si", $password_hash, $agent_id);
            
            if ($update_stmt->execute()) {
                // Log the password reset action
                $log_stmt = $conn->prepare("
                    INSERT INTO admin_actions_log (admin_id, admin_username, action_type, target_type, target_id, target_name, details, ip_address, user_agent, created_at) 
                    VALUES (?, ?, 'password_reset', 'agent', ?, ?, ?, ?, ?, NOW())
                ");
                $admin_id = $_SESSION['admin_id'];
                $admin_username = $_SESSION['admin_username'];
                $details = "Password reset for agent: " . $agent['username'] . " (" . $agent['email'] . ")";
                $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
                
                $log_stmt->bind_param("isissss", $admin_id, $admin_username, $agent_id, $agent['username'], $details, $ip_address, $user_agent);
                $log_stmt->execute();
                $log_stmt->close();
                
                $message = "Password has been successfully reset for agent: " . htmlspecialchars($agent['username']);
                $message_type = "success";
            } else {
                $message = "Failed to update password. Please try again.";
                $message_type = "error";
            }
            $update_stmt->close();
        } else {
            $message = "Agent not found.";
            $message_type = "error";
        }
    }
}

// Get all agents for the dropdown
$agents_query = "SELECT id, username, email, role, account_status FROM agents ORDER BY username ASC";
$agents_result = mysqli_query($conn, $agents_query);

// Set page variables for header
$page_title = 'Password Management';
$page_description = 'Reset agent passwords and manage account security';
?>

<div class="p-6">
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">
            <i class="fas fa-key mr-3 text-blue-600"></i>
            Password Management
        </h1>
        <p class="text-gray-600">Reset agent passwords and manage account security</p>
    </div>

    <!-- Message Display -->
    <?php if (!empty($message)): ?>
    <div class="mb-6 p-4 rounded-lg <?= $message_type === 'success' ? 'bg-green-50 border border-green-200 text-green-700' : 'bg-red-50 border border-red-200 text-red-700' ?>">
        <div class="flex items-center">
            <i class="fas <?= $message_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle' ?> mr-3"></i>
            <span class="font-medium"><?= htmlspecialchars($message) ?></span>
        </div>
    </div>
    <?php endif; ?>

    <!-- Password Reset Form -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-900 mb-6">
            <i class="fas fa-user-lock mr-2"></i>
            Reset Agent Password
        </h2>
        
        <form method="POST" class="space-y-6">
            <input type="hidden" name="action" value="reset_password">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="agent_id" class="block text-sm font-medium text-gray-700 mb-2">Select Agent *</label>
                    <select id="agent_id" name="agent_id" required class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">Choose an agent...</option>
                        <?php while ($agent = mysqli_fetch_assoc($agents_result)): ?>
                        <option value="<?= $agent['id'] ?>" data-email="<?= htmlspecialchars($agent['email']) ?>" data-role="<?= htmlspecialchars($agent['role']) ?>" data-status="<?= htmlspecialchars($agent['account_status']) ?>">
                            <?= htmlspecialchars($agent['username']) ?> (<?= htmlspecialchars($agent['email']) ?>) - <?= ucfirst($agent['role']) ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                    <p class="text-xs text-gray-500 mt-1">Select the agent whose password you want to reset</p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Agent Information</label>
                    <div id="agent-info" class="p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
                        <p>Select an agent to view their information</p>
                    </div>
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="new_password" class="block text-sm font-medium text-gray-700 mb-2">New Password *</label>
                    <input type="password" id="new_password" name="new_password" required class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Enter new password">
                    <p class="text-xs text-gray-500 mt-1">Minimum 8 characters</p>
                </div>
                
                <div>
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-2">Confirm Password *</label>
                    <input type="password" id="confirm_password" name="confirm_password" required class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Confirm new password">
                    <p class="text-xs text-gray-500 mt-1">Must match the new password</p>
                </div>
            </div>
            
            <!-- Password Strength Indicator -->
            <div id="password-strength" class="hidden">
                <div class="text-sm text-gray-600 mb-2">Password Strength:</div>
                <div class="flex space-x-1">
                    <div class="h-2 bg-gray-200 rounded flex-1"></div>
                    <div class="h-2 bg-gray-200 rounded flex-1"></div>
                    <div class="h-2 bg-gray-200 rounded flex-1"></div>
                    <div class="h-2 bg-gray-200 rounded flex-1"></div>
                </div>
                <div id="strength-text" class="text-xs mt-1"></div>
            </div>
            
            <div class="flex justify-end space-x-4">
                <button type="button" onclick="clearForm()" class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                    <i class="fas fa-times mr-2"></i>
                    Clear Form
                </button>
                <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                    <i class="fas fa-key mr-2"></i>
                    Reset Password
                </button>
            </div>
        </form>
    </div>

    <!-- Security Guidelines -->
    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-6">
        <h3 class="text-lg font-semibold text-yellow-900 mb-4">
            <i class="fas fa-shield-alt mr-2"></i>
            Security Guidelines
        </h3>
        <div class="text-yellow-800 space-y-2">
            <ul class="list-disc list-inside space-y-1">
                <li><strong>Strong Passwords:</strong> Use at least 8 characters with uppercase, lowercase, numbers, and symbols</li>
                <li><strong>Agent Notification:</strong> Consider notifying the agent about the password reset</li>
                <li><strong>Audit Trail:</strong> All password resets are logged for security purposes</li>
                <li><strong>Account Status:</strong> Only reset passwords for active accounts</li>
                <li><strong>Immediate Effect:</strong> New password takes effect immediately</li>
            </ul>
        </div>
    </div>
</div>

<script>
// Agent selection handler
document.getElementById('agent_id').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    const agentInfo = document.getElementById('agent-info');
    
    if (this.value) {
        const email = selectedOption.getAttribute('data-email');
        const role = selectedOption.getAttribute('data-role');
        const status = selectedOption.getAttribute('data-status');
        
        agentInfo.innerHTML = `
            <div class="space-y-1">
                <p><strong>Email:</strong> ${email}</p>
                <p><strong>Role:</strong> ${role.charAt(0).toUpperCase() + role.slice(1)}</p>
                <p><strong>Status:</strong> <span class="px-2 py-1 rounded text-xs ${status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">${status.charAt(0).toUpperCase() + status.slice(1)}</span></p>
            </div>
        `;
    } else {
        agentInfo.innerHTML = '<p>Select an agent to view their information</p>';
    }
});

// Password strength checker
function checkPasswordStrength(password) {
    let strength = 0;
    const strengthIndicator = document.getElementById('password-strength');
    const strengthBars = strengthIndicator.querySelectorAll('.h-2');
    const strengthText = document.getElementById('strength-text');
    
    if (password.length >= 8) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/\d/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;
    
    // Update visual indicator
    strengthBars.forEach((bar, index) => {
        bar.className = 'h-2 rounded flex-1 ' + (index < strength ? 
            (strength < 2 ? 'bg-red-400' : strength < 4 ? 'bg-yellow-400' : 'bg-green-400') : 
            'bg-gray-200');
    });
    
    // Update text
    const strengthLevels = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong'];
    strengthText.textContent = strengthLevels[Math.min(strength - 1, 4)] || 'Very Weak';
    strengthText.className = 'text-xs mt-1 ' + (strength < 2 ? 'text-red-600' : strength < 4 ? 'text-yellow-600' : 'text-green-600');
}

// Password input handler
document.getElementById('new_password').addEventListener('input', function() {
    const strengthIndicator = document.getElementById('password-strength');
    
    if (this.value.length > 0) {
        strengthIndicator.classList.remove('hidden');
        checkPasswordStrength(this.value);
    } else {
        strengthIndicator.classList.add('hidden');
    }
});

// Password confirmation handler
document.getElementById('confirm_password').addEventListener('input', function() {
    const newPassword = document.getElementById('new_password').value;
    const confirmPassword = this.value;
    
    if (confirmPassword.length > 0) {
        if (newPassword === confirmPassword) {
            this.classList.remove('border-red-300');
            this.classList.add('border-green-300');
        } else {
            this.classList.remove('border-green-300');
            this.classList.add('border-red-300');
        }
    } else {
        this.classList.remove('border-red-300', 'border-green-300');
    }
});

// Clear form function
function clearForm() {
    document.getElementById('agent_id').value = '';
    document.getElementById('new_password').value = '';
    document.getElementById('confirm_password').value = '';
    document.getElementById('agent-info').innerHTML = '<p>Select an agent to view their information</p>';
    document.getElementById('password-strength').classList.add('hidden');
}

// Form validation
document.querySelector('form').addEventListener('submit', function(e) {
    const agentId = document.getElementById('agent_id').value;
    const newPassword = document.getElementById('new_password').value;
    const confirmPassword = document.getElementById('confirm_password').value;
    
    if (!agentId) {
        alert('Please select an agent.');
        e.preventDefault();
        return;
    }
    
    if (newPassword.length < 8) {
        alert('Password must be at least 8 characters long.');
        e.preventDefault();
        return;
    }
    
    if (newPassword !== confirmPassword) {
        alert('Passwords do not match.');
        e.preventDefault();
        return;
    }
    
    if (!confirm('Are you sure you want to reset this agent\'s password? This action cannot be undone.')) {
        e.preventDefault();
        return;
    }
});
</script>
