<?php
declare(strict_types=1);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Method not allowed.');window.location.href='my-products.php';</script></body></html>";
    exit;
}

$id = (int)($_POST['id'] ?? 0);
$redirect = trim($_POST['redirect'] ?? '');
if ($id <= 0) {
    http_response_code(400);
    $to = $redirect !== '' ? $redirect : 'my-products.php';
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid product id.');window.location.href='{$to}';</script></body></html>";
    exit;
}

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    $to = $redirect !== '' ? $redirect : 'my-products.php';
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='{$to}';</script></body></html>";
    exit;
}

$product = null;
try {
    $st = $pdo->prepare('SELECT image1,image2,image3,image4,image5 FROM products WHERE id=:id');
    $st->execute([':id'=>$id]);
    $product = $st->fetch();
} catch (Throwable $e) {}

if ($product) {
    for ($i=1;$i<=5;$i++) {
        $k = 'image'.$i;
        if (!empty($product[$k])) {
            $path = __DIR__.DIRECTORY_SEPARATOR.$product[$k];
            if (is_file($path)) @unlink($path);
        }
    }
}

try {
    $del = $pdo->prepare('DELETE FROM products WHERE id=:id');
    $del->execute([':id'=>$id]);
} catch (Throwable $e) {
    http_response_code(500);
    $to = $redirect !== '' ? $redirect : 'my-products.php';
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Failed to delete product.');window.location.href='{$to}';</script></body></html>";
    exit;
}

$to = $redirect !== '' ? $redirect : 'my-products.php';
echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Product deleted');window.location.href='{$to}';</script></body></html>";
?>
