<?php
/**
 * POST /api/products/delete.php
 * Body (JSON): { id }
 * Permanently deletes the listing (and its images, via FK cascade + disk cleanup).
 * Only the owner may delete it. To temporarily hide a listing instead, use
 * update.php with status=inactive.
 */

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();
$id = (int) ($input['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 delete your own listings.', 403);
}

// Grab image paths before the FK cascade removes the DB rows
$stmt = $pdo->prepare('SELECT image_path FROM product_images WHERE product_id = ?');
$stmt->execute([$id]);
$images = $stmt->fetchAll();

$stmt = $pdo->prepare('DELETE FROM products WHERE id = ?');
$stmt->execute([$id]);

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

send_json(true, 'Listing deleted.');
