<?php
require_once 'conexion2.php';
session_start(); // Para acceder a $_SESSION['id_usuario'] si existe

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $invoice_id = $_POST['invoice_id'];
  $nuevo_cliente_id = $_POST['nuevo_cliente'];
  $user_id = $_SESSION['id_usuario'] ?? 1; // Reemplaza con el sistema de autenticación real

  try {
    $pdo->beginTransaction();

    // Verifica existencia de factura
    $stmt = $pdo->prepare("SELECT customer_id, store_id FROM selling_info WHERE invoice_id = ?");
    $stmt->execute([$invoice_id]);
    $factura = $stmt->fetch();

    if (!$factura) {
      throw new Exception("Factura no encontrada.");
    }

    $cliente_original_id = $factura['customer_id'];
    $store_id = $factura['store_id'];

    // Actualizar cliente de la factura
    $stmt = $pdo->prepare("UPDATE selling_info SET customer_id = ? WHERE invoice_id = ?");
    $stmt->execute([$nuevo_cliente_id, $invoice_id]);

    // Obtener deuda de la factura
    $stmt = $pdo->prepare("SELECT due FROM selling_price WHERE invoice_id = ?");
    $stmt->execute([$invoice_id]);
    $precios = $stmt->fetch();
    $monto_due = $precios['due'] ?? 0;

    // Recalcular deudas
    $stmt = $pdo->prepare("UPDATE customer_to_store SET due = due - ? WHERE customer_id = ?");
    $stmt->execute([$monto_due, $cliente_original_id]);

    $stmt = $pdo->prepare("UPDATE customer_to_store SET due = due + ? WHERE customer_id = ?");
    $stmt->execute([$monto_due, $nuevo_cliente_id]);

    // Registrar log
    $descripcion = "Transferencia de factura $invoice_id del cliente $cliente_original_id al cliente $nuevo_cliente_id";
    $stmt = $pdo->prepare("INSERT INTO sell_logs (customer_id, ref_invoice_id, type, description, amount, store_id, created_by, created_at) 
                          VALUES (?, ?, 'transfer', ?, ?, ?, ?, NOW())");
    $stmt->execute([
      $nuevo_cliente_id,
      $invoice_id,
      $descripcion,
      $monto_due,
      $store_id,
      $user_id
    ]);

    $pdo->commit();
    mostrar_alerta("La factura fue transferida correctamente.", 'success');

  } catch (Exception $e) {
    $pdo->rollBack();
    mostrar_alerta("Error: " . $e->getMessage(), 'danger');
  }
}

function mostrar_alerta($mensaje, $tipo) {
  echo "
  <!DOCTYPE html>
  <html lang='es'>
  <head>
    <meta charset='UTF-8'>
    <title>Resultado</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css' rel='stylesheet'>
  </head>
  <body class='bg-light'>
    <div class='container py-5'>
      <div class='alert alert-$tipo text-center'>
        $mensaje
      </div>
      <div class='text-center'>
        <a href='transfer_factura.php' class='btn btn-primary'>Volver</a>
      </div>
    </div>
  </body>
  </html>";
}
