<?php
session_start();
include('../includes/config.php');

// Get admin details for notification
$admin_id = $_SESSION['user_id'] ?? 1;
$adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_name = $adminData['first_name'] ?? 'System Administrator';
$admin_email = $adminData['email'] ?? 'admin@system.com';

// Get filter parameters
$format = isset($_GET['format']) ? $_GET['format'] : 'csv';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$role = isset($_GET['role']) ? $_GET['role'] : '';
$module = isset($_GET['module']) ? $_GET['module'] : '';
$admin_filter = isset($_GET['admin']) ? $_GET['admin'] : '';

// Store filter details for notification
$filter_details = array();
if (!empty($date_from)) $filter_details[] = "From: " . $date_from;
if (!empty($date_to)) $filter_details[] = "To: " . $date_to;
if (!empty($role)) $filter_details[] = "Role: " . $role;
if (!empty($module)) $filter_details[] = "Module: " . $module;
if (!empty($admin_filter)) $filter_details[] = "Admin: " . $admin_filter;
$filter_summary = !empty($filter_details) ? implode(", ", $filter_details) : "No filters";

// Build query
$sql = "SELECT * FROM admin_activities WHERE 1=1";

// Apply filters
if (!empty($date_from) && !empty($date_to)) {
    $sql .= " AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'";
} elseif (!empty($date_from)) {
    $sql .= " AND DATE(created_at) >= '$date_from'";
} elseif (!empty($date_to)) {
    $sql .= " AND DATE(created_at) <= '$date_to'";
}

if (!empty($role)) {
    $sql .= " AND admin_role = '$role'";
}

if (!empty($module)) {
    $sql .= " AND module = '$module'";
}

if (!empty($admin_filter)) {
    $sql .= " AND admin_name LIKE '%$admin_filter%'";
}

$sql .= " ORDER BY created_at DESC";

$result = mysqli_query($conn, $sql);
$total_records = mysqli_num_rows($result);

// Count activities by type for report summary
$count_sql = "SELECT action, COUNT(*) as count FROM admin_activities WHERE 1=1";
if (!empty($date_from) && !empty($date_to)) {
    $count_sql .= " AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'";
} elseif (!empty($date_from)) {
    $count_sql .= " AND DATE(created_at) >= '$date_from'";
} elseif (!empty($date_to)) {
    $count_sql .= " AND DATE(created_at) <= '$date_to'";
}
$count_sql .= " GROUP BY action ORDER BY count DESC";
$count_result = mysqli_query($conn, $count_sql);

$activity_counts = array();
while ($row = mysqli_fetch_assoc($count_result)) {
    $activity_counts[] = $row['action'] . ": " . $row['count'];
}
$activity_summary = implode(", ", $activity_counts);

if ($format == 'csv') {
    // CSV Export
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="admin_activities_' . date('Y-m-d_H-i-s') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add headers
    fputcsv($output, array('ID', 'Admin Name', 'Admin Role', 'Action', 'Description', 'Module', 'Affected ID', 'IP Address', 'Created At'));
    
    // Add data
    while ($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, array(
            $row['id'],
            $row['admin_name'],
            $row['admin_role'],
            $row['action'],
            $row['description'],
            $row['module'],
            $row['affected_id'],
            $row['ip_address'],
            $row['created_at']
        ));
    }
    
    fclose($output);
    
} elseif ($format == 'excel') {
    // Excel Export (HTML table that Excel can open)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="admin_activities_' . date('Y-m-d_H-i-s') . '.xls"');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>ID</th>';
    echo '<th>Admin Name</th>';
    echo '<th>Admin Role</th>';
    echo '<th>Action</th>';
    echo '<th>Description</th>';
    echo '<th>Module</th>';
    echo '<th>Affected ID</th>';
    echo '<th>IP Address</th>';
    echo '<th>Created At</th>';
    echo '</tr>';
    
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $row['id'] . '</td>';
        echo '<td>' . $row['admin_name'] . '</td>';
        echo '<td>' . $row['admin_role'] . '</td>';
        echo '<td>' . $row['action'] . '</td>';
        echo '<td>' . $row['description'] . '</td>';
        echo '<td>' . $row['module'] . '</td>';
        echo '<td>' . $row['affected_id'] . '</td>';
        echo '<td>' . $row['ip_address'] . '</td>';
        echo '<td>' . $row['created_at'] . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    
} elseif ($format == 'pdf') {
    // For PDF, you would need a library like TCPDF or FPDF
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="admin_activities_' . date('Y-m-d_H-i-s') . '.pdf"');
    
    // Simple HTML that can be converted to PDF
    $html = '<h1>Admin Activities Report</h1>';
    $html .= '<p>Generated on: ' . date('Y-m-d H:i:s') . '</p>';
    $html .= '<p>Generated by: ' . $admin_name . ' (ID: ' . $admin_id . ')</p>';
    $html .= '<p>Filters: ' . $filter_summary . '</p>';
    $html .= '<table border="1" cellpadding="5" cellspacing="0">';
    $html .= '<tr>';
    $html .= '<th>ID</th>';
    $html .= '<th>Admin Name</th>';
    $html .= '<th>Admin Role</th>';
    $html .= '<th>Action</th>';
    $html .= '<th>Description</th>';
    $html .= '<th>Module</th>';
    $html .= '<th>Created At</th>';
    $html .= '</tr>';
    
    while ($row = mysqli_fetch_assoc($result)) {
        $html .= '<tr>';
        $html .= '<td>' . $row['id'] . '</td>';
        $html .= '<td>' . $row['admin_name'] . '</td>';
        $html .= '<td>' . $row['admin_role'] . '</td>';
        $html .= '<td>' . $row['action'] . '</td>';
        $html .= '<td>' . $row['description'] . '</td>';
        $html .= '<td>' . $row['module'] . '</td>';
        $html .= '<td>' . $row['created_at'] . '</td>';
        $html .= '</tr>';
    }
    
    $html .= '</table>';
    $html .= '<p>Total Records: ' . $total_records . '</p>';
    
    echo $html;
}

