<?php
// delete_document.php - Delete a document from user's document_path array
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$user_id = $_POST['user_id'] ?? '';
$document_index = $_POST['document_index'] ?? '';

if (empty($user_id)) {
    echo json_encode(['success' => false, 'message' => 'User ID required']);
    exit;
}

if ($document_index === '') {
    echo json_encode(['success' => false, 'message' => 'Document index required']);
    exit;
}

// Read the existing data
$jsonFilePath = '../data.json';
if (!file_exists($jsonFilePath)) {
    echo json_encode(['success' => false, 'message' => 'Data file not found']);
    exit;
}

$jsonContent = file_get_contents($jsonFilePath);
$data = json_decode($jsonContent, true);

if (!isset($data[$user_id])) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}

if (!isset($data[$user_id]['document_path']) || !is_array($data[$user_id]['document_path'])) {
    echo json_encode(['success' => false, 'message' => 'No documents found for this user']);
    exit;
}

$documents = $data[$user_id]['document_path'];
$document_index = (int)$document_index;

if (!isset($documents[$document_index])) {
    echo json_encode(['success' => false, 'message' => 'Document not found']);
    exit;
}

// Get the file path before removing from array
$documentToDelete = $documents[$document_index];
$filePath = '../' . $documentToDelete['path'];

// Remove the document from the array
array_splice($data[$user_id]['document_path'], $document_index, 1);

// Save updated data back to JSON file
if (file_put_contents($jsonFilePath, json_encode($data, JSON_PRETTY_PRINT))) {
    // Try to delete the physical file
    if (file_exists($filePath)) {
        unlink($filePath);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Document deleted successfully'
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update database']);
}
?>
