<?php
/**
 * Export Rubrics to CSV
 * Export all rubrics with their remedies to CSV file
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/rubric-tree.php';

requireAdmin();

$pdo = getDB();
$format = $_GET['format'] ?? 'csv';
$type = $_GET['type'] ?? 'full'; // full, rubrics_only, remedies_only

// Set filename
$filename = "rubrics_export_" . date('Y-m-d') . "." . $format;

if ($type == 'rubrics_only') {
    // Export only rubrics (no remedies)
    $stmt = $pdo->query("SELECT id, parent_id, chapter_name, rubric_name, full_path, level, sort_order 
                        FROM rubrics ORDER BY full_path");
    $rubrics = $stmt->fetchAll();
    
    if ($format == 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        fputcsv($output, ['ID', 'Parent ID', 'Chapter', 'Rubric Name', 'Full Path', 'Level', 'Sort Order']);
        
        foreach ($rubrics as $rubric) {
            fputcsv($output, [
                $rubric['id'],
                $rubric['parent_id'],
                $rubric['chapter_name'],
                $rubric['rubric_name'],
                $rubric['full_path'],
                $rubric['level'],
                $rubric['sort_order']
            ]);
        }
        fclose($output);
    }
    
} elseif ($type == 'remedies_only') {
    // Export remedies with their grades
    $stmt = $pdo->query("SELECT r.id, r.name, r.abbreviation, 
                        COUNT(rr.rubric_id) as rubric_count
                        FROM remedies r
                        LEFT JOIN rubric_remedy rr ON r.id = rr.remedy_id
                        GROUP BY r.id
                        ORDER BY r.name");
    $remedies = $stmt->fetchAll();
    
    if ($format == 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="remedies_export_' . date('Y-m-d') . '.csv"');
        
        $output = fopen('php://output', 'w');
        fputcsv($output, ['ID', 'Remedy Name', 'Abbreviation', 'Rubric Count']);
        
        foreach ($remedies as $remedy) {
            fputcsv($output, [
                $remedy['id'],
                $remedy['name'],
                $remedy['abbreviation'],
                $remedy['rubric_count']
            ]);
        }
        fclose($output);
    }
    
} else {
    // Full export: rubrics with their remedies (Kent's format)
    if ($format == 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        
        // Write headers
        fputcsv($output, ['chapter', 'level1', 'level2', 'level3', 'level4', 'remedies']);
        
        // Get all leaf rubrics (level >= 4) or rubrics with remedies
        $stmt = $pdo->query("SELECT r.*, 
                            GROUP_CONCAT(CONCAT(rm.name, '(', rr.grade, ')') ORDER BY rr.grade DESC SEPARATOR ', ') as remedies
                            FROM rubrics r
                            LEFT JOIN rubric_remedy rr ON r.id = rr.rubric_id
                            LEFT JOIN remedies rm ON rr.remedy_id = rm.id
                            WHERE EXISTS (SELECT 1 FROM rubric_remedy WHERE rubric_id = r.id)
                            GROUP BY r.id
                            ORDER BY r.full_path");
        $rubrics = $stmt->fetchAll();
        
        foreach ($rubrics as $rubric) {
            // Split full path into levels
            $pathParts = explode(' - ', $rubric['full_path']);
            $chapter = $pathParts[0] ?? '';
            $level1 = $pathParts[1] ?? '';
            $level2 = $pathParts[2] ?? '';
            $level3 = $pathParts[3] ?? '';
            $level4 = $pathParts[4] ?? '';
            
            fputcsv($output, [
                $chapter,
                $level1,
                $level2,
                $level3,
                $level4,
                $rubric['remedies']
            ]);
        }
        
        fclose($output);
    } elseif ($format == 'json') {
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="rubrics_export_' . date('Y-m-d') . '.json"');
        
        $tree = getRubricTreeArray();
        echo json_encode($tree, JSON_PRETTY_PRINT);
    }
}

exit;
?>