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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

$post_id = get_the_ID();

// Get vendor info (company)
$vendor_id = (int) get_post_meta($post_id, '_manfiet_invoice_vendor_id', true);
$vendor_company = '';
$vendor_phone = '';
$vendor_email = '';
$vendor_address = '';
$vendor_logo_url = '';
$vendor_tagline = '';

if ($vendor_id > 0) {
    $vendor_post = get_post($vendor_id);
    if ($vendor_post && $vendor_post->post_type === 'manfiet_vendor') {
    $vendor_company = (string) get_post_meta($vendor_id, '_manfiet_vendor_company_name', true);
    if ($vendor_company === '') {
      $vendor_company = get_the_title($vendor_post);
    }
        $vendor_phone = (string) get_post_meta($vendor_id, '_manfiet_vendor_phone', true);
        $vendor_email = (string) get_post_meta($vendor_id, '_manfiet_vendor_email', true);
        $vendor_address = (string) get_post_meta($vendor_id, '_manfiet_vendor_address', true);
        $vendor_logo_url = (string) get_post_meta($vendor_id, '_manfiet_vendor_logo_url', true);
        $vendor_tagline = (string) get_post_meta($vendor_id, '_manfiet_vendor_tagline', true);
    }
}

// Get client info (customer)
$client_id = (int) get_post_meta($post_id, '_manfiet_invoice_client_id', true);
$client_name = '';
$client_phone = '';
$client_email = '';
$client_email2 = '';
$client_address = '';

if ($client_id > 0) {
    $client_post = get_post($client_id);
    if ($client_post && $client_post->post_type === 'manfiet_client') {
    $client_name = (string) get_post_meta($client_id, '_manfiet_client_name', true);
    if ($client_name === '') {
      $client_name = get_the_title($client_post);
    }
        $client_phone = (string) get_post_meta($client_id, '_manfiet_client_phone', true);
        $client_email = (string) get_post_meta($client_id, '_manfiet_client_email', true);
        $client_email2 = (string) get_post_meta($client_id, '_manfiet_client_email2', true);
        $client_address = (string) get_post_meta($client_id, '_manfiet_client_address', true);
    }
}

// Legacy invoices may have client_name but no client_id. Resolve by exact name match.
if ($client_id <= 0 && $client_name === '') {
    $client_name = (string) get_post_meta($post_id, '_manfiet_invoice_client_name', true);
}

if ($client_id <= 0 && $client_name !== '') {
    $candidate_client_ids = get_posts([
        'post_type' => 'manfiet_client',
        'post_status' => 'publish',
        'numberposts' => 200,
        'fields' => 'ids',
    ]);

    foreach ((array) $candidate_client_ids as $candidate_id) {
        $candidate_id = (int) $candidate_id;
        $candidate_name = (string) get_post_meta($candidate_id, '_manfiet_client_name', true);
        if ($candidate_name === '') {
            $candidate_post = get_post($candidate_id);
            $candidate_name = $candidate_post ? (string) get_the_title($candidate_post) : '';
        }

        if (strcasecmp(trim($candidate_name), trim($client_name)) !== 0) {
            continue;
        }

        $resolved_client_post = get_post($candidate_id);
        if ($resolved_client_post && $resolved_client_post->post_type === 'manfiet_client') {
            $client_name = $candidate_name;
            $client_phone = (string) get_post_meta($candidate_id, '_manfiet_client_phone', true);
            $client_email = (string) get_post_meta($candidate_id, '_manfiet_client_email', true);
            $client_email2 = (string) get_post_meta($candidate_id, '_manfiet_client_email2', true);
            $client_address = (string) get_post_meta($candidate_id, '_manfiet_client_address', true);
        }
        break;
    }
}

// Fallback to legacy direct entry fields if vendor/client not linked
if (empty($vendor_company)) {
  // Legacy invoices may not have vendor_id saved. If exactly one vendor exists, use it.
  $vendor_ids = get_posts([
    'post_type' => 'manfiet_vendor',
    'post_status' => 'publish',
    'numberposts' => 2,
    'fields' => 'ids',
    'orderby' => 'date',
    'order' => 'DESC',
  ]);

  if (is_array($vendor_ids) && count($vendor_ids) === 1) {
    $fallback_vendor_id = (int) $vendor_ids[0];
    $fallback_vendor_post = get_post($fallback_vendor_id);
    if ($fallback_vendor_post && $fallback_vendor_post->post_type === 'manfiet_vendor') {
      $vendor_company = (string) get_post_meta($fallback_vendor_id, '_manfiet_vendor_company_name', true);
      if ($vendor_company === '') {
        $vendor_company = get_the_title($fallback_vendor_post);
      }
      $vendor_phone = (string) get_post_meta($fallback_vendor_id, '_manfiet_vendor_phone', true);
      $vendor_email = (string) get_post_meta($fallback_vendor_id, '_manfiet_vendor_email', true);
      $vendor_address = (string) get_post_meta($fallback_vendor_id, '_manfiet_vendor_address', true);
      $vendor_logo_url = (string) get_post_meta($fallback_vendor_id, '_manfiet_vendor_logo_url', true);
      $vendor_tagline = (string) get_post_meta($fallback_vendor_id, '_manfiet_vendor_tagline', true);
    }
  }

  if ($vendor_company === '') {
    $vendor_company = get_bloginfo('name') ?: 'Your Company';
    $vendor_phone = (string) get_post_meta($post_id, '_manfiet_invoice_phone', true);
    $vendor_email = (string) get_post_meta($post_id, '_manfiet_invoice_email', true);
    $vendor_address = (string) get_post_meta($post_id, '_manfiet_invoice_address', true);
  }
}

