<?php
require_once '../config/database.php';

header('Content-Type: application/json');

try {
    $requestId = $_POST['id'] ?? null;
    
    if (!$requestId) {
        echo json_encode(['success' => false, 'message' => 'Request ID is required']);
        exit;
    }

    // Get the image path before deleting the request
    $stmt = $pdo->prepare("SELECT product_image_url FROM {$tables['product_requests']} WHERE id = ?");
    $stmt->execute([$requestId]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);

    // Delete from products_req table
    $stmt = $pdo->prepare("DELETE FROM {$tables['product_requests']} WHERE id = ?");
    $result = $stmt->execute([$requestId]);
    
    if ($result) {
        // If the request was deleted successfully and it had a local image, delete the image file
        if ($request && !empty($request['product_image_url']) && !str_starts_with($request['product_image_url'], 'http')) {
            $imagePath = '../' . $request['product_image_url'];
            if (file_exists($imagePath)) {
                unlink($imagePath);
            }
        }
        echo json_encode(['success' => true, 'message' => 'Product request deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to delete product request']);
    }
} catch(Exception $e) {
    error_log("Error in delete_product_request.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An error occurred while deleting the request']);
}
?> 