<?php
header('Content-Type: application/json');
require_once 'conexion2.php';

if (!isset($_POST['sup_id'], $_POST['monto_manual'], $_POST['facturas'])) {
    echo json_encode(['status' => 'error', 'message' => 'Datos incompletos.']);
    exit;
}

$sup_id = (int) $_POST['sup_id'];
$monto = (float) $_POST['monto_manual'];
$facturas = $_POST['facturas'];
$pdo = db();

try {
    $stmt = $pdo->prepare("SELECT pglobal_pesos FROM supplier_to_store WHERE sup_id = ?");
    $stmt->execute([$sup_id]);
    $saldoDisponible = (float) $stmt->fetchColumn();

    if ($monto <= 0 || $monto > $saldoDisponible) {
        echo json_encode(['status' => 'error', 'message' => 'Monto a imputar inválido.']);
        exit;
    }

    $inPlaceholders = implode(',', array_fill(0, count($facturas), '?'));
    $query = "
        SELECT invoice_id, due, paid_amount
        FROM purchase_price
        WHERE invoice_id IN ($inPlaceholders) AND due > 0
        ORDER BY due DESC
    ";
    $stmt = $pdo->prepare($query);
    $stmt->execute($facturas);
    $facturasData = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $pdo->beginTransaction();

    $restante = $monto;
    foreach ($facturasData as $factura) {
        if ($restante <= 0) break;

        $imputar = min($factura['due'], $restante);
        $nuevo_due = $factura['due'] - $imputar;
        $nuevo_paid = $factura['paid_amount'] + $imputar;

        $upd = $pdo->prepare("UPDATE purchase_price SET due = ?, paid_amount = ?, due_paid = due_paid + ? WHERE invoice_id = ?");
        $upd->execute([$nuevo_due, $nuevo_paid, $imputar, $factura['invoice_id']]);

        if ($nuevo_due == 0) {
            $updStatus = $pdo->prepare("UPDATE purchase_info SET payment_status = 'paid' WHERE invoice_id = ?");
            $updStatus->execute([$factura['invoice_id']]);
        }

        $ins = $pdo->prepare("
            INSERT INTO purchase_payments 
            (type, store_id, invoice_id, amount, total_paid, balance, created_by, created_at, tipo_pago, note)
            VALUES
            ('purchase', 1, ?, ?, ?, ?, ?, NOW(), 99, 'Imputación manual desde saldo global')
        ");
        $ins->execute([
            $factura['invoice_id'],
            $imputar,
            $nuevo_paid,
            $nuevo_due,
            1
        ]);

        $restante -= $imputar;
    }

    $nuevo_saldo = $saldoDisponible - $monto + $restante;
    $pdo->prepare("UPDATE supplier_to_store SET pglobal_pesos = ? WHERE sup_id = ?")->execute([$nuevo_saldo, $sup_id]);

    $pdo->commit();
    echo json_encode(['status' => 'success', 'message' => 'Imputación manual realizada.']);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['status' => 'error', 'message' => 'Error: ' . $e->getMessage()]);
}
?>