if (empty($client_name)) {
    $client_name = (string) get_post_meta($post_id, '_manfiet_invoice_client_name', true);
}

if (empty($client_phone)) {
  $client_phone = (string) get_post_meta($post_id, '_manfiet_invoice_phone', true);
}

if (empty($client_email)) {
  $client_email = (string) get_post_meta($post_id, '_manfiet_invoice_email', true);
}

if (empty($client_email2)) {
  $client_email2 = (string) get_post_meta($post_id, '_manfiet_invoice_email2', true);
}

if (empty($client_address)) {
  $client_address = (string) get_post_meta($post_id, '_manfiet_invoice_address', true);
}

if (!function_exists('manfiet_get_currency_symbol')) {
  function manfiet_get_currency_symbol($code) {
    $symbols = [
      'BDT' => '৳',
      'USD' => '$',
      'GBP' => '£',
      'EUR' => '€',
      'CAD' => 'CA$',
      'AUD' => 'A$',
      'INR' => '₹',
      'AED' => 'AED ',
      'SAR' => 'SAR ',
      'MYR' => 'RM ',
      'SGD' => 'S$',
    ];
    return $symbols[strtoupper((string) $code)] ?? (strtoupper((string) $code) . ' ');
  }
}

$campaigns = get_post_meta($post_id, '_manfiet_invoice_campaigns', true);
$campaigns = is_array($campaigns) ? $campaigns : json_decode((string) $campaigns, true);
$campaigns = is_array($campaigns) ? $campaigns : [];
$invoice_type = (string) (get_post_meta($post_id, '_manfiet_invoice_type', true) ?: 'standard');
$service_type_label = (string) (get_post_meta($post_id, '_manfiet_service_type_label', true) ?: get_post_meta($post_id, '_manfiet_invoice_service_type_label', true));
$currency_code = (string) (get_post_meta($post_id, '_manfiet_invoice_currency', true) ?: 'BDT');
$currency_symbol = manfiet_get_currency_symbol($currency_code);
$invoice_no = (string) get_post_meta($post_id, '_manfiet_invoice_no', true);
$date = (string) get_post_meta($post_id, '_manfiet_invoice_date', true);
$due_date = (string) get_post_meta($post_id, '_manfiet_invoice_due_date', true);
$bkash = (string) get_post_meta($post_id, '_manfiet_invoice_bkash', true);
$service_desc = (string) get_post_meta($post_id, '_manfiet_invoice_service_desc', true);
$exchange_rate = (float) get_post_meta($post_id, '_manfiet_invoice_exchange_rate', true);
$discount_type = (string) (get_post_meta($post_id, '_manfiet_invoice_discount_type', true) ?: 'percentage');
$discount_val = (float) get_post_meta($post_id, '_manfiet_invoice_discount_val', true);
if (!metadata_exists('post', $post_id, '_manfiet_invoice_discount_val')) {
  $discount_val = (float) get_post_meta($post_id, '_manfiet_invoice_discount_pct', true);
}
$discount_pct = (float) get_post_meta($post_id, '_manfiet_invoice_discount_pct', true);
$vat_pct = (float) get_post_meta($post_id, '_manfiet_invoice_vat_pct', true);
$adjustment_usd = (float) get_post_meta($post_id, '_manfiet_invoice_adjustment_usd', true);
$adjustment_bdt = (float) get_post_meta($post_id, '_manfiet_invoice_adjustment_bdt', true);
$adjustment_note = (string) get_post_meta($post_id, '_manfiet_invoice_adjustment_note', true);
$late_fee_pct = (float) get_post_meta($post_id, '_manfiet_invoice_late_fee_pct', true);
if ($late_fee_pct <= 0) {
    $late_fee_pct = (float) get_option('manfiet_invoice_late_fee_pct', 5.0);
}
$status = (string) get_post_meta($post_id, '_manfiet_invoice_status', true);
$previous_invoice_id = absint(get_post_meta($post_id, '_manfiet_invoice_previous_invoice_id', true));
$previous_invoice_no = (string) get_post_meta($post_id, '_manfiet_invoice_previous_invoice_no', true);
$previous_due_amount = (float) get_post_meta($post_id, '_manfiet_invoice_previous_due_amount', true);
$payment_received_amount = (float) get_post_meta($post_id, '_manfiet_invoice_payment_received_amount', true);
// If structured payment records exist, sum them (more accurate than stored total)
$raw_pmts_check = get_post_meta($post_id, '_manfiet_invoice_payments', true);
$pmts_check = json_decode((string) $raw_pmts_check, true);
if (is_array($pmts_check) && count($pmts_check) > 0) {
  $payment_received_amount = (float) array_sum(array_column($pmts_check, 'amount'));
}
$vendor_website_url = (string) get_post_meta($vendor_id, '_manfiet_vendor_website_url', true);
$payment_link = (string) get_post_meta($post_id, '_manfiet_invoice_payment_link', true);

