<?php
session_start();
include "../db.php";

// Set the correct response header
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the product ID from the request
    $pid = mysqli_real_escape_string($con, $_POST['pid']);
    
    // Check if the product exists and get the file name
    $query = "SELECT pFinalDocument FROM product WHERE pid = '$pid'";
    $result = mysqli_query($con, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $fileName = $row['pFinalDocument'];

        if (!empty($fileName)) {
            // Construct the file path
            $filePath = '../upload/finalDoc/' . $fileName;

            // Try to unlink (delete) the file
            if (file_exists($filePath)) {
                if (unlink($filePath)) {
                    // Update the database, set pFinalDocument to blank
                    $updateQuery = "UPDATE product SET pFinalDocument = '', pFinalUpDate = NOW() WHERE pid = '$pid'";
                    
                    if (mysqli_query($con, $updateQuery)) {
                        // Send success response
                        echo json_encode(['success' => true, 'message' => 'Document successfully removed.']);
                    } else {
                        // If database update fails
                        echo json_encode(['success' => false, 'message' => 'Failed to update database.']);
                    }
                } else {
                    // If file deletion fails
                    echo json_encode(['success' => false, 'message' => 'Failed to delete the document from the server.']);
                }
            } else {
                // If file does not exist
                echo json_encode(['success' => false, 'message' => 'File not found.']);
            }
        } else {
            // If no document exists in the database
            echo json_encode(['success' => false, 'message' => 'No document to remove.']);
        }
    } else {
        // If the product is not found
        echo json_encode(['success' => false, 'message' => 'Product not found.']);
    }
} else {
    // Invalid request method
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}

mysqli_close($con);
?>