<?php
/**
 * Enterprise HRM ERP System - Export Handler
 * Handles export of reports in various formats
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$siteId = getCurrentSiteId();
$reportType = $_GET['type'] ?? 'attendance';
$format = $_GET['format'] ?? 'excel';
$dateFrom = $_GET['date_from'] ?? date('Y-m-01');
$dateTo = $_GET['date_to'] ?? date('Y-m-d');
$departmentId = isset($_GET['department_id']) ? (int)$_GET['department_id'] : 0;
$designationId = isset($_GET['designation_id']) ? (int)$_GET['designation_id'] : 0;
$leaveTypeId = isset($_GET['leave_type_id']) ? (int)$_GET['leave_type_id'] : 0;
$periodId = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;
$status = $_GET['status'] ?? '';
$preview = isset($_GET['preview']) || isset($_POST['preview']);

try {
    $db = getDB();
    
    // Get data based on report type
    $data = [];
    $headers = [];
    $filename = '';
    
    switch ($reportType) {
        case 'attendance':
            $filename = 'attendance_report_' . date('Y-m-d');
            $headers = ['Date', 'Employee Code', 'Employee Name', 'Department', 'Designation', 'Check In', 'Check Out', 'Total Hours', 'Overtime', 'Status'];
            
            $where = "a.site_id = ? AND a.attendance_date BETWEEN ? AND ?";
            $params = [$siteId, $dateFrom, $dateTo];
            
            if ($departmentId > 0) {
                $where .= " AND e.department_id = ?";
                $params[] = $departmentId;
            }
            
            if ($designationId > 0) {
                $where .= " AND e.designation_id = ?";
                $params[] = $designationId;
            }
            
            $stmt = $db->prepare("
                SELECT 
                    a.attendance_date,
                    e.employee_code,
                    CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
                    d.department_name,
                    des.designation_name,
                    a.check_in_time,
                    a.check_out_time,
                    a.total_hours,
                    a.overtime_hours,
                    a.attendance_status
                FROM attendance a
                INNER JOIN employees e ON a.employee_id = e.employee_id
                LEFT JOIN departments d ON e.department_id = d.department_id
                LEFT JOIN designations des ON e.designation_id = des.designation_id
                WHERE {$where}
                ORDER BY a.attendance_date DESC, e.employee_code
            ");
            $stmt->execute($params);
            $data = $stmt->fetchAll();
            break;
            
        case 'leave':
            $filename = 'leave_report_' . date('Y-m-d');
            $headers = ['Employee Code', 'Employee Name', 'Department', 'Designation', 'Leave Type', 'Start Date', 'End Date', 'Total Days', 'Status', 'Applied Date'];
            
            $where = "la.site_id = ? AND la.applied_at BETWEEN ? AND ?";
            $params = [$siteId, $dateFrom, $dateTo];
            
            if ($leaveTypeId > 0) {
                $where .= " AND la.leave_type_id = ?";
                $params[] = $leaveTypeId;
            }
            
            if (!empty($status)) {
                $where .= " AND la.application_status = ?";
                $params[] = $status;
            }
            
            if ($departmentId > 0) {
                $where .= " AND e.department_id = ?";
                $params[] = $departmentId;
            }
            
            if ($designationId > 0) {
                $where .= " AND e.designation_id = ?";
                $params[] = $designationId;
            }
            
            $stmt = $db->prepare("
                SELECT 
                    e.employee_code,
                    CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
                    d.department_name,
                    des.designation_name,
                    lt.leave_type_name,
                    la.start_date,
                    la.end_date,
                    la.total_days,
                    la.application_status,
                    la.applied_at
                FROM leave_applications la
                INNER JOIN employees e ON la.employee_id = e.employee_id
                LEFT JOIN leave_types lt ON la.leave_type_id = lt.leave_type_id
                LEFT JOIN departments d ON e.department_id = d.department_id
                LEFT JOIN designations des ON e.designation_id = des.designation_id
                WHERE {$where}
                ORDER BY la.applied_at DESC
            ");
            $stmt->execute($params);
            $data = $stmt->fetchAll();
            break;
            
        case 'payroll':
            $filename = 'payroll_report_' . date('Y-m-d');
            $headers = ['Period', 'Employee Code', 'Employee Name', 'Department', 'Designation', 'Working Days', 'Present Days', 'Gross Salary', 'Deductions', 'Net Salary', 'Status'];
            
            $where = "pr.site_id = ?";
            $params = [$siteId];
            
            if ($periodId > 0) {
                $where .= " AND pr.period_id = ?";
                $params[] = $periodId;
            } else {
                $where .= " AND pp.start_date >= ? AND pp.end_date <= ?";
                $params[] = $dateFrom;
                $params[] = $dateTo;
            }
            
            if ($departmentId > 0) {
                $where .= " AND e.department_id = ?";
                $params[] = $departmentId;
            }
            
            if ($designationId > 0) {
                $where .= " AND e.designation_id = ?";
                $params[] = $designationId;
            }
            
            $stmt = $db->prepare("
                SELECT 
                    pp.period_code,
                    e.employee_code,
                    CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
                    d.department_name,
                    des.designation_name,
                    pr.working_days,
                    pr.present_days,
                    pr.gross_salary,
                    pr.total_deductions,
                    pr.net_salary,
                    pr.payroll_status
                FROM payroll_records pr
                INNER JOIN employees e ON pr.employee_id = e.employee_id
                INNER JOIN payroll_periods pp ON pr.period_id = pp.period_id
                LEFT JOIN departments d ON e.department_id = d.department_id
                LEFT JOIN designations des ON e.designation_id = des.designation_id
                WHERE {$where}
                ORDER BY pp.start_date DESC, e.employee_code
            ");
            $stmt->execute($params);
            $data = $stmt->fetchAll();
            break;
            
        case 'employee':
            $filename = 'employee_report_' . date('Y-m-d');
            $headers = ['Employee Code', 'Name', 'Department', 'Designation', 'Email', 'Phone', 'Joining Date', 'Status'];
            
            $stmt = $db->prepare("
                SELECT 
                    e.employee_code,
                    CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
                    d.department_name,
                    des.designation_name,
                    e.email,
                    e.phone,
                    e.joining_date,
                    e.employment_status
                FROM employees e
                LEFT JOIN departments d ON e.department_id = d.department_id
                LEFT JOIN designations des ON e.designation_id = des.designation_id
                WHERE e.site_id = ?
                ORDER BY e.employee_code
            ");
            $stmt->execute([$siteId]);
            $data = $stmt->fetchAll();
            break;
    }
    
    // If preview mode, show data in HTML table
    if ($preview) {
        $reportTypeNames = [
            'attendance' => 'Attendance Reports',
            'leave' => 'Leave Reports',
            'payroll' => 'Payroll Reports',
            'employee' => 'Employee Reports',
            'all' => 'All Reports'
        ];
        header('Content-Type: text/html; charset=utf-8');
        echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Export Preview</title>';
        echo '<style>body{font-family:Arial;padding:20px;}table{border-collapse:collapse;width:100%;}th,td{border:1px solid #ddd;padding:8px;text-align:left;}th{background-color:#4CAF50;color:white;}</style>';
        echo '</head><body><h2>Export Preview - ' . htmlspecialchars($reportTypeNames[$reportType] ?? $reportType) . '</h2>';
        echo '<p>Total Records: <strong>' . count($data) . '</strong></p>';
        echo '<table><tr>';
        foreach ($headers as $header) {
            echo '<th>' . htmlspecialchars($header) . '</th>';
        }
        echo '</tr>';
        foreach (array_slice($data, 0, 100) as $row) { // Show first 100 rows
            echo '<tr>';
            foreach ($row as $key => $value) {
                if (in_array($key, array_keys($row))) {
                    echo '<td>' . htmlspecialchars($value ?? '') . '</td>';
                }
            }
            echo '</tr>';
        }
        if (count($data) > 100) {
            echo '<tr><td colspan="' . count($headers) . '" style="text-align:center;font-style:italic;">... and ' . (count($data) - 100) . ' more rows</td></tr>';
        }
        echo '</table></body></html>';
        exit;
    }
    
    // Export based on format
    switch ($format) {
        case 'csv':
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
            
            $output = fopen('php://output', 'w');
            
            // Add BOM for UTF-8
            fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
            
            // Headers
            fputcsv($output, $headers);
            
            // Data
            foreach ($data as $row) {
                $csvRow = [];
                foreach ($row as $key => $value) {
                    if (in_array($key, array_keys($row))) {
                        $csvRow[] = $value;
                    }
                }
                fputcsv($output, $csvRow);
            }
            
            fclose($output);
            exit;
            
        case 'excel':
            // For Excel, we'll use CSV format (can be opened in Excel)
            header('Content-Type: application/vnd.ms-excel; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
            
            echo '<table border="1">';
            echo '<tr>';
            foreach ($headers as $header) {
                echo '<th style="background-color: #4CAF50; color: white; padding: 8px;">' . htmlspecialchars($header) . '</th>';
            }
            echo '</tr>';
            
            foreach ($data as $row) {
                echo '<tr>';
                foreach ($row as $key => $value) {
                    if (in_array($key, array_keys($row))) {
                        echo '<td>' . htmlspecialchars($value ?? '') . '</td>';
                    }
                }
                echo '</tr>';
            }
            echo '</table>';
            exit;
            
        case 'pdf':
            // For PDF, redirect to a PDF generation page or use a library
            // For now, we'll show a message
            redirect(BASE_URL . '/modules/reports/export.php', 'PDF export feature coming soon. Please use Excel or CSV format.', 'info');
            break;
            
        default:
            redirect(BASE_URL . '/modules/reports/export.php', 'Invalid export format.', 'error');
    }
    
} catch (Exception $e) {
    error_log("Export error: " . $e->getMessage());
    redirect(BASE_URL . '/modules/reports/export.php', 'Error generating export. Please try again.', 'error');
}

