<?php
/**
 * Enterprise HRM ERP System - Export Reports
 */

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

$pageTitle = 'Export Reports';
$currentModule = 'reports';

$siteId = getCurrentSiteId();
$reportType = $_GET['type'] ?? 'attendance';
$format = $_GET['format'] ?? 'excel';

// Available report types
$reportTypes = [
    'attendance' => [
        'name' => 'Attendance Reports',
        'icon' => '⏰',
        'description' => 'Export attendance records with filters'
    ],
    'leave' => [
        'name' => 'Leave Reports',
        'icon' => '📅',
        'description' => 'Export leave applications and balances'
    ],
    'payroll' => [
        'name' => 'Payroll Reports',
        'icon' => '💰',
        'description' => 'Export payroll records and summaries'
    ],
    'employee' => [
        'name' => 'Employee Reports',
        'icon' => '👥',
        'description' => 'Export employee data and statistics'
    ],
    'all' => [
        'name' => 'All Reports',
        'icon' => '📊',
        'description' => 'Export all data in one file'
    ]
];

// Available formats
$formats = [
    'excel' => [
        'name' => 'Excel (XLSX)',
        'icon' => '📗',
        'extension' => 'xlsx'
    ],
    'csv' => [
        'name' => 'CSV',
        'icon' => '📄',
        'extension' => 'csv'
    ],
    'pdf' => [
        'name' => 'PDF',
        'icon' => '📕',
        'extension' => 'pdf'
    ]
];

