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

add_action('init', function () {
  register_post_type('asp_invoice', [
    'label' => 'PayCal Invoices',
    'public' => false,
    'show_ui' => true,
    'menu_icon' => 'dashicons-media-text',
    'supports' => ['title'],
  ]);
});

function paycal_invoice_admin_download_url(int $invoice_id): string {
  return wp_nonce_url(
    admin_url('admin-post.php?action=paycal_invoice_download&invoice_id=' . absint($invoice_id)),
    'paycal_invoice_download_' . absint($invoice_id)
  );
}

function paycal_invoice_order_edit_url(int $order_id): string {
  $order = function_exists('wc_get_order') ? wc_get_order($order_id) : null;
  return $order && method_exists($order, 'get_edit_order_url')
    ? $order->get_edit_order_url()
    : admin_url('post.php?post=' . absint($order_id) . '&action=edit');
}

add_filter('manage_asp_invoice_posts_columns', function($cols){
  $cols['order'] = __('Order', 'klamra-paycal-for-aspaclaria');
  $cols['allocation'] = __('Allocation', 'klamra-paycal-for-aspaclaria');
  $cols['download'] = __('Download', 'klamra-paycal-for-aspaclaria');
  return $cols;
});

add_action('manage_asp_invoice_posts_custom_column', function($col, $post_id){
  $invoice_id = absint($post_id);

  if ($col === 'order') {
    $oid = absint(get_post_meta($invoice_id, '_order_id', true));
    if ($oid) {
      echo '<a href="'.esc_url(paycal_invoice_order_edit_url($oid)).'">#'.esc_html((string)$oid).'</a>';
    } else {
      echo '&mdash;';
    }
  }

  if ($col === 'allocation') {
    $oid = absint(get_post_meta($invoice_id, '_order_id', true));
    $order = $oid && function_exists('wc_get_order') ? wc_get_order($oid) : null;
    echo esc_html(function_exists('paycal_invoice_get_allocation_badge') ? paycal_invoice_get_allocation_badge($invoice_id, $order) : '');
  }

  if ($col === 'download') {
    echo '<a class="button" href="'.esc_url(paycal_invoice_admin_download_url($invoice_id)).'">' . esc_html__('Download invoice', 'klamra-paycal-for-aspaclaria') . '</a>';
  }
}, 10, 2);

add_action('admin_notices', function () {
  $screen = function_exists('get_current_screen') ? get_current_screen() : null;
  if (!$screen || $screen->post_type !== 'asp_invoice' || $screen->base !== 'post') {
    return;
  }

  echo '<div class="notice notice-info"><p>' . esc_html__('This invoice is generated from a WooCommerce order. Edit billing/order details from the linked WooCommerce order.', 'klamra-paycal-for-aspaclaria') . '</p></div>';
});

add_action('add_meta_boxes', function () {
  add_meta_box(
    'paycal_invoice_order_box',
    __('Linked WooCommerce order', 'klamra-paycal-for-aspaclaria'),
    'paycal_invoice_render_order_meta_box',
    'asp_invoice',
    'normal',
    'high'
  );

  add_meta_box(
    'paycal_invoice_allocation_box',
    __('Israel Invoices allocation', 'klamra-paycal-for-aspaclaria'),
    'paycal_invoice_render_allocation_meta_box',
    'asp_invoice',
    'side',
    'default'
  );
});

function paycal_invoice_render_order_meta_box(\WP_Post $post): void {
  $invoice_id = absint($post->ID);
  $order_id = absint(get_post_meta($invoice_id, '_order_id', true));
  $order = $order_id && function_exists('wc_get_order') ? wc_get_order($order_id) : null;

  if (!$order) {
    echo '<p>' . esc_html__('No linked WooCommerce order was found for this invoice.', 'klamra-paycal-for-aspaclaria') . '</p>';
    return;
  }

  $customer_name = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
  $allocation_badge = function_exists('paycal_invoice_get_allocation_badge') ? paycal_invoice_get_allocation_badge($invoice_id, $order) : '';

  echo '<table class="widefat striped"><tbody>';
  echo '<tr><th>' . esc_html__('Order number', 'klamra-paycal-for-aspaclaria') . '</th><td>#' . esc_html((string) $order->get_order_number()) . '</td></tr>';
  echo '<tr><th>' . esc_html__('Customer name', 'klamra-paycal-for-aspaclaria') . '</th><td>' . esc_html($customer_name ?: __('Guest customer', 'klamra-paycal-for-aspaclaria')) . '</td></tr>';
  echo '<tr><th>' . esc_html__('Order total', 'klamra-paycal-for-aspaclaria') . '</th><td>' . wp_kses_post($order->get_formatted_order_total()) . '</td></tr>';
  echo '<tr><th>' . esc_html__('Order status', 'klamra-paycal-for-aspaclaria') . '</th><td>' . esc_html(wc_get_order_status_name($order->get_status())) . '</td></tr>';
  echo '<tr><th>' . esc_html__('Allocation status', 'klamra-paycal-for-aspaclaria') . '</th><td><strong>' . esc_html($allocation_badge) . '</strong></td></tr>';
  echo '</tbody></table>';

  echo '<p>';
  echo '<a class="button button-primary" href="' . esc_url(paycal_invoice_order_edit_url($order_id)) . '">' . esc_html__('View order', 'klamra-paycal-for-aspaclaria') . '</a> ';
  echo '<a class="button" href="' . esc_url(paycal_invoice_admin_download_url($invoice_id)) . '">' . esc_html__('Download invoice', 'klamra-paycal-for-aspaclaria') . '</a>';
  echo '</p>';
}

