<?php
$path = $_SERVER['DOCUMENT_ROOT'];
// Check if request is coming from controlpanel.gocars.online
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$allowed_referer = 'https://controlpanel.gocars.gr/';

//  if (parse_url($referer, PHP_URL_HOST) !== parse_url($allowed_referer, PHP_URL_HOST)) {
//     // Respond with an error if request is not from allowed domain
//     http_response_code(403);
//     header('Content-Type: application/json');
//     echo json_encode(['status' => 'error', 'message' => 'Access Denied']);
//     exit;
// }

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Respond with an error if the request method is not POST
    http_response_code(405);
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Method Not Allowed']);
    exit;
}

if ( !defined('ABSPATH') ) {
    //If wordpress isn't loaded load it up.
    define('WP_USE_THEMES', false);
    require_once $path . '/wp-load.php';
}

// Include the main plugin file to access the update checker instance
require_once WP_PLUGIN_DIR . '/gocars-online/gocars-online.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Log the received input for debugging
    // file_put_contents('update_plugin_log.txt', "Received input: " . file_get_contents('php://input') . "\n", FILE_APPEND);

    $input = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        file_put_contents('update_plugin_log.txt', "Invalid JSON input\n", FILE_APPEND);
        exit;
    }

    if (!isset($input['db_credentials'])) {
        file_put_contents('update_plugin_log.txt', "Missing credentials\n", FILE_APPEND);
        exit;
    }

    $db_credentials = $input['db_credentials'];

    // Connect to the database
    $mysqli = new mysqli(
        $db_credentials['host'],
        $db_credentials['user'],
        $db_credentials['pass'],
        $db_credentials['name']
    );

    if ($mysqli->connect_error) {
        file_put_contents('update_plugin_log.txt', "Database connection failed: " . $mysqli->connect_error . "\n", FILE_APPEND);
        exit;
    }
    // Request plugin update
    $update = $gocars_online_update_checker->requestUpdate();

    if ($update) {
        // Force update using WordPress's built-in updater
        include_once ABSPATH . 'wp-admin/includes/plugin.php';
        include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        include_once ABSPATH . 'wp-admin/includes/file.php';

        $plugin_slug = 'gocars-online/gocars-online.php';

        $upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
        $result = $upgrader->upgrade($plugin_slug);
        // Activate the plugin after update
        activate_plugin($plugin_slug);


        if ($result || is_wp_error($result)) {
            // Log success
            // file_put_contents('update_plugin_log.txt', "Plugin updated to version {$update->version}\n", FILE_APPEND);
            echo json_encode(['status' => 'success', 'message' => 'Plugin updated successfully from ' . $gocars_online_update_checker->getInstalledVersion() . ' to ' . $update->version]);
            
        } else {
            // file_put_contents('update_plugin_log.txt', "No update available\n", FILE_APPEND);         
            echo json_encode(['status' => 'info', 'message' => 'No update available']);
        }
    } else {
        // No update available
        echo json_encode(['status' => 'info', 'message' => 'No Request update available']);
    }

    $mysqli->close();

}

?>