<?php
require_once '../connection.php';

// Check if user is admin
if (!isAdmin()) {
    header('Location: login.php');
    exit();
}

$client_id = $_GET['id'] ?? 0;

if ($client_id) {
    try {
        // Get client information
        $stmt = $pdo->prepare("SELECT username, full_name, pppoe_username FROM clients WHERE id = ?");
        $stmt->execute([$client_id]);
        $client = $stmt->fetch();
        
        if (!$client) {
            $_SESSION['error'] = "Client not found!";
            header('Location: dashboard.php');
            exit();
        }
        
        // Generate new random password
        $new_password = generateRandomPassword(12);
        $hashed_password = md5($new_password); // Using MD5 for consistency with login system
        
        // Update password in database
        $stmt = $pdo->prepare("UPDATE clients SET pppoe_password = ? WHERE id = ?");
        $stmt->execute([$new_password, $client_id]);
        
        // Update in MikroTik (uncomment when API is configured)
        /*
        require_once 'mikrotik_integration.php';
        $profile = getClientProfile($client_id); // Get current plan profile
        updateMikroTikUserPassword($client['pppoe_username'], $new_password);
        */
        
        // Log the action
        $stmt = $pdo->prepare("
            INSERT INTO payment_logs (client_id, amount, payment_method, status, description) 
            VALUES (?, 0, 'admin_action', 'completed', ?)
        ");
        $stmt->execute([$client_id, "PPPoE password reset by admin"]);
        
        $_SESSION['success'] = "PPPoE password reset successfully!<br>
                                Client: {$client['full_name']}<br>
                                PPPoE Username: {$client['pppoe_username']}<br>
                                <strong>New Password: {$new_password}</strong><br>
                                <small class='text-muted'>Please provide these credentials to the client.</small>";
        
    } catch (Exception $e) {
        $_SESSION['error'] = "Error resetting password: " . $e->getMessage();
    }
} else {
    $_SESSION['error'] = "Invalid client ID";
}

header('Location: dashboard.php');
exit();

// Function to generate random password
function generateRandomPassword($length = 12) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $password;
}
?>