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

if (!isset($_POST['sup_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Proveedor no especificado']);
    exit;
}

$sup_id = (int) $_POST['sup_id'];
$pdo = db();

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

    if ($pglobal <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Saldo imputable agotado.']);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT pi.invoice_id, pp.due, pp.paid_amount 
        FROM purchase_info pi
        JOIN purchase_price pp ON pi.invoice_id = pp.invoice_id
        WHERE pi.sup_id = ? AND pp.due > 0
        ORDER BY pi.purchase_date ASC
    ");
    $stmt->execute([$sup_id]);
    $facturas = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($facturas)) {
        echo json_encode(['status' => 'error', 'message' => 'No hay facturas con saldo pendiente.']);
        exit;
    }

    $pdo->beginTransaction();
    foreach ($facturas as $factura) {
        $imputar = min((float)$factura['due'], $pglobal);
        if ($imputar <= 0) break;

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

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

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

        $insert_pago = $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 automática desde saldo global')
        ");
        $insert_pago->execute([
            $factura['invoice_id'],
            $imputar,
            $nuevo_paid,
            $nuevo_due,
            1
        ]);

        $pglobal -= $imputar;
    }

    $stmt = $pdo->prepare("UPDATE supplier_to_store SET pglobal_pesos = ? WHERE sup_id = ?");
    $stmt->execute([$pglobal, $sup_id]);
    $pdo->commit();

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