<?php
session_start();
header('Content-Type: application/json');
require_once '../../config/config.php';

// Check if user is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

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

// Check if ID is provided
if (!isset($_POST['id']) || empty($_POST['id'])) {
    echo json_encode(['success' => false, 'message' => 'Document ID is required']);
    exit();
}

try {
    $documentId = (int)$_POST['id'];
    
    // Connect to database
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get document details
    $stmt = $pdo->prepare("SELECT * FROM documents WHERE id = :id");
    $stmt->execute(['id' => $documentId]);
    $document = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$document) {
        echo json_encode(['success' => false, 'message' => 'Document not found']);
        exit();
    }
    
    // Check if user has permission to delete this document
    // For now, allow all admins to delete documents
    // In a production environment, you might want to restrict this to the uploader or specific roles
    
    // Delete file from filesystem
    if (file_exists($document['file_path'])) {
        unlink($document['file_path']);
    }
    
    // Delete document record from database
    $deleteStmt = $pdo->prepare("DELETE FROM documents WHERE id = :id");
    $deleteStmt->execute(['id' => $documentId]);
    
    // Log deletion activity
    $logStmt = $pdo->prepare("
        INSERT INTO activity_logs (user_id, action, details, entity_type, entity_id)
        VALUES (:user_id, 'document_delete', :details, 'document', :entity_id)
    ");
    
    $logStmt->execute([
        'user_id' => $_SESSION['admin_id'],
        'details' => "Deleted document: " . $document['title'],
        'entity_id' => $documentId
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Document deleted successfully'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
