<?php
if (!defined('ABSPATH')) exit;

function paycal_invoice_trigger_status(): string {
  $s = get_option('paycal_invoice_settings', []);
  if (!is_array($s)) $s = [];
  if (isset($s['enabled']) && (string)$s['enabled'] !== 'yes') {
    return 'disabled';
  }
  $st = (string)($s['trigger_status'] ?? 'completed');
  $allowed = ['processing','completed'];
  return in_array($st, $allowed, true) ? $st : 'completed';
}

function paycal_invoice_create_for_order(int $order_id): void {
  $order = wc_get_order($order_id);
  if (!$order) return;

  // prevent duplicates
  // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Duplicate guard for the WooCommerce order currently changing status.
  $existing = get_posts([
    'post_type' => 'asp_invoice',
    'post_status' => 'publish',
    'meta_key' => '_order_id',
    'meta_value' => $order_id,
    'fields' => 'ids',
    'posts_per_page' => 1
  ]);
  // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
  if (!empty($existing)) return;

  $number = asp_get_next_invoice_number();
  $invoice_id = wp_insert_post([
    'post_type' => 'asp_invoice',
    'post_status' => 'publish',
    'post_title' => 'חשבונית #' . $number,
  ]);

  if ($invoice_id) {
    update_post_meta($invoice_id, '_invoice_number', $number);
    update_post_meta($invoice_id, '_order_id', $order_id);
    update_post_meta($invoice_id, '_customer_id', $order->get_user_id());
    $allocation_required = function_exists('paycal_invoice_is_allocation_required') && paycal_invoice_is_allocation_required($order);
    update_post_meta($invoice_id, '_paycal_israel_allocation_required', $allocation_required ? 'yes' : 'no');
    update_post_meta($invoice_id, '_paycal_israel_allocation_status', $allocation_required ? 'missing' : 'not_required');
  }
}

add_action('woocommerce_order_status_processing', function($order_id){
  if (paycal_invoice_trigger_status() === 'processing') {
    paycal_invoice_create_for_order((int)$order_id);
  }
}, 10, 1);

add_action('woocommerce_order_status_completed', function($order_id){
  if (paycal_invoice_trigger_status() === 'completed') {
    paycal_invoice_create_for_order((int)$order_id);
  }
}, 10, 1);
