<?php
defined('BASEPATH') or exit('No direct script access allowed');
/**
 * application/views/penjualan/list_invoice.php
 * Dipanggil via AJAX dari dashboard (penjualan/list_invoice)
 * Menampilkan: ORDER ID | PELANGGAN | TOTAL | BAYAR | PIUTANG | STATUS(PROSES) | LUNAS(PEMBAYARAN)
 */

$html = '';

/* =========================
 * Helpers (aman dari redeclare)
 * ========================= */
if (!function_exists('fmt_rp')) {
  function fmt_rp($n){
    $n = (int)($n ?? 0);
    return 'Rp ' . number_format($n, 0, ',', '.');
  }
}

if (!function_exists('badge_simple')) {
  function badge_simple($text, $class){
    return '<span class="badge '.$class.' flat">'.htmlspecialchars($text, ENT_QUOTES, 'UTF-8').'</span>';
  }
}

/* =========================
 * STATUS PROSES (baru/desain/cetak/selesai/diambil/dikirim)
 * ========================= */
if (!function_exists('render_progress_badge_from_code')) {
  function render_progress_badge_from_code($code)
  {
    $meta = job_status_meta((int)$code);
    return '<span class="badge flat" style="background-color:'.htmlspecialchars($meta['color'], ENT_QUOTES, 'UTF-8').';color:#fff">'.htmlspecialchars($meta['label'], ENT_QUOTES, 'UTF-8').'</span>';
  }
}

if (!function_exists('get_invoice_progress_badge')) {
  function get_invoice_progress_badge($id_invoice)
  {
    $progress_badge = badge_simple('-', 'badge-secondary');

    $detail_list = detail_pekerjaan($id_invoice);
    if (!empty($detail_list) && is_array($detail_list)) {
	  $statusCodes = [];
      foreach ($detail_list as $d) {
		if (isset($d->status)) $statusCodes[] = (int)$d->status;
      }
	  if ($statusCodes) $progress_badge = render_progress_badge_from_code(job_status_slowest($statusCodes));
    }

    return $progress_badge;
  }
}

/* =========================
 * STATUS PEMBAYARAN (LUNAS/PIUTANG/PENDING/BATAL)
 * ========================= */
if (!function_exists('badge_pembayaran')) {
  function badge_pembayaran($row, $total, $bayar, $piutang)
  {
    $st = isset($row['status']) ? strtolower(trim($row['status'])) : '';
    if ($st === 'batal' || $st === 'batal_order') {
      return badge_simple('BATAL', 'badge-danger');
    }

    // pending = belum bayar sama sekali (bayar 0) tapi ada tagihan
    if ((int)$total > 0 && (int)$bayar <= 0) {
      return badge_simple('PENDING', 'badge-secondary');
    }

    // piutang = sudah ada bayar tapi masih sisa
    if ((int)$piutang > 0) {
      return badge_simple('PIUTANG', 'badge-warning');
    }

    // lunas = tidak ada sisa
    if ((int)$total > 0 && (int)$piutang <= 0) {
      return badge_simple('LUNAS', 'badge-success');
    }

    // fallback
    return badge_simple('PENDING', 'badge-secondary');
  }
}

/* =========================
 * Render rows
 * ========================= */
if (!empty($invoice) && is_array($invoice)) {

  foreach ($invoice as $row) {

    $id_invoice = isset($row['id_invoice']) ? (int)$row['id_invoice'] : 0;

    // ORDER ID
    $order_id_display = !empty($row['id_transaksi']) ? '#'.$row['id_transaksi'] : '#-';

    // PELANGGAN
    $pelanggan_nama = 'Umum';
    if (isset($row['id_konsumen']) && (int)$row['id_konsumen'] > 0) {
      $kons = cekKonsumen($row['id_konsumen']);
      if (is_array($kons) && !empty($kons['nama'])) {
        $pelanggan_nama = $kons['nama'];
      }
    }

    // view mode modal (biar modal detail tetap jalan)
    $oto = isset($row['oto']) ? (int)$row['oto'] : 2;
    if ($oto === 0 || $oto === 1 || $oto === 3) $view = 'edit';
    elseif ($oto === 5) $view = 'batal';
    else $view = 'view';

    /**
     * TOTAL/BAYAR/PIUTANG
     * Samakan dengan ajax-order.php:
     *   total  = sumOrder(id_invoice)  (fallback total_bayar)
     *   bayar  = sumPiutang(id_invoice)[0]['piutang'] + pajak (jika ada)
     *   piutang = total - bayar - diskon
     */
    // TOTAL
    if (function_exists('sumOrder')) {
      $total = (int) sumOrder($id_invoice);
    } else {
      $total = isset($row['total_bayar']) ? (int)$row['total_bayar'] : 0;
    }

    // DISKON
    $diskon = isset($row['potongan_harga']) ? (int)$row['potongan_harga'] : 0;

    // BAYAR (mengikuti ajax-order.php)
    $bayar = 0;
    if (function_exists('sumPiutang')) {
      $sumPiutang = sumPiutang($id_invoice);
      if (is_array($sumPiutang) && isset($sumPiutang[0]['piutang'])) {
        $bayar = (int)$sumPiutang[0]['piutang'];
      }
    } else {
      $bayar = isset($row['jumlah_bayar']) ? (int)$row['jumlah_bayar'] : 0;
    }

    // PAJAK (ajax-order menambahkan pajak ke bayar)
    $pajakPercent = isset($row['pajak']) ? (int)$row['pajak'] : 0;
    if ($pajakPercent > 0) {
      $pajak = (int) round(($total * $pajakPercent) / 100);
      $bayar += $pajak;
    }

    // PIUTANG (sisa)
    $piutang = $total - $bayar - $diskon;
    if ($piutang < 0) $piutang = 0;

    $total_rp   = fmt_rp($total);
    $bayar_rp   = fmt_rp($bayar);
    $piutang_rp = fmt_rp($piutang);

    // STATUS PROSES (sesuai ajax-operator)
    $status_proses_badge = get_invoice_progress_badge($id_invoice);

    // STATUS PEMBAYARAN (sesuai ajax-order)
    $lunas_badge = badge_pembayaran($row, $total, $bayar, $piutang);

    // RENDER
    $html .= '<tr>
      <td>
        <a href="#" class="cek_transaksi"
           data-toggle="modal"
           data-id="'.htmlspecialchars($id_invoice, ENT_QUOTES, 'UTF-8').'"
           data-modEdit="'.htmlspecialchars($view, ENT_QUOTES, 'UTF-8').'"
           id="cart">
          <span class="badge badge-info flat"
                data-toggle="tooltip"
                title="Detail Transaksi">'.htmlspecialchars($order_id_display, ENT_QUOTES, 'UTF-8').'</span>
        </a>
      </td>

      <td>'.htmlspecialchars($pelanggan_nama, ENT_QUOTES, 'UTF-8').'</td>

      <td class="text-right" title="'.$total_rp.'">'.$total_rp.'</td>
      <td class="text-right" title="'.$bayar_rp.'">'.$bayar_rp.'</td>
      <td class="text-right" title="'.$piutang_rp.'">'.$piutang_rp.'</td>

      <td>'.$status_proses_badge.'</td>
      <td class="text-right">'.$lunas_badge.'</td>
    </tr>';
  }

} else {

  $html .= '<tr>
    <td colspan="7" class="text-center text-muted" style="font-size:.8rem;padding:.75rem;">
      Belum ada invoice.
    </td>
  </tr>';
}

echo $html;
