<?php
function wpkginst_fetch_packages() {
    check_ajax_referer('wpkginst_nonce', 'nonce');
    $packages = [
        'php-xml', 'php-mbstring', 'php-curl', 'php-mysql', 'php-gd', 'php-imagick',
        'php-zip', 'php-intl', 'php-bcmath', 'php-soap', 'php-redis', 'php-memcached',
        'php-json', 'php-opcache', 'php-apcu', 'php-uuid', 'php-pgsql', 'php-sqlite3',
        'php-ldap', 'php-imap'
    ];
    $result = [];
    foreach ($packages as $package) {
        // Clear transients to ensure fresh status
        delete_transient('wpkginst_progress_' . $package);
        delete_transient('wpkginst_output_' . $package);
        delete_transient('wpkginst_installed_' . $package);
        $status = wpkginst_get_package_status($package);
        $result[] = [
            'name' => $package,
            'installed' => $status['installed'],
            'message' => $status['message'] ?? ''
        ];
    }
    wp_send_json_success(['packages' => $result]);
}
add_action('wp_ajax_wpkginst_fetch_packages', 'wpkginst_fetch_packages');
function wpkginst_install_package() {
    if (!check_ajax_referer('wpkginst_nonce', 'nonce', false)) {
        wp_send_json_error(['message' => 'Invalid nonce']);
        return;
    }
    $package = sanitize_text_field($_POST['package']);
    $transient_key = 'wpkginst_progress_' . $package;
    $output_key = 'wpkginst_output_' . $package;
    $installed_key = 'wpkginst_installed_' . $package;
    // Simulate progress (increment for polling)
    $current_progress = (int) str_replace('%', '', get_transient($transient_key) ?: '0');
    $new_progress = min(100, $current_progress + 10);
    set_transient($transient_key, $new_progress . '%', 60);
    set_transient($output_key, 'Installing ' . $package . ': ' . $new_progress . '%', 60);
    $command = "apt install $package -y 2>&1";
    $result = wpkginst_execute_ssh_command($command);
    if (!$result['success']) {
        set_transient($transient_key, '0%', 60);
        set_transient($installed_key, false, 60);
        wp_send_json_error(['message' => $result['message']]);
        return;
    }
    $output = $result['output'];
    set_transient($output_key, $output, 60);
    if (strpos($output, 'Unpacking') !== false) {
        set_transient($transient_key, '50%', 60);
    }
    if (strpos($output, 'Setting up') !== false || strpos($output, 'est déjà la version la plus récente') !== false) {
        set_transient($transient_key, '100%', 60);
        set_transient($installed_key, true, 60);
    }
    // Verify installation status with dpkg-query
    $status = wpkginst_get_package_status($package);
    $installed = $status['installed'];
    wp_send_json_success([
        'progress' => get_transient($transient_key),
        'output' => get_transient($output_key),
        'installed' => $installed
    ]);
}
add_action('wp_ajax_wpkginst_install_package', 'wpkginst_install_package');
function wpkginst_uninstall_package() {
    if (!check_ajax_referer('wpkginst_nonce', 'nonce', false)) {
        wp_send_json_error(['message' => 'Invalid nonce']);
        return;
    }
    $package = sanitize_text_field($_POST['package']);
    $transient_key = 'wpkginst_progress_' . $package;
    $output_key = 'wpkginst_output_' . $package;
    $installed_key = 'wpkginst_installed_' . $package;
    // Simulate progress
    $current_progress = (int) str_replace('%', '', get_transient($transient_key) ?: '0');
    $new_progress = min(100, $current_progress + 10);
    set_transient($transient_key, $new_progress . '%', 60);
    set_transient($output_key, 'Uninstalling ' . $package . ': ' . $new_progress . '%', 60);
    $command = "apt remove $package -y 2>&1";
    $result = wpkginst_execute_ssh_command($command);
    if (!$result['success']) {
        set_transient($transient_key, '0%', 60);
        set_transient($installed_key, false, 60);
        wp_send_json_error(['message' => $result['message']]);
        return;
    }
    $output = $result['output'];
    set_transient($output_key, $output, 60);
    set_transient($transient_key, '100%', 60);
    set_transient($installed_key, false, 60);
    wp_send_json_success([
        'progress' => get_transient($transient_key),
        'output' => get_transient($output_key),
        'installed' => false
    ]);
}
add_action('wp_ajax_wpkginst_uninstall_package', 'wpkginst_uninstall_package');
function wpkginst_fetch_package_progress() {
    if (!check_ajax_referer('wpkginst_nonce', 'nonce', false)) {
        wp_send_json_error(['message' => 'Invalid nonce']);
        return;
    }
    $package = sanitize_text_field($_GET['package']);
    $transient_key = 'wpkginst_progress_' . $package;
    $output_key = 'wpkginst_output_' . $package;
    $installed_key = 'wpkginst_installed_' . $package;
    $progress = get_transient($transient_key) ?: '0%';
    $output = get_transient($output_key) ?: '';
    $installed = (bool) get_transient($installed_key);
    // Verify installation status with dpkg-query for accuracy
    $status = wpkginst_get_package_status($package);
    $installed = $status['installed'];
    if ($installed) {
        set_transient($transient_key, '100%', 60);
        set_transient($installed_key, true, 60);
    }
    wp_send_json_success([
        'progress' => $progress,
        'output' => $output,
        'installed' => $installed
    ]);
}
add_action('wp_ajax_wpkginst_fetch_package_progress', 'wpkginst_fetch_package_progress');
function wpkginst_local_test_ssh_connection() {
    if (!check_ajax_referer('wpkginst_nonce', 'nonce', false)) {
        error_log('wpkginst_test_ssh_connection: Invalid nonce');
        wp_send_json_error(['message' => 'Invalid nonce']);
        return;
    }
    $result = wpkginst_test_ssh_connection();
    error_log('wpkginst_test_ssh_connection result: ' . print_r($result, true));
    wp_send_json($result);
}
add_action('wp_ajax_wpkginst_test_ssh_connection', 'wpkginst_local_test_ssh_connection');
?>
