<?php
/**
 * Export API - Phase 7
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
$userId = getCurrentUserId();

switch ($method) {
    case 'GET':
        // Get export history
        $db = getDB();
        $stmt = $db->prepare("
            SELECT * FROM export_logs
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT 10
        ");
        $stmt->execute([$userId]);
        $exports = $stmt->fetchAll();

        echo json_encode([
            'success' => true,
            'exports' => $exports
        ]);
        break;

    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        $type = $data['type'] ?? '';
        $format = $data['format'] ?? 'pdf';
        $filters = $data['filters'] ?? [];

        if (!in_array($type, ['studies', 'publications', 'users', 'comments'])) {
            echo json_encode(['success' => false, 'error' => 'Invalid export type']);
            exit;
        }

        if (!in_array($format, ['pdf', 'excel', 'csv'])) {
            echo json_encode(['success' => false, 'error' => 'Invalid export format']);
            exit;
        }

        try {
            $db = getDB();

            // Generate export based on type
            $exportData = [];
            $filename = '';

            switch ($type) {
                case 'studies':
                    $stmt = $db->prepare("
                        SELECT s.id, s.title, s.type, s.status, s.summary,
                               u.first_name, u.last_name, i.name as institution,
                               c.name as category, s.created_at
                        FROM studies s
                        JOIN users u ON s.creator_id = u.id
                        LEFT JOIN institutions i ON s.institution_id = i.id
                        LEFT JOIN categories c ON s.category_id = c.id
                        WHERE s.is_public = 1 AND s.approval_status = 'approved'
                        ORDER BY s.created_at DESC
                    ");
                    $stmt->execute();
                    $exportData = $stmt->fetchAll();
                    $filename = 'studies_export_' . date('Y-m-d');
                    break;

                case 'publications':
                    $stmt = $db->prepare("
                        SELECT p.*, u.first_name, u.last_name
                        FROM publications p
                        JOIN users u ON p.submitter_id = u.id
                        WHERE p.status = 'published'
                        ORDER BY p.created_at DESC
                    ");
                    $stmt->execute();
                    $exportData = $stmt->fetchAll();
                    $filename = 'publications_export_' . date('Y-m-d');
                    break;

                case 'users':
                    if (!isAdmin()) {
                        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
                        exit;
                    }
                    $stmt = $db->prepare("
                        SELECT id, first_name, last_name, email, role, institution,
                               created_at, last_login
                        FROM users
                        ORDER BY created_at DESC
                    ");
                    $stmt->execute();
                    $exportData = $stmt->fetchAll();
                    $filename = 'users_export_' . date('Y-m-d');
                    break;

                case 'comments':
                    $stmt = $db->prepare("
                        SELECT sc.*, s.title as study_title, u.first_name, u.last_name
                        FROM study_comments sc
                        JOIN studies s ON sc.study_id = s.id
                        JOIN users u ON sc.user_id = u.id
                        WHERE sc.status = 'approved'
                        ORDER BY sc.created_at DESC
                    ");
                    $stmt->execute();
                    $exportData = $stmt->fetchAll();
                    $filename = 'comments_export_' . date('Y-m-d');
                    break;
            }

            // Generate file based on format
            $filePath = generateExportFile($exportData, $format, $filename);

            // Log the export
            $stmt = $db->prepare("
                INSERT INTO export_logs (user_id, export_type, format, filters, record_count, file_path)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $userId,
                $type,
                $format,
                json_encode($filters),
                count($exportData),
                $filePath
            ]);

            echo json_encode([
                'success' => true,
                'file_path' => $filePath,
                'filename' => $filename . '.' . $format,
                'record_count' => count($exportData)
            ]);

        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => 'Export failed: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        break;
}

function generateExportFile($data, $format, $filename) {
    $uploadDir = '../assets/uploads/exports/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $filePath = $uploadDir . $filename . '.' . $format;

    switch ($format) {
        case 'csv':
            generateCSV($data, $filePath);
            break;
        case 'excel':
            generateExcel($data, $filePath);
            break;
        case 'pdf':
            generatePDF($data, $filePath);
            break;
    }

    return str_replace('../', '', $filePath);
}

function generateCSV($data, $filePath) {
    if (empty($data)) return;

    $fp = fopen($filePath, 'w');

    // Write headers
    fputcsv($fp, array_keys($data[0]));

    // Write data
    foreach ($data as $row) {
        fputcsv($fp, $row);
    }

    fclose($fp);
}

function generateExcel($data, $filePath) {
    // For simplicity, generate CSV with .xlsx extension
    // In production, you'd use a library like PhpSpreadsheet
    generateCSV($data, str_replace('.xlsx', '.csv', $filePath));
    rename(str_replace('.xlsx', '.csv', $filePath), $filePath);
}

function generatePDF($data, $filePath) {
    // For simplicity, generate basic HTML that can be converted to PDF
    // In production, you'd use a library like TCPDF or Dompdf
    $html = '<html><body><table border="1">';

    if (!empty($data)) {
        // Headers
        $html .= '<tr>';
        foreach (array_keys($data[0]) as $header) {
            $html .= '<th>' . htmlspecialchars($header) . '</th>';
        }
        $html .= '</tr>';

        // Data
        foreach ($data as $row) {
            $html .= '<tr>';
            foreach ($row as $cell) {
                $html .= '<td>' . htmlspecialchars($cell) . '</td>';
            }
            $html .= '</tr>';
        }
    }

    $html .= '</table></body></html>';

    file_put_contents($filePath, $html);
}
?>
