<?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_generation_jobs (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    material_id     INT NOT NULL,
    subject_id      INT NOT NULL,
    class_name      VARCHAR(100) NOT NULL,
    term            VARCHAR(50) DEFAULT NULL,
    academic_year   VARCHAR(20) DEFAULT NULL,
    difficulty      VARCHAR(20) DEFAULT 'medium',
    mcq_count       INT DEFAULT 0,
    theory_count    INT DEFAULT 0,
    fill_blank_count INT DEFAULT 0,
    diagram_count   INT DEFAULT 0,
    status          VARCHAR(20) DEFAULT 'processing',
    result_summary  TEXT DEFAULT NULL,
    engine_used     VARCHAR(50) DEFAULT NULL,
    error_message   TEXT DEFAULT NULL,
    created_by      INT NOT NULL,
    created_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at    TIMESTAMP NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$stmt = $conn->prepare(
    "SELECT agj.*, s.subject_name,
            TIMESTAMPDIFF(SECOND, agj.created_at, COALESCE(agj.completed_at, NOW())) AS duration_seconds
     FROM ai_generation_jobs agj
     LEFT JOIN subjects s ON s.id = agj.subject_id
     WHERE agj.created_by = ?
     ORDER BY agj.created_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);
