<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../db_connection.php';

$response = [
    'success' => false,
    'message' => 'Error desconocido.'
];

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $productId = isset($_POST['productId']) ? (int)$_POST['productId'] : 0;
    $quantities = isset($_POST['quantities']) ? $_POST['quantities'] : [];
    $presentation = isset($_POST['presentation']) ? $_POST['presentation'] : null;
    $expirationDate = isset($_POST['expirationDate']) ? $_POST['expirationDate'] : null;

    if ($productId > 0) {
        try {
            $conn->begin_transaction();
            $updated_timestamp = null;

            // Update product's expiration date
            if ($expirationDate !== null) {
                $update_exp_stmt = $conn->prepare("UPDATE productos SET FechaVencimiento = ? WHERE id = ?");
                $update_exp_stmt->bind_param('si', $expirationDate, $productId);
                $update_exp_stmt->execute();
                $update_exp_stmt->close();
            }

            // Update quantities
            foreach ($quantities as $branchId => $quantity) {
                $branchId = (int)$branchId;
                $quantity = (int)$quantity;

                $check_stmt = $conn->prepare("SELECT id FROM inventario WHERE lote_id = ? AND sucursal_id = ?");
                $check_stmt->bind_param('ii', $productId, $branchId);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();

                if ($check_result->num_rows > 0) {
                    if ($quantity <= 0) {
                        // Delete record if quantity is 0 or less
                        $delete_stmt = $conn->prepare("DELETE FROM inventario WHERE lote_id = ? AND sucursal_id = ?");
                        $delete_stmt->bind_param('ii', $productId, $branchId);
                        $delete_stmt->execute();
                        $delete_stmt->close();
                    } else {
                        // Update existing record
                        $update_stmt = $conn->prepare("UPDATE inventario SET stock_unidad_base = ?, last_updated = NOW() WHERE lote_id = ? AND sucursal_id = ?");
                        $update_stmt->bind_param('iii', $quantity, $productId, $branchId);
                        $update_stmt->execute();
                        $update_stmt->close();
                    }
                } else if ($quantity > 0) {
                    // Insert new record only if quantity is greater than 0
                    $insert_stmt = $conn->prepare("INSERT INTO inventario (lote_id, sucursal_id, stock_unidad_base, last_updated) VALUES (?, ?, ?, NOW())");
                    $insert_stmt->bind_param('iii', $productId, $branchId, $quantity);
                    $insert_stmt->execute();
                    $insert_stmt->close();
                }
            }

            // Update presentation (assuming it updates for the first branch with an entry, or creates one if none exists)
            // This logic might need refinement based on whether presentation is per product or per branch.
            if ($presentation !== null) {
                // Find an existing inventory entry for this product to update its presentation
                $find_branch_stmt = $conn->prepare("SELECT sucursal_id FROM inventario WHERE lote_id = ? LIMIT 1");
                $find_branch_stmt->bind_param('i', $productId);
                $find_branch_stmt->execute();
                $find_branch_result = $find_branch_stmt->get_result();

                if ($find_branch_result->num_rows > 0) {
                    $row = $find_branch_result->fetch_assoc();
                    $targetBranchId = $row['sucursal_id'];
                    $update_pres_stmt = $conn->prepare("UPDATE inventario SET presentacion = ?, last_updated = NOW() WHERE lote_id = ? AND sucursal_id = ?");
                    $update_pres_stmt->bind_param('sii', $presentation, $productId, $targetBranchId);
                    $update_pres_stmt->execute();
                    $update_pres_stmt->close();
                } else {
                    // If no inventory entry exists, create one for the first branch in branchOrder
                    // This is a fallback and might not be desired behavior.
                    $defaultBranchId = 3; // Assuming branch 3 is a default or primary branch
                    $insert_pres_stmt = $conn->prepare("INSERT INTO inventario (lote_id, sucursal_id, presentacion, last_updated) VALUES (?, ?, ?, NOW())");
                    $insert_pres_stmt->bind_param('iis', $productId, $defaultBranchId, $presentation);
                    $insert_pres_stmt->execute();
                    $insert_pres_stmt->close();
                }
                $find_branch_stmt->close();
            }

            $conn->commit();
            $response['success'] = true;
            $response['message'] = 'Inventario actualizado con éxito.';
            
            // Get the updated timestamp to return to the frontend
            // This will be the latest timestamp from any updated entry for this product
            $get_timestamp_stmt = $conn->prepare("SELECT MAX(last_updated) as latest_update FROM inventario WHERE lote_id = ?");
            $get_timestamp_stmt->bind_param('i', $productId);
            $get_timestamp_stmt->execute();
            $updated_timestamp = $get_timestamp_stmt->get_result()->fetch_assoc()['latest_update'];
            $get_timestamp_stmt->close();
            $response['last_updated'] = $updated_timestamp;

        } catch (Exception $e) {
            $conn->rollback();
            $response['message'] = 'Error al actualizar el inventario: ' . $e->getMessage();
            error_log('Error en update_inventory.php: ' . $e->getMessage());
        }
    } else {
        $response['message'] = 'Datos incompletos para la actualización.';
    }
} else {
    $response['message'] = 'Método de solicitud no permitido.';
}

if (isset($conn) && $conn->ping()) {
    $conn->close();
}

echo json_encode($response);
?>