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

/**
 * Returns invoice HTML.
 * If custom_html exists, placeholders are replaced.
 * Otherwise, uses a built-in layout (modern/classic/minimal) based on settings.
 */
function paycal_invoice_get_settings(): array {
  $defaults = [
    'enabled' => 'yes',
    'layout' => 'modern',
    'primary_color' => '#1366D6',
    'accent_color'  => '#23C5F2',
    'logo_id' => 0,
    'business_name' => get_bloginfo('name'),
    'business_details' => '',
    'footer_html' => '<p style="margin:0">תודה רבה! נשמח לראות אתכם שוב.</p>',
    'show_sku' => 0,
    'show_notes' => 1,
    'advanced_mode' => 0,
    'custom_html' => '',
    'trigger_status' => 'completed',
    'israel_allocation_threshold_2025' => 20000,
    'israel_allocation_threshold_2026_h1' => 10000,
    'israel_allocation_threshold_current' => 5000,
    'israel_allocation_current_from' => '2026-06-01',
  ];
  $s = get_option('paycal_invoice_settings', []);
  if (!is_array($s)) $s = [];
  return array_merge($defaults, $s);
}

function paycal_invoice_replace_placeholders(string $html, \WC_Order $order, int $invoice_id): string {
  $allocation_number = $invoice_id > 0 ? (string) get_post_meta($invoice_id, '_paycal_israel_allocation_number', true) : '';
  $map = [
    '{{invoice_id}}' => (string)$invoice_id,
    '{{invoice_number}}' => get_post_field('post_title', $invoice_id),
    '{{order_id}}' => (string)$order->get_id(),
    '{{order_number}}' => (string)$order->get_order_number(),
    '{{order_date}}' => esc_html($order->get_date_created() ? $order->get_date_created()->date_i18n('d/m/Y') : ''),
    '{{total}}' => wp_kses_post(wc_price($order->get_total())),
    '{{billing_name}}' => esc_html(trim($order->get_billing_first_name().' '.$order->get_billing_last_name())),
    '{{billing_email}}' => esc_html($order->get_billing_email()),
    '{{billing_phone}}' => esc_html($order->get_billing_phone()),
    '{{israel_allocation_number}}' => esc_html($allocation_number),
  ];
  return strtr($html, $map);
}

function paycal_invoice_get_order_total_before_vat(\WC_Order $order): float {
  return max(0.0, (float) $order->get_total() - (float) $order->get_total_tax());
}

function paycal_invoice_get_allocation_threshold(?\WC_DateTime $date = null): float {
  $s = paycal_invoice_get_settings();
  $timestamp = $date ? $date->getTimestamp() : current_time('timestamp');
  $current_from = strtotime((string) ($s['israel_allocation_current_from'] ?? '2026-06-01'));
  $h1_2026_from = strtotime('2026-01-01');
  $year_2025_from = strtotime('2025-01-01');

  if ($current_from && $timestamp >= $current_from) {
    return (float) ($s['israel_allocation_threshold_current'] ?? 5000);
  }

  if ($timestamp >= $h1_2026_from && $timestamp <= strtotime('2026-05-31 23:59:59')) {
    return (float) ($s['israel_allocation_threshold_2026_h1'] ?? 10000);
  }

  if ($timestamp >= $year_2025_from && $timestamp <= strtotime('2025-12-31 23:59:59')) {
    return (float) ($s['israel_allocation_threshold_2025'] ?? 20000);
  }

  return (float) ($s['israel_allocation_threshold_current'] ?? 5000);
}

function paycal_invoice_is_allocation_required(\WC_Order $order): bool {
  $currency = strtoupper((string) $order->get_currency());
  if ($currency !== 'ILS') {
    return false;
  }

  return paycal_invoice_get_order_total_before_vat($order) >= paycal_invoice_get_allocation_threshold($order->get_date_created());
}

