<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions. Not Authorized.']);
    exit;
}

try {
    $doc_id = $_POST['id'] ?? null;
    if (!$doc_id) {
        throw new Exception('Document ID is required');
    }

    // Get document info
    $sql = "SELECT file_path FROM client_documents WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $doc_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $doc = $result->fetch_assoc();

    if (!$doc) {
        throw new Exception('Document not found');
    }

    // Delete file from filesystem
    if (file_exists($doc['file_path'])) {
        unlink($doc['file_path']);
    }

    // Delete record from database
    $sql = "DELETE FROM client_documents WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $doc_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to delete document');
    }

    echo json_encode(['success' => true, 'message' => 'Document deleted successfully']);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

$conn->close();
?>