<?php
require 'db_config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? 0;

    if ($id > 0) {
        try {
            // First, get the image path so we can delete the file
            $stmt_select = $pdo->prepare("SELECT image_path FROM products WHERE id = ?");
            $stmt_select->execute([$id]);
            $product = $stmt_select->fetch(PDO::FETCH_ASSOC);

            // Delete the database record
            $stmt_delete = $pdo->prepare("DELETE FROM products WHERE id = ?");
            $stmt_delete->execute([$id]);

            // If the database delete was successful, delete the file
            if ($stmt_delete->rowCount() > 0 && $product && !empty($product['image_path']) && file_exists($product['image_path'])) {
                unlink($product['image_path']);
            }

            echo json_encode(['status' => 'success', 'message' => 'Product deleted.']);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Valid ID is required.']);
    }
}
?>