<?php
require_once '../includes/config.php';

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

// Check if user is logged in and is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || $_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'Not authorized']);
    exit();
}

// Get all activities with details
$sql = "SELECT 
            a.name,
            a.date,
            a.time_in,
            a.time_out,
            a.location,
            a.description,
            a.required_students,
            c.code as course_code,
            c.name as course_name,
            d.code as department_code,
            d.name as department_name,
            u.full_name as created_by,
            CASE a.status WHEN 1 THEN 'Active' ELSE 'Inactive' END as status,
            a.created_at,
            a.updated_at
        FROM activities a
        LEFT JOIN users u ON a.created_by = u.id
        LEFT JOIN courses c ON a.course_id = c.id
        LEFT JOIN departments d ON a.department_id = d.id
        ORDER BY a.date DESC, a.time_in ASC";

$result = query($conn, $sql);
$activities = [];

while ($row = mysqli_fetch_assoc($result)) {
    $activities[] = $row;
}

// Create CSV file
$filename = 'activities_' . date('Y-m-d_H-i-s') . '.csv';
$filepath = '../exports/' . $filename;

// Create exports directory if not exists
if (!file_exists('../exports')) {
    mkdir('../exports', 0777, true);
}

// Open file for writing
$file = fopen($filepath, 'w');

// Add UTF-8 BOM for Excel compatibility
fputs($file, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));

// Add headers
$headers = [
    'Activity Name',
    'Date',
    'Time In',
    'Time Out',
    'Location',
    'Description',
    'Participants',
    'Course Code',
    'Course Name',
    'Department Code',
    'Department Name',
    'Created By',
    'Status',
    'Created At',
    'Updated At'
];
fputcsv($file, $headers);

// Add data rows
foreach ($activities as $activity) {
    fputcsv($file, [
        $activity['name'],
        $activity['date'],
        $activity['time_in'],
        $activity['time_out'],
        $activity['location'],
        $activity['description'],
        $activity['required_students'],
        $activity['course_code'],
        $activity['course_name'],
        $activity['department_code'],
        $activity['department_name'],
        $activity['created_by'],
        $activity['status'],
        $activity['created_at'],
        $activity['updated_at']
    ]);
}

fclose($file);

echo json_encode([
    'success' => true,
    'message' => 'Export completed',
    'download_url' => '../exports/' . $filename,
    'count' => count($activities)
]);
?>