$raw_payments = get_post_meta($post_id, '_manfiet_invoice_payments', true);
$payments_list = json_decode((string) $raw_payments, true);
if (!is_array($payments_list)) {
  $payments_list = [];
}
if (empty($payments_list) && $payment_received_amount > 0) {
  $payments_list = [
    [
      'id' => 'pay_legacy_1',
      'date' => ($invoice_date ?: gmdate('Y-m-d')) . ' 12:00',
      'amount' => $payment_received_amount,
      'method' => 'Recorded Payment',
      'transaction_id' => '-',
      'note' => '',
    ]
  ];
}

if ($vendor_website_url === '') {
  $vendor_website_url = home_url('/');
}
$payment_status = ucfirst($status ?: 'pending');
$previous_invoice_link = '';
$previous_invoice_label = '';
if ($previous_invoice_no !== '') {
  $previous_invoice_label = $previous_invoice_no;
}
if ($previous_invoice_id) {
  $previous_invoice_link = get_permalink($previous_invoice_id);
  if ($previous_invoice_label === '') {
    $previous_invoice_label = (string) get_post_meta($previous_invoice_id, '_manfiet_invoice_no', true);
  }
}
$financial_account_ids = json_decode((string) get_post_meta($post_id, '_manfiet_invoice_financial_account_ids', true), true);
$financial_account_ids = is_array($financial_account_ids) ? array_values(array_filter(array_map('absint', $financial_account_ids))) : [];
$selected_accounts = [];
foreach ($financial_account_ids as $account_id) {
  $account_post = get_post($account_id);
  if (!$account_post || $account_post->post_type !== 'manfiet_fin_account') {
    continue;
  }

  $selected_accounts[] = [
    'type' => (string) get_post_meta($account_id, '_manfiet_account_type', true),
    'provider_name' => (string) get_post_meta($account_id, '_manfiet_provider_name', true),
    'account_number' => (string) get_post_meta($account_id, '_manfiet_account_number', true),
    'holder_name' => (string) get_post_meta($account_id, '_manfiet_holder_name', true),
    'routing_number' => (string) get_post_meta($account_id, '_manfiet_routing_number', true),
    'branch_name' => (string) get_post_meta($account_id, '_manfiet_branch_name', true),
    'note' => (string) get_post_meta($account_id, '_manfiet_account_note', true),
  ];
}
  $payment_bkash = '';
  foreach ($selected_accounts as $account) {
    if (($account['type'] ?? '') === 'bkash' && !empty($account['account_number'])) {
      $payment_bkash = trim((string) ($account['account_number'] ?? ''));
      break;
    }
  }
  $payment_bkash = $payment_bkash ?: $bkash;
$bank = [
    'name' => (string) get_post_meta($post_id, '_manfiet_invoice_bank_name', true),
    'account' => (string) get_post_meta($post_id, '_manfiet_invoice_bank_account', true),
    'title' => (string) get_post_meta($post_id, '_manfiet_invoice_bank_title', true),
    'branch' => (string) get_post_meta($post_id, '_manfiet_invoice_bank_branch', true),
    'routing' => (string) get_post_meta($post_id, '_manfiet_invoice_bank_routing', true),
    'type' => (string) get_post_meta($post_id, '_manfiet_invoice_bank_type', true),
];

