<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly

use AC_SYNC\Includes\Classes\Api\Action_Wear_Api_Route;
use AC_SYNC\Includes\Classes\Api\Action_Wear_API_Response as ApiResponse;
use AC_SYNC\Includes\Classes\Product\Action_Wear_Product as Product;
use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Queue as JobQueue;


$route = new Action_Wear_Api_Route("/toggle_wc_to_create");
$route->setMethods("POST");
$route->setCallback(function () {
  global $wpdb;
  $response = new ApiResponse();
  $data = json_decode(file_get_contents("php://input"));

  $id = (int)$data->id;

  try {
    $row = $wpdb->get_row($wpdb->prepare(
      "SELECT wc_to_create, sku FROM {$wpdb->prefix}actionwear_products WHERE id = %d", $id
    ));
    $current = (int) $row->wc_to_create;
    $sku = $row->sku;

    // Only reset wc_created if the WC product doesn't actually exist
    $wcProductExists = $sku && wc_get_product_id_by_sku($sku) > 0;
    $updateData = ["wc_to_create" => $current === 0 ? 1 : 0];
    if (!$wcProductExists) {
      $updateData["wc_created"] = 0;
    }
    $wpdb->update("{$wpdb->prefix}actionwear_products", $updateData, ["id" => $id]);

    if ($current === 0) {
      try {
        JobQueue::pushProductImport($sku);
      } catch (\Throwable $e) {
        Log::write($e->getMessage(), Log::ERROR, Log::CONTEXT_GENERAL, __LINE__, __FILE__);
      }
    }
  } catch (\Exception $e) {
    $response->fail($e->getMessage());
    return new WP_REST_Response($response->getResponse(), 422);
  }

  $response->success();
  return $response->getResponse();
});
$route->registerRoute();