function paycal_invoice_get_allocation_badge(int $invoice_id, ?\WC_Order $order = null): string {
  $allocation_number = trim((string) get_post_meta($invoice_id, '_paycal_israel_allocation_number', true));
  if ($allocation_number !== '') {
    return 'Allocation number added';
  }

  $required = (string) get_post_meta($invoice_id, '_paycal_israel_allocation_required', true);
  if ($required === '') {
    $required = $order && paycal_invoice_is_allocation_required($order) ? 'yes' : 'no';
  }

  return $required === 'yes' ? 'Allocation number required' : 'Allocation number not required';
}

function paycal_invoice_build_items_table(\WC_Order $order, array $s): string {
  $rows = '';
  foreach ($order->get_items() as $item_id => $item) {
    $product = $item->get_product();
    $sku = ($s['show_sku'] && $product) ? esc_html($product->get_sku()) : '';
    $name = esc_html($item->get_name());
    $qty = (int) $item->get_quantity();
    $total = wc_price($order->get_line_total($item, true, true));

    $rows .= '<tr>'
      . '<td style="padding:10px;border-bottom:1px solid #E3ECFA"><div style="font-weight:700">'.$name.'</div>'
      . ($sku ? '<div style="color:#64748B;font-size:12px">SKU: '.$sku.'</div>' : '')
      . '</td>'
      . '<td style="padding:10px;text-align:center;border-bottom:1px solid #E3ECFA">'.$qty.'</td>'
      . '<td style="padding:10px;text-align:left;border-bottom:1px solid #E3ECFA">'.$total.'</td>'
      . '</tr>';
  }

  return '<table width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin-top:14px">'
    . '<thead><tr>'
    . '<th style="text-align:right;padding:10px;border-bottom:1px solid #E3ECFA;color:#64748B">פריט</th>'
    . '<th style="text-align:center;padding:10px;border-bottom:1px solid #E3ECFA;color:#64748B">כמות</th>'
    . '<th style="text-align:left;padding:10px;border-bottom:1px solid #E3ECFA;color:#64748B">סה״כ</th>'
    . '</tr></thead>'
    . '<tbody>'.$rows.'</tbody>'
    . '</table>';
}

function paycal_invoice_get_authorized_order_for_download(int $invoice_id) {
  if ($invoice_id <= 0 || get_post_type($invoice_id) !== 'asp_invoice') {
    return new \WP_Error('paycal_invoice_not_found', 'Invoice not found.', ['status' => 404]);
  }

  if (!function_exists('wc_get_order')) {
    return new \WP_Error('paycal_invoice_not_found', 'Invoice not found.', ['status' => 404]);
  }

  $order_id = absint(get_post_meta($invoice_id, '_order_id', true));
  $order = $order_id ? wc_get_order($order_id) : null;
  if (!$order) {
    return new \WP_Error('paycal_invoice_not_found', 'Invoice not found.', ['status' => 404]);
  }

  $current_user_id = get_current_user_id();
  $customer_id = (int) $order->get_customer_id();
  if (
    ($current_user_id > 0 && $customer_id === $current_user_id)
    || current_user_can('manage_woocommerce')
    || current_user_can('edit_shop_orders')
  ) {
    return $order;
  }

  return new \WP_Error('paycal_invoice_forbidden', 'Access denied.', ['status' => 403]);
}

