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

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

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Export Data';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Handle export request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();

    $exportType = $_POST['export_type'] ?? '';
    $format = $_POST['format'] ?? 'excel';
    $filters = $_POST['filters'] ?? [];

    if (empty($exportType)) {
        $error = 'Please select an export type.';
    } else {
        try {
            // Log the export request
            $db = getDB();
            $stmt = $db->prepare("
                INSERT INTO export_logs (user_id, export_type, format, filters)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$userId, $exportType, $format, json_encode($filters)]);

            // Generate filename
            $timestamp = date('Y-m-d_H-i-s');
            $filename = "export_{$exportType}_{$timestamp}";

            // Set headers based on format
            if ($format === 'excel') {
                header('Content-Type: application/vnd.ms-excel');
                header("Content-Disposition: attachment; filename=\"{$filename}.xls\"");
            } elseif ($format === 'csv') {
                header('Content-Type: text/csv');
                header("Content-Disposition: attachment; filename=\"{$filename}.csv\"");
            } elseif ($format === 'pdf') {
                header('Content-Type: application/pdf');
                header("Content-Disposition: attachment; filename=\"{$filename}.pdf\"");
            }

            // Generate and output data based on type
            switch ($exportType) {
                case 'studies':
                    exportStudies($format, $filters);
                    break;
                case 'publications':
                    exportPublications($format, $filters);
                    break;
                case 'collaborators':
                    exportCollaborators($format, $filters);
                    break;
                case 'comments':
                    exportComments($format, $filters);
                    break;
                default:
                    throw new Exception('Invalid export type.');
            }

            exit; // Stop execution after export

        } catch (Exception $e) {
            $error = 'Export failed: ' . $e->getMessage();
        }
    }
}

// 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]);
$exportHistory = $stmt->fetchAll();

include '../templates/researcher-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2"><i class="fas fa-download"></i> Export Data</h1>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Export Form -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-file-export"></i> Export Data</h5>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <?php echo csrfField(); ?>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="exportType" class="form-label">Export Type</label>
                                    <select class="form-select" id="exportType" name="export_type" required>
                                        <option value="">Select export type...</option>
                                        <option value="studies">My Studies</option>
                                        <option value="publications">My Publications</option>
                                        <option value="collaborators">My Collaborators</option>
                                        <option value="comments">Study Comments & Reviews</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="format" class="form-label">Format</label>
                                    <select class="form-select" id="format" name="format" required>
                                        <option value="excel">Excel (.xls)</option>
                                        <option value="csv">CSV (.csv)</option>
                                        <option value="pdf">PDF (.pdf)</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div id="filtersSection" style="display: none;">
                            <h6>Filters</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="dateFrom" class="form-label">Date From</label>
                                        <input type="date" class="form-control" id="dateFrom" name="filters[date_from]">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="dateTo" class="form-label">Date To</label>
                                        <input type="date" class="form-control" id="dateTo" name="filters[date_to]">
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3" id="statusFilter" style="display: none;">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" id="status" name="filters[status]">
                                    <option value="">All Statuses</option>
                                    <option value="draft">Draft</option>
                                    <option value="published">Published</option>
                                    <option value="approved">Approved</option>
                                    <option value="pending">Pending</option>
                                </select>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">
                                <i class="fas fa-info-circle"></i>
                                Exports are logged for security purposes. Large exports may take time to process.
                            </small>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-download"></i> Export Data
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Export History -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-history"></i> Recent Exports</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($exportHistory)): ?>
                        <p class="text-muted">No export history yet.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Type</th>
                                        <th>Format</th>
                                        <th>Records</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($exportHistory as $export): ?>
                                        <tr>
                                            <td><?php echo ucfirst($export['export_type']); ?></td>
                                            <td><?php echo strtoupper($export['format']); ?></td>
                                            <td><?php echo $export['record_count']; ?></td>
                                            <td><?php echo date('M d, Y H:i', strtotime($export['created_at'])); ?></td>
                                            <td>
                                                <?php if ($export['file_path']): ?>
                                                    <span class="badge bg-success">Completed</span>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">Processing</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Show/hide filters based on export type
document.getElementById('exportType').addEventListener('change', function() {
    const filtersSection = document.getElementById('filtersSection');
    const statusFilter = document.getElementById('statusFilter');

    if (this.value) {
        filtersSection.style.display = 'block';
        statusFilter.style.display = ['studies', 'publications'].includes(this.value) ? 'block' : 'none';
    } else {
        filtersSection.style.display = 'none';
    }
});
</script>

<?php include '../templates/researcher-mobile-footer.php'; ?>
</body>
</html>

<?php
// Export functions
function exportStudies($format, $filters) {
    global $userId;

    $db = getDB();
    $query = "
        SELECT s.title, s.type, s.status, s.summary, s.objectives, s.methodology,
               s.start_date, s.end_date, s.is_public, s.created_at,
               COUNT(DISTINCT sc.user_id) as collaborator_count,
               COUNT(DISTINCT sd.id) as document_count
        FROM studies s
        LEFT JOIN study_collaborators sc ON s.id = sc.study_id
        LEFT JOIN study_documents sd ON s.id = sd.study_id
        WHERE s.creator_id = ?
    ";

    $params = [$userId];

    // Add date filters
    if (!empty($filters['date_from'])) {
        $query .= " AND s.created_at >= ?";
        $params[] = $filters['date_from'];
    }
    if (!empty($filters['date_to'])) {
        $query .= " AND s.created_at <= ?";
        $params[] = $filters['date_to'] . ' 23:59:59';
    }
    if (!empty($filters['status'])) {
        $query .= " AND s.status = ?";
        $params[] = $filters['status'];
    }

    $query .= " GROUP BY s.id ORDER BY s.created_at DESC";

    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $studies = $stmt->fetchAll();

    if ($format === 'csv') {
        outputCSV($studies, ['Title', 'Type', 'Status', 'Summary', 'Objectives', 'Methodology', 'Start Date', 'End Date', 'Public', 'Created', 'Collaborators', 'Documents']);
    } elseif ($format === 'excel') {
        outputExcel($studies, ['Title', 'Type', 'Status', 'Summary', 'Objectives', 'Methodology', 'Start Date', 'End Date', 'Public', 'Created', 'Collaborators', 'Documents']);
    } elseif ($format === 'pdf') {
        outputPDF($studies, 'My Studies Export');
    }
}

