<?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();
}

try {
    // 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 statistics
    $stats = [];
    
    // Total documents
    $stmt = $pdo->query("SELECT COUNT(*) FROM documents");
    $stats['total'] = $stmt->fetchColumn();
    
    // Public documents
    $stmt = $pdo->query("SELECT COUNT(*) FROM documents WHERE is_public = 1");
    $stats['public'] = $stmt->fetchColumn();
    
    // Private documents
    $stats['private'] = $stats['total'] - $stats['public'];
    
    // Total downloads
    $stmt = $pdo->query("SELECT COALESCE(SUM(download_count), 0) FROM documents");
    $stats['downloads'] = $stmt->fetchColumn();
    
    // Storage used (in bytes)
    $stmt = $pdo->query("SELECT COALESCE(SUM(file_size), 0) FROM documents");
    $stats['storage'] = $stmt->fetchColumn();
    
    // Recent uploads (last 7 days)
    $stmt = $pdo->query("SELECT COUNT(*) FROM documents WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
    $stats['recent'] = $stmt->fetchColumn();
    
    // Top categories
    $stmt = $pdo->query("SELECT category, COUNT(*) as count FROM documents GROUP BY category ORDER BY count DESC LIMIT 5");
    $stats['top_categories'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'stats' => $stats
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
