<?php
require_once 'conexion2.php';

header('Content-Type: application/json');
ini_set('display_errors', 1);
error_reporting(E_ALL);

if (isset($_POST['cliente_id'])) {
  $cliente_id = intval($_POST['cliente_id']);

  $respuesta = [
    'saldos' => ['balance' => '0.0000', 'due' => '0.0000'],
    'tabla' => '<p class="text-danger">No hay facturas registradas para este cliente.</p>'
  ];

  // Obtener saldos
  $stmt = $pdo->prepare("SELECT balance, due FROM customer_to_store WHERE customer_id = ?");
  $stmt->execute([$cliente_id]);
  $saldos = $stmt->fetch(PDO::FETCH_ASSOC);
  if ($saldos) {
    $respuesta['saldos'] = $saldos;
  }

  // Obtener facturas
  $stmt = $pdo->prepare("
    SELECT si.invoice_id, si.created_at, sp.subtotal, sp.others_charge, sp.payable_amount,
           sp.paid_amount, sp.due, sp.due_paid, sp.return_amount 
    FROM selling_info si 
    JOIN selling_price sp ON si.invoice_id = sp.invoice_id 
    WHERE si.customer_id = ? 
    ORDER BY si.created_at DESC");
  $stmt->execute([$cliente_id]);
  $facturas = $stmt->fetchAll(PDO::FETCH_ASSOC);

  if ($facturas) {
    // Inicializar totales
    $totales = [
      'subtotal' => 0,
      'others_charge' => 0,
      'payable_amount' => 0,
      'paid_amount' => 0,
      'due' => 0,
      'due_paid' => 0,
      'return_amount' => 0
    ];

    $tabla = '<div style="max-height: 300px; overflow-y: auto;">
      <table class="table table-bordered table-sm mt-3">
    <thead class="table-light">
  <tr>
    <th>Fecha</th>
    <th>Factura</th>
    <th>Subtotal</th>
    <th>Otros Cargos</th>
    <th>Total</th>
    <th>Pagado</th>
    <th>Deuda</th>
    <th>Pagado Deuda</th>
    <th>Devuelto</th>
    <th>Saldo</th>
  </tr>
</thead>

	  <tbody>';

    foreach ($facturas as $f) {
      $tabla .= "<tr>
        <td>{$f['created_at']}</td>
        <td>{$f['invoice_id']}</td>
        <td>{$f['subtotal']}</td>
        <td>{$f['others_charge']}</td>
        <td>{$f['payable_amount']}</td>
        <td>{$f['paid_amount']}</td>
        <td>{$f['due']}</td>
        <td>{$f['due_paid']}</td>
        <td>{$f['return_amount']}</td>
      </tr>";

      // Sumar totales
      $totales['subtotal'] += floatval($f['subtotal']);
      $totales['others_charge'] += floatval($f['others_charge']);
      $totales['payable_amount'] += floatval($f['payable_amount']);
      $totales['paid_amount'] += floatval($f['paid_amount']);
      $totales['due'] += floatval($f['due']);
      $totales['due_paid'] += floatval($f['due_paid']);
      $totales['return_amount'] += floatval($f['return_amount']);
    }

    // Fila de totales
   $saldo_final = $totales['payable_amount'] - $totales['paid_amount'] - $totales['return_amount'];

$tabla .= "<tr class='table-secondary fw-bold'>
  <td colspan='2'>Totales:</td>
  <td>" . number_format($totales['subtotal'], 4, '.', ',') . "</td>
  <td>" . number_format($totales['others_charge'], 4, '.', ',') . "</td>
  <td>" . number_format($totales['payable_amount'], 4, '.', ',') . "</td>
  <td>" . number_format($totales['paid_amount'], 4, '.', ',') . "</td>
  <td>" . number_format($totales['due'], 4, '.', ',') . "</td>
  <td>" . number_format($totales['due_paid'], 4, '.', ',') . "</td>
  <td>" . number_format($totales['return_amount'], 4, '.', ',') . "</td>
  <td>" . number_format($saldo_final, 4, '.', ',') . "</td>
</tr>";


    $tabla .= '</tbody></table></div>';
    $respuesta['tabla'] = $tabla;
  }

  echo json_encode($respuesta);
  exit;
}