// Send notification AFTER export headers are sent
// We'll use output buffering to capture the export and still send notification
ob_start();

// The export logic above will output content

// End output buffering and send output
ob_end_flush();

// Now send notification (this happens after the download starts)
// NOTIFICATION: Admin Activities Export (ADMIN)
$mail_subject = "Admin Activities Report Exported";
$mail_message = "<!-- Content Section -->
                <div class='email-content'>
                    <h2 class='greeting'>Report Export Completed</h2>
                    
                    <p class='message'>
                        An admin activities report has been successfully exported from the system.
                    </p>

                    <!-- Export Details -->
                    <div class='details-section'>
                        <div class='detail-box'>
                            <strong>Export Type:</strong> " . strtoupper($format) . " File<br>
                            <strong>File Name:</strong> admin_activities_" . date('Y-m-d_H-i-s') . "." . $format . "<br>
                            <strong>Total Records:</strong> " . number_format($total_records) . " activities<br>
                            <strong>Exported By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                            <strong>Export Time:</strong> " . date('F j, Y g:i A') . "<br>
                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                            <strong>Applied Filters:</strong> " . $filter_summary . "<br>
                            <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>EXPORT COMPLETED</span>
                        </div>
                    </div>

                    <!-- Report Summary -->
                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #0056b3;'>📊 Report Summary</h4>
                        <p style='color: #0056b3;'>
                            <strong>Activities Breakdown:</strong><br>
                            " . (!empty($activity_summary) ? $activity_summary : 'No activities to summarize') . "<br>
                            <strong>Time Range:</strong> " . (!empty($date_from) ? $date_from : 'Start') . " to " . (!empty($date_to) ? $date_to : date('Y-m-d')) . "<br>
                            <strong>Most Active Module:</strong> " . ($module ?: 'All Modules') . "
                        </p>
                    </div>

                    <!-- Data Sensitivity Warning -->
                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #856404;'>🔒 Data Sensitivity Warning</h4>
                        <ul style='color: #856404;'>
                            <li>This report contains sensitive administrative activity data</li>
                            <li>Store the exported file securely</li>
                            <li>Limit access to authorized personnel only</li>
                            <li>Delete the file after its intended use</li>
                            <li>Do not share via unsecured channels</li>
                        </ul>
                    </div>

                    <!-- Report Contents -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>📋 Report Contents</h3>
                        <p style='color: #6c757d;'>The exported file includes:</p>
                        <ul style='color: #6c757d;'>
                            <li>Admin username and role</li>
                            <li>Action performed</li>
                            <li>Detailed description</li>
                            <li>Module/area of operation</li>
                            <li>Affected record ID (if applicable)</li>
                            <li>IP address of admin</li>
                            <li>Timestamp of activity</li>
                        </ul>
                    </div>

                    <!-- What to Do with the Report -->
                    <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #0c5460;'>📈 Typical Uses for This Report</h4>
                        <ul style='color: #0c5460;'>
                            <li>Audit and compliance documentation</li>
                            <li>Security review and analysis</li>
                            <li>Performance monitoring of admin activities</li>
                            <li>Incident investigation</li>
                            <li>Training and process improvement</li>
                        </ul>
                    </div>

                    <!-- Admin Actions -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/admin/activities.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                            View Activities Dashboard
                        </a>
                        <a href='" . $myUrl . "/admin/reports.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                            Generate More Reports
                        </a>
                    </div>

                    <!-- System Information -->
                    <div class='support-section'>
                        <p class='support-text'>Export Information:</p>
                        <p style='color: #6c757d; font-size: 12px;'>
                            <strong>Export Format:</strong> " . strtoupper($format) . "<br>
                            <strong>File Size:</strong> Approximately " . formatSize(estimateReportSize($total_records)) . "<br>
                            <strong>Export Method:</strong> Direct Download<br>
                            <strong>Data Source:</strong> admin_activities table
                        </p>
                    </div>
                </div>";

// Send admin notification
require_once("../proccess/admin_mailer.php");

// Helper function to estimate file size
function estimateReportSize($records) {
    // Estimate ~500 bytes per record for CSV, more for other formats
    $bytes_per_record = 500;
    return $records * $bytes_per_record;
}

function formatSize($bytes) {
    if ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

// Log the export activity
$log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, created_at) 
            VALUES ('$admin_id', '$admin_name', 'admin', 'Report Exported', 'Exported admin activities report in $format format ($total_records records)', 'Reports', NOW())";
mysqli_query($conn, $log_sql);
?>