$subtotal_usd = 0;
foreach ($campaigns as $campaign) {
    $subtotal_usd += (float) ($campaign['amount'] ?? 0);
}
// Only perform exchange rate multiplication if invoice type is daily_rate
$effective_exchange_rate = ($invoice_type === 'daily_rate' && $exchange_rate > 0) ? $exchange_rate : 1.0;
$subtotal_bdt = $subtotal_usd * $effective_exchange_rate;
if ($discount_type === 'flat' || $discount_type === 'fixed') {
    $discount_bdt = round(min($subtotal_bdt, max(0, $discount_val)), 2);
    $discount_pct = $subtotal_bdt > 0 ? round(($discount_bdt / $subtotal_bdt) * 100, 2) : 0;
} else {
    $discount_pct = max(0, $discount_val);
    $discount_bdt = round($subtotal_bdt * ($discount_pct / 100), 2);
}
$after_discount = round(max(0, $subtotal_bdt - $discount_bdt), 2);
$vat_bdt = round($after_discount * ($vat_pct / 100), 2);
$grand_total = round($after_discount + $vat_bdt + $adjustment_bdt, 2);
$amount_due = round($grand_total + $previous_due_amount, 2);
$balance_due = round(max(0, $amount_due - $payment_received_amount), 2);
$overpaid_amount = round(max(0, $payment_received_amount - $amount_due), 2);

function manfiet_invoice_money($value) {
    return number_format((float) $value, 2);
}

