<?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 {
    // Get parameters
    $category = $_GET['category'] ?? '';
    $access = $_GET['access'] ?? '';
    $search = $_GET['search'] ?? '';
    $page = (int)($_GET['page'] ?? 1);
    $limit = 12; // Documents per page
    $offset = ($page - 1) * $limit;
    
    // 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);
    
    // Build query
    $where = "WHERE 1=1";
    $params = [];
    
    if (!empty($category)) {
        $where .= " AND category = :category";
        $params['category'] = $category;
    }
    
    if ($access !== '') {
        $where .= " AND is_public = :access";
        $params['access'] = $access;
    }
    
    if (!empty($search)) {
        $where .= " AND (title LIKE :search OR description LIKE :search)";
        $params['search'] = "%$search%";
    }
    
    // Get total count
    $countQuery = "SELECT COUNT(*) FROM documents $where";
    $countStmt = $pdo->prepare($countQuery);
    $countStmt->execute($params);
    $totalCount = $countStmt->fetchColumn();
    
    // Get documents
    $query = "SELECT d.*, 
                     CONCAT(a.first_name, ' ', a.last_name) as uploaded_by_name
              FROM documents d
              LEFT JOIN admins a ON d.uploaded_by = a.id
              $where
              ORDER BY d.created_at DESC 
              LIMIT :limit OFFSET :offset";
    
    $stmt = $pdo->prepare($query);
    
    // Bind parameters
    foreach ($params as $key => $value) {
        $stmt->bindValue(":$key", $value);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    
    $stmt->execute();
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Check if there are more documents
    $hasMore = ($offset + $limit) < $totalCount;
    
    echo json_encode([
        'success' => true,
        'documents' => $documents,
        'hasMore' => $hasMore,
        'total' => $totalCount,
        'page' => $page
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