function paycal_invoice_render_allocation_meta_box(\WP_Post $post): void {
  $invoice_id = absint($post->ID);
  $order_id = absint(get_post_meta($invoice_id, '_order_id', true));
  $order = $order_id && function_exists('wc_get_order') ? wc_get_order($order_id) : null;
  $allocation_number = (string) get_post_meta($invoice_id, '_paycal_israel_allocation_number', true);
  $allocation_required = (string) get_post_meta($invoice_id, '_paycal_israel_allocation_required', true);
  if ($allocation_required === '' && $order && function_exists('paycal_invoice_is_allocation_required')) {
    $allocation_required = paycal_invoice_is_allocation_required($order) ? 'yes' : 'no';
  }

  wp_nonce_field('paycal_invoice_allocation_save', 'paycal_invoice_allocation_nonce');
  echo '<p><strong>' . esc_html(function_exists('paycal_invoice_get_allocation_badge') ? paycal_invoice_get_allocation_badge($invoice_id, $order) : '') . '</strong></p>';
  if ($allocation_required === 'yes' && trim($allocation_number) === '') {
    echo '<p class="notice notice-warning" style="padding:8px;margin:8px 0">' . esc_html__('Allocation number required. Invoice generation is not blocked.', 'klamra-paycal-for-aspaclaria') . '</p>';
  }
  echo '<p><label for="paycal_israel_allocation_number">' . esc_html__('Israel Invoices allocation number', 'klamra-paycal-for-aspaclaria') . '</label></p>';
  echo '<input id="paycal_israel_allocation_number" name="paycal_israel_allocation_number" type="text" style="width:100%" value="' . esc_attr($allocation_number) . '" />';
  echo '<p class="description">' . esc_html__('Required only for eligible tax invoices above the legal threshold. This field may be filled manually until automatic Tax Authority integration is implemented.', 'klamra-paycal-for-aspaclaria') . '</p>';
}

add_action('save_post_asp_invoice', function ($post_id) {
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return;
  }
  if (!current_user_can('manage_woocommerce') && !current_user_can('edit_shop_orders') && !current_user_can('manage_options')) {
    return;
  }
  $nonce = sanitize_text_field(wp_unslash($_POST['paycal_invoice_allocation_nonce'] ?? ''));
  if (!$nonce || !wp_verify_nonce($nonce, 'paycal_invoice_allocation_save')) {
    return;
  }

  $allocation_number = sanitize_text_field(wp_unslash($_POST['paycal_israel_allocation_number'] ?? ''));
  update_post_meta($post_id, '_paycal_israel_allocation_number', $allocation_number);

  $order_id = absint(get_post_meta($post_id, '_order_id', true));
  $order = $order_id && function_exists('wc_get_order') ? wc_get_order($order_id) : null;
  $required = $order && function_exists('paycal_invoice_is_allocation_required') && paycal_invoice_is_allocation_required($order);
  update_post_meta($post_id, '_paycal_israel_allocation_required', $required ? 'yes' : 'no');
  update_post_meta($post_id, '_paycal_israel_allocation_status', $allocation_number !== '' ? 'added' : ($required ? 'missing' : 'not_required'));
});

add_action('woocommerce_admin_order_data_after_order_details', function ($order) {
  if (!$order instanceof \WC_Order) {
    return;
  }

  // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Narrow admin lookup for one invoice linked to the current WooCommerce order.
  $invoice_ids = get_posts([
    'post_type' => 'asp_invoice',
    'post_status' => 'publish',
    'meta_key' => '_order_id',
    'meta_value' => $order->get_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

  $invoice_id = !empty($invoice_ids) ? absint($invoice_ids[0]) : 0;
  $label = $invoice_id && function_exists('paycal_invoice_get_allocation_badge')
    ? paycal_invoice_get_allocation_badge($invoice_id, $order)
    : (function_exists('paycal_invoice_is_allocation_required') && paycal_invoice_is_allocation_required($order) ? 'Allocation number required' : 'Allocation number not required');

  echo '<p class="form-field form-field-wide"><strong>' . esc_html__('PayCal Israel Invoices:', 'klamra-paycal-for-aspaclaria') . '</strong> ' . esc_html($label) . '</p>';
});