function manfiet_invoice_format_date($date_string) {
    if (!$date_string) {
        return '';
    }
    try {
        $timestamp = strtotime($date_string);
    return $timestamp ? wp_date('d M Y', $timestamp) : (string) $date_string;
    } catch (\Throwable $e) {
    return (string) $date_string;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php wp_head(); ?>
</head>
<body>
<div class="invoice-wrapper">
  <div class="print-btn">
    <?php if ($payment_link && $balance_due > 0) : ?>
      <a href="<?php echo esc_url($payment_link); ?>" target="_blank" rel="noopener noreferrer" style="text-decoration: none; margin-right: 12px; display: inline-block;">
        <button style="background: #2563eb; color: white; display: flex; align-items: center; gap: 8px;">💳 Pay Invoice Online</button>
      </a>
    <?php endif; ?>
    <button onclick="window.print()">🖨 Print / Save PDF</button>
  </div>

  <div class="invoice">
    <div class="invoice-header">
      <div class="agency-brand">
        <?php
          $logo_urls = array_values(array_filter(array_map('trim', preg_split('/[\r\n,]+/', (string) $vendor_logo_url))));
          $phone_list = array_values(array_filter(array_map('trim', preg_split('/[\r\n,]+/', (string) $vendor_phone))));
          $email_list = array_values(array_filter(array_map('trim', preg_split('/[\r\n,]+/', (string) $vendor_email))));
          $website_list = array_values(array_filter(array_map('trim', preg_split('/[\r\n,]+/', (string) $vendor_website_url))));
        ?>
        <?php if (!empty($logo_urls)) : ?>
          <div class="agency-logo" style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-bottom: 8px;">
            <?php foreach ($logo_urls as $l_url) : ?>
              <img src="<?php echo esc_url($l_url); ?>" alt="<?php echo esc_attr($vendor_company); ?> logo" style="max-height: 52px; width: auto; object-fit: contain;">
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
        <div class="agency-name"><?php echo esc_html($vendor_company); ?></div>
        <?php if ($vendor_tagline) : ?>
          <div class="tagline"><?php echo esc_html($vendor_tagline); ?></div>
        <?php endif; ?>
        <div class="agency-contact">
          <?php if (!empty($phone_list)) : ?>
            <?php echo esc_html(implode(' | ', $phone_list)); ?><br>
          <?php endif; ?>
          <?php if (!empty($email_list)) : ?>
            <?php echo esc_html(implode(' | ', $email_list)); ?><br>
          <?php endif; ?>
          <?php echo nl2br(esc_html($vendor_address)); ?>
        </div>
      </div>
      <div class="invoice-badge">
        <div class="label">INVOICE</div>
        <div class="inv-number"># <?php echo esc_html($invoice_no); ?></div>
        <div class="inv-date">Date: <?php echo esc_html(manfiet_invoice_format_date($date)); ?></div>
        <div class="inv-date">Due: <?php echo esc_html(manfiet_invoice_format_date($due_date)); ?></div>
        <div class="invoice-status"><?php echo esc_html($payment_status); ?></div>
      </div>
    </div>

    <div class="gold-bar"></div>

    <div class="bill-section">
      <div class="bill-to-block">
        <div class="section-label">Bill To</div>
        <div class="client-name"><?php echo esc_html($client_name); ?></div>
        <div class="client-address">
          <?php if ($client_phone) : ?>
            Phone: <?php echo esc_html($client_phone); ?><br>
          <?php endif; ?>
          <?php if ($client_email) : ?>
            Email: <?php echo esc_html($client_email); ?><br>
          <?php endif; ?>
          <?php if ($client_email2) : ?>
            Email 2: <?php echo esc_html($client_email2); ?><br>
          <?php endif; ?>
          <?php if ($client_address) : ?>
            <?php echo nl2br(esc_html($client_address)); ?>
          <?php endif; ?>
        </div>
      </div>
      <div class="campaign-meta">
        <?php if ($service_type_label !== '') : ?>
          <div class="meta-row"><span>Category</span><span><?php echo esc_html($service_type_label); ?></span></div>
        <?php endif; ?>
        <div class="meta-row"><span>Service Type</span><span><?php echo esc_html($service_desc !== '' ? $service_desc : 'Services & Billing'); ?></span></div>
        <div class="meta-row"><span>Payment Status</span><span><?php echo esc_html($payment_status); ?></span></div>
        <?php if ($previous_invoice_label !== '' && $previous_due_amount > 0) : ?>
          <div class="meta-row"><span>Previous Invoice</span><span><?php echo esc_html($previous_invoice_label); ?></span></div>
        <?php endif; ?>
      </div>
    </div>

    <div class="table-section">
      <table>
        <thead>
          <tr>
            <?php if ($invoice_type === 'daily_rate') : ?>
              <th style="width:38%">Item / Campaign</th>
              <th>Daily Rate</th>
              <th>Duration</th>
              <th>Amount</th>
            <?php elseif ($invoice_type === 'hourly') : ?>
              <th style="width:38%">Task / Service</th>
              <th>Hourly Rate</th>
              <th>Hours</th>
              <th>Amount</th>
            <?php elseif ($invoice_type === 'fixed') : ?>
              <th style="width:50%">Milestone / Deliverable</th>
              <th style="width:30%">Description</th>
              <th style="width:20%">Amount</th>
            <?php else : ?>
              <th style="width:40%">Item / Service</th>
              <th>Rate</th>
              <th>Quantity</th>
              <th>Total Amount</th>
            <?php endif; ?>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($campaigns as $campaign) : ?>
          <tr>
            <td>
              <div class="service-name"><?php echo esc_html($campaign['name'] ?? ''); ?></div>
              <?php if (!empty($campaign['description'])) : ?>
                <div class="service-desc"><?php echo esc_html($campaign['description']); ?></div>
              <?php endif; ?>
            </td>
            <?php if ($invoice_type === 'daily_rate') : ?>
              <td>$<?php echo esc_html(number_format((float) ($campaign['daily_budget'] ?? 0), 2)); ?> / day</td>
              <td><?php echo esc_html((int) ($campaign['duration'] ?? 0)); ?> days</td>
              <td>$<?php echo esc_html(number_format((float) ($campaign['amount'] ?? 0), 2)); ?></td>
            <?php elseif ($invoice_type === 'hourly') : ?>
              <td><?php echo esc_html($currency_symbol); ?><?php echo esc_html(number_format((float) ($campaign['daily_budget'] ?? 0), 2)); ?> / hr</td>
              <td><?php echo esc_html((float) ($campaign['duration'] ?? 0)); ?> hrs</td>
              <td><?php echo esc_html($currency_symbol); ?><?php echo esc_html(number_format((float) ($campaign['amount'] ?? 0), 2)); ?></td>
            <?php elseif ($invoice_type === 'fixed') : ?>
              <td colspan="1"><?php echo esc_html($campaign['description'] ?? '-'); ?></td>
              <td><?php echo esc_html($currency_symbol); ?><?php echo esc_html(number_format((float) ($campaign['amount'] ?? 0), 2)); ?></td>
            <?php else : ?>
              <td><?php echo esc_html($currency_symbol); ?><?php echo esc_html(number_format((float) ($campaign['daily_budget'] ?? 0), 2)); ?></td>
              <td><?php echo esc_html((float) ($campaign['duration'] ?? 1)); ?></td>
              <td><?php echo esc_html($currency_symbol); ?><?php echo esc_html(number_format((float) ($campaign['amount'] ?? 0), 2)); ?></td>
            <?php endif; ?>
          </tr>
        <?php endforeach; ?>
        <?php if ($adjustment_usd != 0 || $adjustment_bdt != 0 || !empty($adjustment_note)) : ?>
          <?php
            $adj_active_val = ($adjustment_bdt !== 0.0) ? $adjustment_bdt : $adjustment_usd;
            $adj_color = $adj_active_val < 0 ? '#b91c1c' : '#15803d';
            $adj_sign = $adj_active_val < 0 ? '−' : '+';
            $adj_amount_num = ($adjustment_bdt !== 0.0) ? abs($adjustment_bdt) : abs($adjustment_usd);
          ?>
          <tr class="adjustment-row" style="background: #fafaf9; font-style: italic;">
            <td colspan="<?php echo ($invoice_type === 'fixed' ? 2 : 3); ?>">
              <strong>Adjustment:</strong> <?php echo esc_html($adjustment_note ?: 'Invoice adjustment'); ?>
            </td>
            <td style="font-weight: bold; color: <?php echo esc_attr($adj_color); ?>;">
              <?php echo esc_html($adj_sign . $currency_symbol . manfiet_invoice_money($adj_amount_num)); ?>
            </td>
          </tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>

    <div class="totals-section">
      <div class="totals-box">
        <?php if ($invoice_type === 'daily_rate' && $exchange_rate > 0) : ?>
          <div class="totals-row"><span class="label">Subtotal (USD)</span><span class="val">$<?php echo esc_html(manfiet_invoice_money($subtotal_usd)); ?></span></div>
          <div class="totals-row"><span class="label">Exchange Rate</span><span class="val">× <?php echo esc_html(number_format($exchange_rate, 2)); ?> BDT</span></div>
          <div class="totals-row"><span class="label">Subtotal (BDT)</span><span class="val">৳<?php echo esc_html(manfiet_invoice_money($subtotal_bdt)); ?></span></div>
          <?php $disc_label_bdt = ($discount_type === 'flat' || $discount_type === 'fixed') ? 'Discount (Flat)' : 'Discount (' . number_format($discount_pct, 2) . '%)'; ?>
          <div class="totals-row" style="color: var(--success);"><span class="label"><?php echo esc_html($disc_label_bdt); ?></span><span class="val" style="color: var(--success);">− ৳<?php echo esc_html(manfiet_invoice_money($discount_bdt)); ?></span></div>
          <div class="totals-row"><span class="label">After Discount</span><span class="val">৳<?php echo esc_html(manfiet_invoice_money($after_discount)); ?></span></div>
          <div class="totals-row"><span class="label">VAT (<?php echo esc_html(number_format($vat_pct, 2)); ?>%)</span><span class="val">+ ৳<?php echo esc_html(manfiet_invoice_money($vat_bdt)); ?></span></div>
          <?php if ($adjustment_bdt != 0) : ?>
          <div class="totals-row" style="color: <?php echo $adjustment_bdt < 0 ? '#b91c1c' : '#15803d'; ?>;"><span class="label">Adjustment</span><span class="val" style="color: <?php echo $adjustment_bdt < 0 ? '#b91c1c' : '#15803d'; ?>;"><?php echo $adjustment_bdt < 0 ? '−' : '+'; ?> ৳<?php echo esc_html(manfiet_invoice_money(abs($adjustment_bdt))); ?></span></div>
          <?php endif; ?>
          <div class="totals-row grand"><span>Grand Total</span><span class="gr-val">৳<?php echo esc_html(manfiet_invoice_money($grand_total)); ?></span></div>
          <?php if ($previous_due_amount > 0) : ?>
          <div class="totals-row"><span class="label">Previous Due</span><span class="val">+ ৳<?php echo esc_html(manfiet_invoice_money($previous_due_amount)); ?></span></div>
          <?php endif; ?>
          <div class="totals-row"><span class="label">Total Amount Due</span><span class="val">৳<?php echo esc_html(manfiet_invoice_money($amount_due)); ?></span></div>
          <div class="totals-row" style="color: var(--success);"><span class="label">Paid Amount</span><span class="val" style="color: var(--success);">− ৳<?php echo esc_html(manfiet_invoice_money($payment_received_amount)); ?></span></div>
          <?php if ($overpaid_amount > 0) : ?>
            <div class="totals-row" style="color: #2563eb; background: #eff6ff; padding: 4px 8px; border-radius: 4px; margin: 4px 0;"><span class="label" style="color: #1e40af; font-weight: 600;">Overpaid / Refundable</span><span class="val" style="color: #2563eb; font-weight: 700;">৳<?php echo esc_html(manfiet_invoice_money($overpaid_amount)); ?></span></div>
          <?php endif; ?>
          <div class="totals-row grand" style="border-top: 2px solid var(--border); padding-top: 8px; margin-top: 6px;"><span class="label">Balance Due</span><span class="gr-val">৳<?php echo esc_html(manfiet_invoice_money($balance_due)); ?></span></div>
        <?php else : ?>
          <div class="totals-row"><span class="label">Subtotal</span><span class="val"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($subtotal_bdt)); ?></span></div>
          <?php $disc_label_cur = ($discount_type === 'flat' || $discount_type === 'fixed') ? 'Discount (Flat)' : 'Discount (' . number_format($discount_pct, 2) . '%)'; ?>
          <div class="totals-row" style="color: var(--success);"><span class="label"><?php echo esc_html($disc_label_cur); ?></span><span class="val" style="color: var(--success);">− <?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($discount_bdt)); ?></span></div>
          <div class="totals-row"><span class="label">After Discount</span><span class="val"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($after_discount)); ?></span></div>
          <div class="totals-row"><span class="label">VAT (<?php echo esc_html(number_format($vat_pct, 2)); ?>%)</span><span class="val">+ <?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($vat_bdt)); ?></span></div>
          <?php if ($adjustment_bdt != 0) : ?>
          <div class="totals-row" style="color: <?php echo $adjustment_bdt < 0 ? '#b91c1c' : '#15803d'; ?>;"><span class="label">Adjustment</span><span class="val" style="color: <?php echo $adjustment_bdt < 0 ? '#b91c1c' : '#15803d'; ?>;"><?php echo $adjustment_bdt < 0 ? '−' : '+'; ?> <?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money(abs($adjustment_bdt))); ?></span></div>
          <?php endif; ?>
          <div class="totals-row grand"><span>Grand Total</span><span class="gr-val"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($grand_total)); ?></span></div>
          <?php if ($previous_due_amount > 0) : ?>
          <div class="totals-row"><span class="label">Previous Due</span><span class="val">+ <?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($previous_due_amount)); ?></span></div>
          <?php endif; ?>
          <div class="totals-row"><span class="label">Total Amount Due</span><span class="val"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($amount_due)); ?></span></div>
          <div class="totals-row" style="color: var(--success);"><span class="label">Paid Amount</span><span class="val" style="color: var(--success);">− <?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($payment_received_amount)); ?></span></div>
          <?php if ($overpaid_amount > 0) : ?>
            <div class="totals-row" style="color: #2563eb; background: #eff6ff; padding: 4px 8px; border-radius: 4px; margin: 4px 0;"><span class="label" style="color: #1e40af; font-weight: 600;">Overpaid / Refundable</span><span class="val" style="color: #2563eb; font-weight: 700;"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($overpaid_amount)); ?></span></div>
          <?php endif; ?>
          <div class="totals-row grand" style="border-top: 2px solid var(--border); padding-top: 8px; margin-top: 6px;"><span class="label">Balance Due</span><span class="gr-val"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($balance_due)); ?></span></div>
        <?php endif; ?>
      </div>
    </div>

    <div class="payment-section">
      <div class="payment-card settled">
        <div class="card-label">Paid Amount</div>
        <div class="card-value"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($payment_received_amount)); ?></div>
        <div class="card-note">Recorded against this invoice</div>
      </div>
      <?php if ($overpaid_amount > 0) : ?>
        <div class="payment-card" style="border: 2px solid #2563eb; background: #eff6ff; border-radius: 8px; padding: 16px;">
          <div class="card-label" style="color: #1e40af; font-weight: 700;">Refundable / Overpaid</div>
          <div class="card-value" style="color: #2563eb; font-size: 24px; font-weight: 700;"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($overpaid_amount)); ?></div>
          <div class="card-note" style="color: #1e40af;">Client overpaid against this invoice — Refund due</div>
        </div>
      <?php else : ?>
        <div class="payment-card due">
          <div class="card-label">Due Amount</div>
          <div class="card-value"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($balance_due)); ?></div>
          <div class="card-note">Please settle by <?php echo esc_html(manfiet_invoice_format_date($due_date)); ?><?php if ($late_fee_pct > 0) : ?> (Overdue fee: <?php echo esc_html($late_fee_pct); ?>%)<?php endif; ?></div>
          <?php if ($payment_link && $balance_due > 0) : ?>
            <div class="no-print" style="margin-top: 15px;">
              <a href="<?php echo esc_url($payment_link); ?>" target="_blank" rel="noopener noreferrer" style="text-decoration: none; display: block;">
                <button style="background: #2563eb; color: white; border: none; padding: 10px 20px; font-family: inherit; font-size: 13px; font-weight: 600; border-radius: 6px; cursor: pointer; transition: background 0.2s; width: 100%; box-shadow: 0 4px 10px rgba(37, 99, 235, 0.15);">
                  💳 Pay Now Online
                </button>
              </a>
            </div>
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>

    <?php if (!empty($payments_list)) : ?>
    <div style="margin-top: 20px; border: 1px solid var(--border); border-radius: 10px; padding: 16px; background: #fafafa;">
      <div class="note-label" style="margin-bottom: 12px; font-weight: 600; color: var(--strong); font-size: 14px;">Payments Received</div>
      <table style="width: 100%; border-collapse: collapse; font-size: 13px; color: var(--text);">
        <thead>
          <tr style="border-bottom: 2px solid var(--border); text-align: left;">
            <th style="padding: 6px 8px;">Date &amp; Time</th>
            <th style="padding: 6px 8px;">Method</th>
            <th style="padding: 6px 8px;">Transaction ID / Ref</th>
            <th style="padding: 6px 8px; text-align: right;">Amount Paid</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($payments_list as $pay) : ?>
          <tr style="border-bottom: 1px solid var(--border);">
            <td style="padding: 8px;"><?php echo esc_html($pay['date'] ?? '-'); ?></td>
            <td style="padding: 8px;"><span style="background: #e0f2fe; color: #0369a1; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 500;"><?php echo esc_html($pay['method'] ?: 'Standard'); ?></span></td>
            <td style="padding: 8px;"><code><?php echo esc_html($pay['transaction_id'] ?: '-'); ?></code></td>
            <td style="padding: 8px; text-align: right; font-weight: 600;"><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money((float) ($pay['amount'] ?? 0))); ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>

    <div class="notes-section">
      <div class="note-label">Payment Information</div>
      <p>
        Please make payment via bKash to <strong><?php echo esc_html($payment_bkash); ?></strong> or bank transfer.<br>
        Kindly mention your invoice number <strong><?php echo esc_html($invoice_no); ?></strong> as the reference.<br>
        <?php if ($previous_invoice_label !== '' && $previous_due_amount > 0) : ?>
        Previous invoice <strong><?php echo esc_html($previous_invoice_label); ?></strong> carried due of <strong><?php echo esc_html($currency_symbol); ?><?php echo esc_html(manfiet_invoice_money($previous_due_amount)); ?></strong>.<br>
        <?php endif; ?>
        For any queries, contact us at <strong><?php echo esc_html($vendor_phone); ?></strong> or <strong><?php echo esc_html($vendor_email); ?></strong>.
      </p>

      <div class="terms-conditions-box" style="margin-top: 16px; border: 1px solid #e2e8f0; border-left: 4px solid #b8963e; border-radius: 8px; padding: 14px 18px; background: #fafaf9;">
        <div class="note-label" style="font-weight: 700; color: #1e293b; margin-bottom: 8px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px;">Terms &amp; Conditions</div>
        <ul style="margin: 0; padding-left: 18px; line-height: 1.8; color: #475569; font-size: 13px;">
          <?php if (!empty($due_date)) : ?>
            <li>Payment is due on or before <strong><?php echo esc_html(manfiet_invoice_format_date($due_date)); ?></strong>.</li>
          <?php endif; ?>
          <?php if ($late_fee_pct > 0) : ?>
            <li>An overdue fee of <strong><?php echo esc_html($late_fee_pct); ?>%</strong> will apply to any unpaid balance after the due date.</li>
          <?php endif; ?>
          <li>Please quote invoice number <strong><?php echo esc_html($invoice_no); ?></strong> as reference when making payments.</li>
          <?php
            $notes = (string) get_post_meta($post_id, '_manfiet_invoice_notes', true);
          ?>
          <?php if (!empty($notes)) : ?>
            <li style="margin-top: 6px; list-style-type: none; margin-left: -18px; padding: 8px 12px; background: #fff; border: 1px solid #e2e8f0; border-radius: 6px; color: #334155;"><?php echo nl2br(esc_html($notes)); ?></li>
          <?php endif; ?>
        </ul>
      </div>

      <div style="margin-top:12px;">
        <div class="note-label" style="margin-bottom:8px;">Payment Accounts</div>
        <?php
          $display_accounts = array_values(array_filter($selected_accounts, function ($account) {
              return ($account['type'] ?? '') !== 'bkash';
          }));
        ?>
        <?php if (!empty($display_accounts)) : ?>
          <div style="font-size:13px; color:var(--muted); line-height:1.7; display:grid; gap:12px;">
            <?php foreach ($display_accounts as $account) : ?>
              <div style="padding:12px 14px; border:1px solid var(--border); border-radius:10px; background:#fff;">
                <strong><?php echo esc_html(trim(($account['provider_name'] ?: 'Account') . ' ' . ($account['account_number'] ? '- ' . $account['account_number'] : ''))); ?></strong><br>
                Type: <?php echo esc_html($account['type'] ?: 'bank'); ?><br>
                Holder: <?php echo esc_html($account['holder_name']); ?><br>
                Branch: <?php echo esc_html($account['branch_name']); ?><br>
                Routing: <?php echo esc_html($account['routing_number']); ?>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else : ?>
          <div style="font-size:13px; color:var(--muted); line-height:1.6;">
            <strong><?php echo esc_html($bank['name']); ?></strong><br>
            Account: <?php echo esc_html($bank['account']); ?><br>
            Account title: <?php echo esc_html($bank['title']); ?><br>
            <?php echo esc_html($bank['branch']); ?><br>
            Routing number: <?php echo esc_html($bank['routing']); ?><br>
            Account type: <?php echo esc_html($bank['type']); ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="invoice-footer">
      <div class="footer-left">Thank you for your business.</div>
      <div class="footer-right">
        <?php if (!empty($website_list)) : ?>
          <?php foreach ($website_list as $idx => $site_url) : ?>
            <?php if ($idx > 0) echo ' <span style="margin: 0 4px; opacity: 0.6;">|</span> '; ?>
            <a href="<?php echo esc_url($site_url); ?>" target="_blank" rel="noreferrer"><?php echo esc_html(wp_parse_url($site_url, PHP_URL_HOST) ?: $site_url); ?></a>
          <?php endforeach; ?>
        <?php else : ?>
          <a href="<?php echo esc_url(home_url('/')); ?>" target="_blank" rel="noreferrer"><?php echo esc_html(wp_parse_url(home_url('/'), PHP_URL_HOST)); ?></a>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
</body>
</html>
