<?php



require_once __DIR__ . '/../../config.php';

// POST /admin/ordenes/confirm.php
// Body: { id, shippingCompany (optional), trackingNumber (optional) }

requireAdmin();

$data = body();

if (empty($data['id'])) {
    jsonErr(400, 'ID de orden requerido.');
}

$db = getDB();

// First, update transaction type
$stmt = $db->prepare('SELECT tipo FROM transacciones WHERE idtransacciones = ?');
$stmt->execute([$data['id']]);
$transaction = $stmt->fetch();

if (!$transaction) {
    jsonErr(404, 'Orden no encontrada.');
}

$newTipo = $transaction['tipo'] == 7 ? 10 : 11;

$stmt = $db->prepare('UPDATE transacciones SET tipo = ? WHERE idtransacciones = ?');
$stmt->execute([$newTipo, $data['id']]);

// Update depositos
$stmt = $db->prepare('UPDATE depositos SET status = "confirmado" WHERE transacciones_idtransacciones = ?');
$stmt->execute([$data['id']]);

// If shipping info provided, create guía record
if (!empty($data['trackingNumber'])) {
    $stmt = $db->prepare('
        INSERT INTO guias (idtransacciones, rastreo, fechg, statusenvio)
        VALUES (?, ?, NOW(), "en_transito")
    ');
    $stmt->execute([$data['id'], $data['trackingNumber']]);
}

jsonOk(['message' => 'Orden confirmada.']);