function paycal_invoice_render_html(int $invoice_id, ?int $order_id = null): string {
  if (!class_exists('WooCommerce')) return '<p>WooCommerce not active.</p>';

  $order_id = $order_id ?: (int) get_post_meta($invoice_id, '_order_id', true);
  $order = $order_id ? wc_get_order($order_id) : null;
  if (!$order) return '<p>Order not found.</p>';

  $s = paycal_invoice_get_settings();

  $logo_url = '';
  if (!empty($s['logo_id'])) {
    $logo_url = wp_get_attachment_image_url((int)$s['logo_id'], 'medium') ?: '';
  }

  // Advanced custom HTML
  if (!empty($s['advanced_mode']) && !empty($s['custom_html'])) {
    $html = (string) $s['custom_html'];
    $html = paycal_invoice_replace_placeholders($html, $order, $invoice_id);
    return $html;
  }

  // Built-in layouts
  $primary = esc_attr($s['primary_color']);
  $accent = esc_attr($s['accent_color']);
  $biz = esc_html($s['business_name']);
  $biz_details = wp_kses_post($s['business_details']);
  $footer = wp_kses_post($s['footer_html']);
  $allocation_number = $invoice_id > 0 ? trim((string) get_post_meta($invoice_id, '_paycal_israel_allocation_number', true)) : '';
  $allocation_html = $allocation_number !== ''
    ? '<div style="margin-top:10px;color:#0F172A;font-weight:800">Israel Invoices allocation number: '.esc_html($allocation_number).'</div>'
    : '';

  $items = paycal_invoice_build_items_table($order, $s);
  $total = wc_price($order->get_total());

  $header = '
  <div style="border-radius:16px;padding:18px;background:linear-gradient(135deg,#0B2A4A,'.$primary.');color:#fff">
    <div style="display:flex;gap:14px;align-items:center;justify-content:space-between;flex-wrap:wrap">
      <div>
        <div style="font-size:20px;font-weight:900;margin:0">'.$biz.'</div>
        <div style="opacity:.9;color:#E6F4FF;margin-top:6px">חשבונית • '.$order->get_order_number().' • '.($order->get_date_created() ? $order->get_date_created()->date_i18n('d/m/Y') : '').'</div>
      </div>'
      . ($logo_url ? '<img src="'.esc_url($logo_url).'" alt="logo" style="max-height:52px;border-radius:10px" />' : '') .
    '</div>
  </div>';

  $card = '
  <div style="border:1px solid #E3ECFA;border-radius:16px;background:#fff;box-shadow:0 10px 30px rgba(15,23,42,.08);padding:16px;margin-top:14px">
    <div style="display:flex;gap:14px;justify-content:space-between;flex-wrap:wrap">
      <div>
        <div style="color:#64748B;font-weight:700">לכבוד</div>
        <div style="font-weight:900;color:#0F172A">'.esc_html(trim($order->get_billing_first_name().' '.$order->get_billing_last_name())).'</div>
        <div style="color:#64748B">'.esc_html($order->get_billing_email()).'</div>
        <div style="color:#64748B">'.esc_html($order->get_billing_phone()).'</div>
      </div>
      <div style="text-align:left">
        <div style="color:#64748B;font-weight:700">סה״כ לתשלום</div>
        <div style="font-size:22px;font-weight:900;color:#0F172A">'.$total.'</div>
        '.$allocation_html.'
        <div style="margin-top:8px;padding:8px 10px;border-radius:999px;border:1px solid #E3ECFA;display:inline-flex;gap:8px;align-items:center">
          <span style="width:10px;height:10px;border-radius:50%;background:'.$accent.'"></span>
          <span style="color:#0E4C8A;font-weight:800">PayCal</span>
        </div>
      </div>
    </div>
    '.$items.'
  </div>';

  $notes = '';
  if (!empty($s['show_notes'])) {
    $customer_note = $order->get_customer_note();
    if ($customer_note) {
      $notes = '<div style="margin-top:12px;border:1px solid #E3ECFA;border-radius:14px;background:#F5F9FF;padding:12px">
        <div style="font-weight:900;color:#0F172A">הערת לקוח</div>
        <div style="color:#334155;margin-top:6px">'.esc_html($customer_note).'</div>
      </div>';
    }
  }

  $footer_box = '<div style="margin-top:14px;color:#64748B">'.$footer.'</div>';

  $wrap = '<div dir="rtl" style="font-family:Arial,system-ui,-apple-system,Segoe UI,Roboto;max-width:900px;margin:0 auto;padding:20px;background:#F5F9FF">
    '.$header.$card.$notes.$footer_box.'
  </div>';

  return $wrap;
}
