<?php
/**
 * POST /api/pantry/add_from_order.php
 * Body (JSON): { order_id }
 * Convenience action offered on the order confirmation screen: pulls every
 * line item from the buyer's own completed order into their pantry in one go,
 * so they don't have to re-type what they just bought.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$orderId = (int) ($input['order_id'] ?? 0);
if ($orderId <= 0) {
    send_error('A valid order_id is required.', 422);
}

$pdo = Database::connect();

$stmt = $pdo->prepare('SELECT buyer_id FROM orders WHERE id = ?');
$stmt->execute([$orderId]);
$order = $stmt->fetch();

if (!$order) {
    send_error('Order not found.', 404);
}
if ((int) $order['buyer_id'] !== $userId) {
    send_error('You can only do this for your own orders.', 403);
}

$stmt = $pdo->prepare('
    SELECT oi.product_id, oi.quantity, p.name, p.expiry_date
    FROM order_items oi
    JOIN products p ON p.id = oi.product_id
    WHERE oi.order_id = ?
');
$stmt->execute([$orderId]);
$lines = $stmt->fetchAll();

$pdo->beginTransaction();
try {
    $stmt = $pdo->prepare(
        'INSERT INTO pantry_items (user_id, source_product_id, product_name, quantity, expiry_date) VALUES (?, ?, ?, ?, ?)'
    );
    foreach ($lines as $line) {
        $stmt->execute([$userId, $line['product_id'], $line['name'], $line['quantity'], $line['expiry_date']]);
    }
    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    send_error('Could not add these items to your pantry.', 500, APP_ENV === 'local' ? [$e->getMessage()] : []);
}

send_json(true, 'Added ' . count($lines) . ' item(s) to your pantry.');
