<?php
/**
 * POST /api/products/create.php
 * multipart/form-data fields:
 *   name, category_id, description, quantity, original_price, selling_price,
 *   expiry_date (YYYY-MM-DD), location, barcode (optional)
 *   images[] (up to 5 files)
 */

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

only_post_allowed();
$userId = require_login();

$missing = validate_required($_POST, ['name', 'quantity', 'selling_price']);
if ($missing) {
    send_error('Missing required fields.', 422, $missing);
}

$name         = trim($_POST['name']);
$categoryId   = !empty($_POST['category_id']) ? (int) $_POST['category_id'] : null;
$description  = trim($_POST['description'] ?? '');
$quantity     = max(1, (int) $_POST['quantity']);
$originalPrice = !empty($_POST['original_price']) ? (float) $_POST['original_price'] : null;
$sellingPrice = (float) $_POST['selling_price'];
$expiryDate   = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;
$location     = trim($_POST['location'] ?? '');
$city         = trim($_POST['city'] ?? '');
$country      = trim($_POST['country'] ?? '');
$barcode      = trim($_POST['barcode'] ?? '');

if ($sellingPrice <= 0) {
    send_error('Selling price must be greater than 0.', 422);
}

if ($expiryDate && !DateTime::createFromFormat('Y-m-d', $expiryDate)) {
    send_error('Expiry date must be in YYYY-MM-DD format.', 422);
}

$pdo = Database::connect();

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare(
        'INSERT INTO products
         (owner_id, category_id, barcode, name, description, quantity, original_price, selling_price, expiry_date, location, city, country, status)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active")'
    );
    $stmt->execute([
        $userId, $categoryId, $barcode ?: null, $name, $description,
        $quantity, $originalPrice, $sellingPrice, $expiryDate, $location ?: null, $city ?: null, $country ?: null,
    ]);
    $productId = (int) $pdo->lastInsertId();

    // Handle images: $_FILES['images'] as an array upload
    $savedImages = [];
    if (!empty($_FILES['images']) && is_array($_FILES['images']['name'])) {
        $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([$productId, $result['path'], $i]);
                $savedImages[] = UPLOAD_URL . $result['path'];
            }
            // Silently skip individual bad files rather than failing the whole listing;
            // the product itself is still valid without every photo.
        }
    }

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

// Award points outside the listing transaction — a points-logging hiccup
// shouldn't roll back an otherwise-successful listing.
try {
    $pdoForPoints = Database::connect();
    award_loyalty_points($pdoForPoints, $userId, points_per_new_listing($pdoForPoints), 'Published a new listing');
} catch (Throwable $e) {
    // Non-critical - the listing itself already succeeded.
}

send_json(true, 'Listing published.', [
    'product' => ['id' => $productId, 'images' => $savedImages],
], 201);
