<?php
/**
 * POST /api/products/update.php
 * multipart/form-data fields (all optional except id - only send what changed):
 *   id (required), name, category_id, description, quantity, original_price,
 *   selling_price, expiry_date, location, status (active|inactive|sold),
 *   images[] (new files to add), remove_image_ids[] (existing image ids to delete)
 *
 * Only the product's owner may update it.
 */

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

only_post_allowed();
$userId = require_login();

$id = (int) ($_POST['id'] ?? 0);
if ($id <= 0) {
    send_error('A valid product id is required.', 422);
}

$pdo = Database::connect();

$stmt = $pdo->prepare('SELECT owner_id FROM products WHERE id = ?');
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    send_error('Product not found.', 404);
}
if ((int) $product['owner_id'] !== $userId) {
    send_error('You can only edit your own listings.', 403);
}

// Build a dynamic UPDATE from whichever fields were sent.
$fieldMap = [
    'name'           => 'name',
    'category_id'    => 'category_id',
    'description'    => 'description',
    'quantity'       => 'quantity',
    'original_price' => 'original_price',
    'selling_price'  => 'selling_price',
    'expiry_date'    => 'expiry_date',
    'location'       => 'location',
    'city'           => 'city',
    'country'        => 'country',
    'status'         => 'status',
];

$set = [];
$params = [];

foreach ($fieldMap as $postKey => $column) {
    if (!array_key_exists($postKey, $_POST)) {
        continue;
    }
    $value = trim((string) $_POST[$postKey]);

    if ($postKey === 'status' && !in_array($value, ['active', 'inactive', 'sold'], true)) {
        send_error('Invalid status value.', 422);
    }
    if ($postKey === 'selling_price' && (float) $value <= 0) {
        send_error('Selling price must be greater than 0.', 422);
    }
    if ($postKey === 'expiry_date' && $value !== '' && !DateTime::createFromFormat('Y-m-d', $value)) {
        send_error('Expiry date must be in YYYY-MM-DD format.', 422);
    }

    $set[] = "$column = ?";
    $params[] = $value === '' && in_array($postKey, ['category_id', 'expiry_date', 'original_price'], true)
        ? null
        : $value;
}

$pdo->beginTransaction();

try {
    if ($set) {
        $params[] = $id;
        $sql = 'UPDATE products SET ' . implode(', ', $set) . ' WHERE id = ?';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
    }

    // Remove selected existing images
    if (!empty($_POST['remove_image_ids']) && is_array($_POST['remove_image_ids'])) {
        $ids = array_map('intval', $_POST['remove_image_ids']);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));

        // Fetch paths first so we can delete the files from disk
        $stmt = $pdo->prepare("SELECT id, image_path FROM product_images WHERE product_id = ? AND id IN ($placeholders)");
        $stmt->execute(array_merge([$id], $ids));
        $toDelete = $stmt->fetchAll();

        $stmt = $pdo->prepare("DELETE FROM product_images WHERE product_id = ? AND id IN ($placeholders)");
        $stmt->execute(array_merge([$id], $ids));

        foreach ($toDelete as $img) {
            $fullPath = rtrim(UPLOAD_DIR, '/') . '/' . $img['image_path'];
            if (is_file($fullPath)) {
                @unlink($fullPath);
            }
        }
    }

    // Add new images
    if (!empty($_FILES['images']) && is_array($_FILES['images']['name'])) {
        $stmt = $pdo->prepare('SELECT COALESCE(MAX(sort_order), -1) FROM product_images WHERE product_id = ?');
        $stmt->execute([$id]);
        $nextOrder = (int) $stmt->fetchColumn() + 1;

        $count = count($_FILES['images']['name']);
        for ($i = 0; $i < min($count, 5); $i++) {
            if ($_FILES['images']['error'][$i] === UPLOAD_ERR_NO_FILE) {
                continue;
            }
            $file = [
                'name'     => $_FILES['images']['name'][$i],
                'type'     => $_FILES['images']['type'][$i],
                'tmp_name' => $_FILES['images']['tmp_name'][$i],
                'error'    => $_FILES['images']['error'][$i],
                'size'     => $_FILES['images']['size'][$i],
            ];
            $result = save_uploaded_image($file);
            if ($result['ok']) {
                $stmt = $pdo->prepare('INSERT INTO product_images (product_id, image_path, sort_order) VALUES (?, ?, ?)');
                $stmt->execute([$id, $result['path'], $nextOrder++]);
            }
        }
    }

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    send_error('Could not update the listing.', 500, APP_ENV === 'local' ? [$e->getMessage()] : []);
}

send_json(true, 'Listing updated.');
