<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode([]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode([]); exit; }

$conn->query("CREATE TABLE IF NOT EXISTS ai_study_materials (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    subject_id      INT NOT NULL,
    class_name      VARCHAR(100) NOT NULL,
    original_filename VARCHAR(255) NOT NULL,
    stored_filename VARCHAR(255) NOT NULL,
    file_type       VARCHAR(20) NOT NULL DEFAULT 'pdf',
    file_size       INT NOT NULL DEFAULT 0,
    extracted_content LONGTEXT DEFAULT NULL,
    extraction_status VARCHAR(20) NOT NULL DEFAULT 'processing',
    word_count      INT NOT NULL DEFAULT 0,
    uploaded_by     INT NOT NULL,
    uploaded_at     TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$stmt = $conn->prepare(
    "SELECT asm.*, s.subject_name
     FROM ai_study_materials asm
     LEFT JOIN subjects s ON s.id = asm.subject_id
     WHERE asm.uploaded_by = ?
     ORDER BY asm.uploaded_at DESC"
);
$stmt->bind_param('i', $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($row = $result->fetch_assoc()) { $rows[] = $row; }
$stmt->close();
echo json_encode($rows);