// Get filter options based on report type
try {
    $db = getDB();
    $departments = [];
    $designations = [];
    $leaveTypes = [];
    $periods = [];
    
    // Get departments
    $stmt = $db->prepare("SELECT department_id, department_name FROM departments WHERE site_id = ? ORDER BY department_name");
    $stmt->execute([$siteId]);
    $departments = $stmt->fetchAll();
    
    // Get designations
    $stmt = $db->prepare("SELECT designation_id, designation_name FROM designations WHERE site_id = ? ORDER BY designation_name");
    $stmt->execute([$siteId]);
    $designations = $stmt->fetchAll();
    
    // Get leave types (for leave reports)
    if ($reportType === 'leave') {
        $stmt = $db->prepare("SELECT leave_type_id, leave_type_name FROM leave_types WHERE site_id = ? ORDER BY leave_type_name");
        $stmt->execute([$siteId]);
        $leaveTypes = $stmt->fetchAll();
    }
    
    // Get payroll periods (for payroll reports)
    if ($reportType === 'payroll') {
        $stmt = $db->prepare("SELECT period_id, period_name, period_code FROM payroll_periods WHERE site_id = ? ORDER BY start_date DESC LIMIT 12");
        $stmt->execute([$siteId]);
        $periods = $stmt->fetchAll();
    }
    
    // Get record count for preview
    $recordCount = 0;
    $dateFrom = $_GET['date_from'] ?? date('Y-m-01');
    $dateTo = $_GET['date_to'] ?? date('Y-m-d');
    
    switch ($reportType) {
        case 'attendance':
            $stmt = $db->prepare("SELECT COUNT(*) FROM attendance WHERE site_id = ? AND attendance_date BETWEEN ? AND ?");
            $stmt->execute([$siteId, $dateFrom, $dateTo]);
            $recordCount = $stmt->fetchColumn();
            break;
        case 'leave':
            $stmt = $db->prepare("SELECT COUNT(*) FROM leave_applications WHERE site_id = ? AND applied_at BETWEEN ? AND ?");
            $stmt->execute([$siteId, $dateFrom, $dateTo]);
            $recordCount = $stmt->fetchColumn();
            break;
        case 'payroll':
            $stmt = $db->prepare("
                SELECT COUNT(*) FROM payroll_records pr
                INNER JOIN payroll_periods pp ON pr.period_id = pp.period_id
                WHERE pr.site_id = ? AND pp.start_date BETWEEN ? AND ?
            ");
            $stmt->execute([$siteId, $dateFrom, $dateTo]);
            $recordCount = $stmt->fetchColumn();
            break;
        case 'employee':
            $stmt = $db->prepare("SELECT COUNT(*) FROM employees WHERE site_id = ?");
            $stmt->execute([$siteId]);
            $recordCount = $stmt->fetchColumn();
            break;
    }
    
} catch (Exception $e) {
    error_log("Export page error: " . $e->getMessage());
    $departments = [];
    $designations = [];
    $leaveTypes = [];
    $periods = [];
    $recordCount = 0;
}

include __DIR__ . '/../../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Export Reports</h2>
        <a href="<?php echo BASE_URL; ?>/modules/reports/index.php" class="btn btn-secondary">Back to Reports</a>
    </div>
    
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-top: 20px;">
        <!-- Report Type Selection -->
        <div class="card" style="padding: 20px;">
            <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Select Report Type</h3>
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <?php foreach ($reportTypes as $key => $type): ?>
                <div 
                    class="card" 
                    style="padding: 15px; cursor: pointer; transition: all 0.2s; <?php echo $reportType === $key ? 'border: 2px solid var(--primary-color); background: #f0f4ff;' : ''; ?>"
                    onmouseover="this.style.transform='scale(1.02)'" 
                    onmouseout="this.style.transform='scale(1)'"
                    onclick="selectReportType('<?php echo $key; ?>')">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <div style="font-size: 32px;"><?php echo $type['icon']; ?></div>
                        <div style="flex: 1;">
                            <div style="font-weight: 600; font-size: 16px;"><?php echo $type['name']; ?></div>
                            <div style="color: var(--text-secondary); font-size: 12px; margin-top: 3px;"><?php echo $type['description']; ?></div>
                        </div>
                        <?php if ($reportType === $key): ?>
                        <div style="color: var(--primary-color); font-size: 20px;">✓</div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Format Selection -->
        <div class="card" style="padding: 20px;">
            <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Select Export Format</h3>
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <?php foreach ($formats as $key => $formatItem): ?>
                <div 
                    class="card" 
                    style="padding: 15px; cursor: pointer; transition: all 0.2s; <?php echo $format === $key ? 'border: 2px solid var(--primary-color); background: #f0f4ff;' : ''; ?>"
                    onmouseover="this.style.transform='scale(1.02)'" 
                    onmouseout="this.style.transform='scale(1)'"
                    onclick="selectFormat('<?php echo $key; ?>')">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <div style="font-size: 32px;"><?php echo $formatItem['icon']; ?></div>
                        <div style="flex: 1;">
                            <div style="font-weight: 600; font-size: 16px;"><?php echo $formatItem['name']; ?></div>
                            <div style="color: var(--text-secondary); font-size: 12px; margin-top: 3px;">.<?php echo $formatItem['extension']; ?> format</div>
                        </div>
                        <?php if ($format === $key): ?>
                        <div style="color: var(--primary-color); font-size: 20px;">✓</div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <!-- Export Options -->
    <div class="card" style="margin-top: 30px; padding: 20px;">
        <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Export Options</h3>
        
        <form id="exportForm" method="GET" action="<?php echo BASE_URL; ?>/modules/reports/export_handler.php">
            <input type="hidden" name="type" value="<?php echo htmlspecialchars($reportType); ?>">
            <input type="hidden" name="format" value="<?php echo htmlspecialchars($format); ?>">
            
            <!-- Quick Date Presets -->
            <div style="margin-bottom: 20px;">
                <label class="form-label" style="margin-bottom: 10px; display: block;">Quick Date Range</label>
                <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('today')">Today</button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('yesterday')">Yesterday</button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('thisweek')">This Week</button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('lastweek')">Last Week</button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('thismonth')">This Month</button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('lastmonth')">Last Month</button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('thisquarter')">This Quarter</button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setDateRange('thisyear')">This Year</button>
                </div>
            </div>
            
            <!-- Date Range -->
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 20px;">
                <div class="form-group">
                    <label class="form-label">Date From *</label>
                    <input type="date" name="date_from" id="date_from" class="form-control" 
                           value="<?php echo htmlspecialchars($_GET['date_from'] ?? date('Y-m-01')); ?>" 
                           required onchange="updatePreview()">
                </div>
                <div class="form-group">
                    <label class="form-label">Date To *</label>
                    <input type="date" name="date_to" id="date_to" class="form-control" 
                           value="<?php echo htmlspecialchars($_GET['date_to'] ?? date('Y-m-d')); ?>" 
                           required onchange="updatePreview()">
                </div>
            </div>
            
            <!-- Additional Filters based on Report Type -->
            <?php if ($reportType === 'attendance' || $reportType === 'employee'): ?>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 20px;">
                <div class="form-group">
                    <label class="form-label">Department</label>
                    <select name="department_id" class="form-control" onchange="updatePreview()">
                        <option value="0">All Departments</option>
                        <?php foreach ($departments as $dept): ?>
                        <option value="<?php echo $dept['department_id']; ?>" 
                                <?php echo (isset($_GET['department_id']) && $_GET['department_id'] == $dept['department_id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($dept['department_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Designation</label>
                    <select name="designation_id" class="form-control" onchange="updatePreview()">
                        <option value="0">All Designations</option>
                        <?php foreach ($designations as $desg): ?>
                        <option value="<?php echo $desg['designation_id']; ?>" 
                                <?php echo (isset($_GET['designation_id']) && $_GET['designation_id'] == $desg['designation_id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($desg['designation_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if ($reportType === 'leave'): ?>
            <div style="margin-bottom: 20px;">
                <div class="form-group">
                    <label class="form-label">Leave Type</label>
                    <select name="leave_type_id" class="form-control" onchange="updatePreview()">
                        <option value="0">All Leave Types</option>
                        <?php foreach ($leaveTypes as $type): ?>
                        <option value="<?php echo $type['leave_type_id']; ?>" 
                                <?php echo (isset($_GET['leave_type_id']) && $_GET['leave_type_id'] == $type['leave_type_id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($type['leave_type_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if ($reportType === 'payroll'): ?>
            <div style="margin-bottom: 20px;">
                <div class="form-group">
                    <label class="form-label">Payroll Period</label>
                    <select name="period_id" class="form-control" onchange="updatePreview()">
                        <option value="0">All Periods</option>
                        <?php foreach ($periods as $period): ?>
                        <option value="<?php echo $period['period_id']; ?>" 
                                <?php echo (isset($_GET['period_id']) && $_GET['period_id'] == $period['period_id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($period['period_name'] . ' (' . $period['period_code'] . ')'); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Status Filter for Leave Reports -->
            <?php if ($reportType === 'leave'): ?>
            <div style="margin-bottom: 20px;">
                <div class="form-group">
                    <label class="form-label">Application Status</label>
                    <select name="status" class="form-control" onchange="updatePreview()">
                        <option value="">All Status</option>
                        <option value="pending" <?php echo (isset($_GET['status']) && $_GET['status'] === 'pending') ? 'selected' : ''; ?>>Pending</option>
                        <option value="approved" <?php echo (isset($_GET['status']) && $_GET['status'] === 'approved') ? 'selected' : ''; ?>>Approved</option>
                        <option value="rejected" <?php echo (isset($_GET['status']) && $_GET['status'] === 'rejected') ? 'selected' : ''; ?>>Rejected</option>
                        <option value="cancelled" <?php echo (isset($_GET['status']) && $_GET['status'] === 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                    </select>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Preview Section -->
            <div style="padding: 15px; background: #f8fafc; border-radius: 8px; margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <div style="font-size: 24px;">📊</div>
                    <div style="flex: 1;">
                        <div style="font-weight: 600; font-size: 16px;">Records Found</div>
                        <div style="color: var(--text-secondary); font-size: 14px;" id="recordCount">
                            <?php echo number_format($recordCount); ?> records will be exported
                        </div>
                    </div>
                    <div style="font-size: 28px; color: var(--primary-color); font-weight: 600;">
                        <?php echo number_format($recordCount); ?>
                    </div>
                </div>
            </div>
            
            <!-- Export Options -->
            <div style="padding: 15px; background: #fff9e6; border: 1px solid #ffd700; border-radius: 8px; margin-bottom: 20px;">
                <div style="display: flex; align-items: start; gap: 10px;">
                    <div style="font-size: 20px;">⚙️</div>
                    <div style="flex: 1;">
                        <div style="font-weight: 600; margin-bottom: 10px;">Export Settings</div>
                        <div style="display: flex; flex-direction: column; gap: 8px;">
                            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="include_headers" value="1" checked>
                                <span>Include Column Headers</span>
                            </label>
                            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="include_summary" value="1">
                                <span>Include Summary Statistics</span>
                            </label>
                            <?php if ($format === 'excel'): ?>
                            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="format_numbers" value="1" checked>
                                <span>Format Numbers & Currency</span>
                            </label>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Action Buttons -->
            <div style="display: flex; gap: 10px; justify-content: flex-end; padding-top: 20px; border-top: 1px solid var(--border-color);">
                <a href="<?php echo BASE_URL; ?>/modules/reports/index.php" class="btn btn-secondary">Cancel</a>
                <button type="button" onclick="previewExport()" class="btn btn-secondary">
                    <span style="margin-right: 5px;">👁️</span>
                    Preview
                </button>
                <button type="submit" class="btn btn-primary" id="exportBtn">
                    <span style="margin-right: 5px;">📥</span>
                    Export <?php echo $reportTypes[$reportType]['name']; ?> as <?php echo strtoupper($format); ?>
                </button>
            </div>
        </form>
    </div>
    
    <!-- Export History -->
    <div class="card" style="margin-top: 30px; padding: 20px;">
        <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Recent Exports</h3>
        <div style="text-align: center; padding: 40px; color: var(--text-secondary);">
            <div style="font-size: 48px; margin-bottom: 10px;">📋</div>
            <div>No recent exports found</div>
            <div style="font-size: 12px; margin-top: 5px;">Your export history will appear here</div>
        </div>
    </div>
</div>

<script>
function selectReportType(type) {
    const params = new URLSearchParams(window.location.search);
    params.set('type', type);
    window.location.href = '?' + params.toString();
}

function selectFormat(format) {
    const params = new URLSearchParams(window.location.search);
    params.set('format', format);
    window.location.href = '?' + params.toString();
}

function setDateRange(range) {
    const today = new Date();
    const dateFrom = document.getElementById('date_from');
    const dateTo = document.getElementById('date_to');
    
    let fromDate, toDate;
    
    switch(range) {
        case 'today':
            fromDate = toDate = today.toISOString().split('T')[0];
            break;
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            fromDate = toDate = yesterday.toISOString().split('T')[0];
            break;
        case 'thisweek':
            const startOfWeek = new Date(today);
            startOfWeek.setDate(today.getDate() - today.getDay());
            fromDate = startOfWeek.toISOString().split('T')[0];
            toDate = today.toISOString().split('T')[0];
            break;
        case 'lastweek':
            const lastWeekStart = new Date(today);
            lastWeekStart.setDate(today.getDate() - today.getDay() - 7);
            const lastWeekEnd = new Date(lastWeekStart);
            lastWeekEnd.setDate(lastWeekStart.getDate() + 6);
            fromDate = lastWeekStart.toISOString().split('T')[0];
            toDate = lastWeekEnd.toISOString().split('T')[0];
            break;
        case 'thismonth':
            fromDate = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
            toDate = today.toISOString().split('T')[0];
            break;
        case 'lastmonth':
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
            fromDate = lastMonth.toISOString().split('T')[0];
            toDate = lastMonthEnd.toISOString().split('T')[0];
            break;
        case 'thisquarter':
            const quarter = Math.floor(today.getMonth() / 3);
            fromDate = new Date(today.getFullYear(), quarter * 3, 1).toISOString().split('T')[0];
            toDate = today.toISOString().split('T')[0];
            break;
        case 'thisyear':
            fromDate = new Date(today.getFullYear(), 0, 1).toISOString().split('T')[0];
            toDate = today.toISOString().split('T')[0];
            break;
    }
    
    dateFrom.value = fromDate;
    dateTo.value = toDate;
    updatePreview();
}

function updatePreview() {
    // Update preview count via AJAX
    const form = document.getElementById('exportForm');
    const formData = new FormData(form);
    formData.append('preview', '1');
    
    fetch('<?php echo BASE_URL; ?>/modules/reports/export_preview.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('recordCount').textContent = 
            new Intl.NumberFormat().format(data.count) + ' records will be exported';
        document.querySelector('#recordCount').parentElement.nextElementSibling.textContent = 
            new Intl.NumberFormat().format(data.count);
    })
    .catch(error => {
        console.error('Error updating preview:', error);
    });
}

function previewExport() {
    const form = document.getElementById('exportForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    params.set('preview', '1');
    
    window.open('<?php echo BASE_URL; ?>/modules/reports/export_handler.php?' + params.toString(), '_blank');
}
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