function exportPublications($format, $filters) {
    global $userId;

    $db = getDB();
    $query = "SELECT title, authors, journal, publication_date, doi, url, status, created_at FROM publications WHERE submitter_id = ?";

    $params = [$userId];

    if (!empty($filters['date_from'])) {
        $query .= " AND created_at >= ?";
        $params[] = $filters['date_from'];
    }
    if (!empty($filters['date_to'])) {
        $query .= " AND created_at <= ?";
        $params[] = $filters['date_to'] . ' 23:59:59';
    }
    if (!empty($filters['status'])) {
        $query .= " AND status = ?";
        $params[] = $filters['status'];
    }

    $query .= " ORDER BY created_at DESC";

    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $publications = $stmt->fetchAll();

    if ($format === 'csv') {
        outputCSV($publications, ['Title', 'Authors', 'Journal', 'Publication Date', 'DOI', 'URL', 'Status', 'Created']);
    } elseif ($format === 'excel') {
        outputExcel($publications, ['Title', 'Authors', 'Journal', 'Publication Date', 'DOI', 'URL', 'Status', 'Created']);
    } elseif ($format === 'pdf') {
        outputPDF($publications, 'My Publications Export');
    }
}

function exportCollaborators($format, $filters) {
    global $userId;

    $db = getDB();
    $query = "
        SELECT u.first_name, u.last_name, u.email, u.institution, u.specialization,
               s.title as study_title, sc.joined_at, sc.role
        FROM study_collaborators sc
        JOIN users u ON sc.user_id = u.id
        JOIN studies s ON sc.study_id = s.id
        WHERE s.creator_id = ?
    ";

    $params = [$userId];

    if (!empty($filters['date_from'])) {
        $query .= " AND sc.joined_at >= ?";
        $params[] = $filters['date_from'];
    }
    if (!empty($filters['date_to'])) {
        $query .= " AND sc.joined_at <= ?";
        $params[] = $filters['date_to'] . ' 23:59:59';
    }

    $query .= " ORDER BY sc.joined_at DESC";

    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $collaborators = $stmt->fetchAll();

    if ($format === 'csv') {
        outputCSV($collaborators, ['First Name', 'Last Name', 'Email', 'Institution', 'Specialization', 'Study', 'Joined', 'Role']);
    } elseif ($format === 'excel') {
        outputExcel($collaborators, ['First Name', 'Last Name', 'Email', 'Institution', 'Specialization', 'Study', 'Joined', 'Role']);
    } elseif ($format === 'pdf') {
        outputPDF($collaborators, 'My Collaborators Export');
    }
}

function exportComments($format, $filters) {
    global $userId;

    $db = getDB();
    $query = "
        SELECT sc.content, sc.rating, sc.is_review, sc.status, sc.created_at,
               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 s.creator_id = ?
    ";

    $params = [$userId];

    if (!empty($filters['date_from'])) {
        $query .= " AND sc.created_at >= ?";
        $params[] = $filters['date_from'];
    }
    if (!empty($filters['date_to'])) {
        $query .= " AND sc.created_at <= ?";
        $params[] = $filters['date_to'] . ' 23:59:59';
    }

    $query .= " ORDER BY sc.created_at DESC";

    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $comments = $stmt->fetchAll();

    if ($format === 'csv') {
        outputCSV($comments, ['Content', 'Rating', 'Is Review', 'Status', 'Created', 'Study', 'Author First', 'Author Last']);
    } elseif ($format === 'excel') {
        outputExcel($comments, ['Content', 'Rating', 'Is Review', 'Status', 'Created', 'Study', 'Author First', 'Author Last']);
    } elseif ($format === 'pdf') {
        outputPDF($comments, 'Study Comments & Reviews Export');
    }
}

function outputCSV($data, $headers) {
    $output = fopen('php://output', 'w');
    fputcsv($output, $headers);

    foreach ($data as $row) {
        fputcsv($output, $row);
    }

    fclose($output);
}

function outputExcel($data, $headers) {
    // Simple Excel output using HTML table
    echo "<table border='1'>";
    echo "<tr>";
    foreach ($headers as $header) {
        echo "<th>$header</th>";
    }
    echo "</tr>";

    foreach ($data as $row) {
        echo "<tr>";
        foreach ($row as $cell) {
            echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
}

function outputPDF($data, $title) {
    // Simple text-based PDF output
    echo "PDF Export: $title\n\n";

    if (!empty($data)) {
        foreach ($data as $i => $row) {
            echo "Record " . ($i + 1) . ":\n";
            foreach ($row as $key => $value) {
                echo ucfirst(str_replace('_', ' ', $key)) . ": $value\n";
            }
            echo "\n";
        }
    } else {
        echo "No data to export.";
    }
}
?>
