<?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 ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Log the received input for debugging
    // file_put_contents('update_functions_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_functions_log.txt', "Invalid JSON input\n", FILE_APPEND);
        exit;
    }

    if (!isset($input['db_credentials'])) {
        file_put_contents('update_functions_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_functions_log.txt', "Database connection failed: " . $mysqli->connect_error . "\n", FILE_APPEND);
        exit;
    }

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

    $args = array(
        'post_type' => 'gocars_shortcode',
        'posts_per_page' => -1,
        'suppress_filters' => true
    );

    $listings = new WP_Query($args);
    if ($listings->have_posts()) {
        while ($listings->have_posts()) {
            $listings->the_post();
            GocarsOnline::update_fields(get_the_ID(), 'controlpanel');
        }
        wp_reset_postdata();
    }

    // Log the update completion
    // file_put_contents('update_functions_log.txt', "Gocars functions updated successfully\n", FILE_APPEND);

    $mysqli->close();

    // Respond with a success message
    echo json_encode(['status' => 'success']);
}
?>
