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

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

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

$siteId = getCurrentSiteId();
$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;

try {
    $db = getDB();
    
    // Get departments for filter
    $stmt = $db->prepare("SELECT department_id, department_name FROM departments WHERE site_id = ? ORDER BY department_name");
    $stmt->execute([$siteId]);
    $departments = $stmt->fetchAll();
    
    // Overall Statistics
    $stats = [];
    
    // Total Records
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ?
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $stats['total_records'] = $stmt->fetchColumn();
    
    // Present Count
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ? AND attendance_status = 'present'
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $stats['present'] = $stmt->fetchColumn();
    
    // Absent Count
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ? AND attendance_status = 'absent'
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $stats['absent'] = $stmt->fetchColumn();
    
    // Late Count
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ? AND attendance_status = 'late'
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $stats['late'] = $stmt->fetchColumn();
    
    // Total Hours
    $stmt = $db->prepare("
        SELECT COALESCE(SUM(total_hours), 0) FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ?
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $stats['total_hours'] = $stmt->fetchColumn();
    
    // Overtime Hours
    $stmt = $db->prepare("
        SELECT COALESCE(SUM(overtime_hours), 0) FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ?
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $stats['overtime_hours'] = $stmt->fetchColumn();
    
    // Attendance by Status
    $stmt = $db->prepare("
        SELECT attendance_status, COUNT(*) as count
        FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ?
        GROUP BY attendance_status
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $statusBreakdown = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Daily Attendance Trend
    $stmt = $db->prepare("
        SELECT attendance_date, 
               COUNT(*) as total,
               SUM(CASE WHEN attendance_status = 'present' THEN 1 ELSE 0 END) as present
        FROM attendance 
        WHERE site_id = ? AND attendance_date BETWEEN ? AND ?
        GROUP BY attendance_date
        ORDER BY attendance_date
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $dailyTrend = $stmt->fetchAll();
    
    // Department-wise Statistics
    $whereDept = $departmentId > 0 ? "AND e.department_id = ?" : "";
    $deptParams = $departmentId > 0 ? [$siteId, $dateFrom, $dateTo, $departmentId] : [$siteId, $dateFrom, $dateTo];
    
    $stmt = $db->prepare("
        SELECT 
            d.department_name,
            COUNT(DISTINCT a.employee_id) as employees,
            COUNT(*) as total_records,
            SUM(CASE WHEN a.attendance_status = 'present' THEN 1 ELSE 0 END) as present,
            SUM(CASE WHEN a.attendance_status = 'absent' THEN 1 ELSE 0 END) as absent,
            ROUND(AVG(a.total_hours), 2) as avg_hours
        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
        WHERE a.site_id = ? AND a.attendance_date BETWEEN ? AND ? {$whereDept}
        GROUP BY d.department_id, d.department_name
        ORDER BY d.department_name
    ");
    $stmt->execute($deptParams);
    $deptStats = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Attendance report error: " . $e->getMessage());
    $stats = ['total_records' => 0, 'present' => 0, 'absent' => 0, 'late' => 0, 'total_hours' => 0, 'overtime_hours' => 0];
    $statusBreakdown = [];
    $dailyTrend = [];
    $deptStats = [];
    $departments = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Attendance Reports & Analytics</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/reports/index.php" class="btn btn-secondary">Back to Reports</a>
            <button onclick="exportReport('excel')" class="btn btn-primary">Export Excel</button>
            <button onclick="exportReport('pdf')" class="btn btn-primary">Export PDF</button>
        </div>
    </div>
    
    <!-- Filters -->
    <div style="padding: 20px; background: #f8fafc; border-radius: 8px; margin-bottom: 20px;">
        <form method="GET" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; align-items: end;">
            <div class="form-group">
                <label class="form-label">From Date</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($dateFrom); ?>" onchange="this.form.submit()">
            </div>
            <div class="form-group">
                <label class="form-label">To Date</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($dateTo); ?>" onchange="this.form.submit()">
            </div>
            <div class="form-group">
                <label class="form-label">Department</label>
                <select name="department_id" class="form-control" onchange="this.form.submit()">
                    <option value="0">All Departments</option>
                    <?php foreach ($departments as $dept): ?>
                    <option value="<?php echo $dept['department_id']; ?>" <?php echo $departmentId == $dept['department_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($dept['department_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </form>
    </div>
    
    <!-- Statistics Cards -->
    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 30px;">
        <div class="card" style="padding: 20px; text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
            <div style="font-size: 32px; font-weight: 600;"><?php echo number_format($stats['total_records']); ?></div>
            <div style="margin-top: 5px; opacity: 0.9;">Total Records</div>
        </div>
        <div class="card" style="padding: 20px; text-align: center; background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white;">
            <div style="font-size: 32px; font-weight: 600;"><?php echo number_format($stats['present']); ?></div>
            <div style="margin-top: 5px; opacity: 0.9;">Present</div>
        </div>
        <div class="card" style="padding: 20px; text-align: center; background: linear-gradient(135deg, #ee0979 0%, #ff6a00 100%); color: white;">
            <div style="font-size: 32px; font-weight: 600;"><?php echo number_format($stats['absent']); ?></div>
            <div style="margin-top: 5px; opacity: 0.9;">Absent</div>
        </div>
        <div class="card" style="padding: 20px; text-align: center; background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
            <div style="font-size: 32px; font-weight: 600;"><?php echo number_format($stats['late']); ?></div>
            <div style="margin-top: 5px; opacity: 0.9;">Late</div>
        </div>
    </div>
    
    <!-- Additional Stats -->
    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 30px;">
        <div class="card" style="padding: 20px;">
            <h3 style="margin-bottom: 15px;">Total Working Hours</h3>
            <div style="font-size: 36px; font-weight: 600; color: var(--primary-color);">
                <?php echo number_format($stats['total_hours'], 2); ?> hrs
            </div>
            <div style="margin-top: 10px; color: var(--text-secondary);">
                Overtime: <?php echo number_format($stats['overtime_hours'], 2); ?> hrs
            </div>
        </div>
        <div class="card" style="padding: 20px;">
            <h3 style="margin-bottom: 15px;">Attendance Rate</h3>
            <?php 
            $attendanceRate = $stats['total_records'] > 0 ? ($stats['present'] / $stats['total_records']) * 100 : 0;
            ?>
            <div style="font-size: 36px; font-weight: 600; color: var(--success-color);">
                <?php echo number_format($attendanceRate, 1); ?>%
            </div>
            <div style="margin-top: 10px; color: var(--text-secondary);">
                Present: <?php echo $stats['present']; ?> / Total: <?php echo $stats['total_records']; ?>
            </div>
        </div>
    </div>
    
    <!-- Status Breakdown Chart -->
    <div class="card" style="margin-bottom: 30px;">
        <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Status Breakdown</h3>
        <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 15px;">
            <?php 
            $statusLabels = [
                'present' => 'Present',
                'absent' => 'Absent',
                'late' => 'Late',
                'half_day' => 'Half Day',
                'on_leave' => 'On Leave'
            ];
            $statusColors = [
                'present' => '#10b981',
                'absent' => '#ef4444',
                'late' => '#f59e0b',
                'half_day' => '#8b5cf6',
                'on_leave' => '#3b82f6'
            ];
            foreach ($statusLabels as $key => $label): 
                $count = $statusBreakdown[$key] ?? 0;
                $percentage = $stats['total_records'] > 0 ? ($count / $stats['total_records']) * 100 : 0;
            ?>
            <div style="text-align: center; padding: 15px; background: #f8fafc; border-radius: 8px;">
                <div style="font-size: 24px; font-weight: 600; color: <?php echo $statusColors[$key]; ?>;">
                    <?php echo number_format($count); ?>
                </div>
                <div style="margin-top: 5px; color: var(--text-secondary);"><?php echo $label; ?></div>
                <div style="margin-top: 5px; font-size: 12px; color: var(--text-secondary);">
                    <?php echo number_format($percentage, 1); ?>%
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <!-- Department-wise Statistics -->
    <?php if (count($deptStats) > 0): ?>
    <div class="card">
        <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Department-wise Statistics</h3>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Department</th>
                    <th>Employees</th>
                    <th>Total Records</th>
                    <th>Present</th>
                    <th>Absent</th>
                    <th>Avg Hours/Day</th>
                    <th>Attendance Rate</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($deptStats as $dept): 
                    $deptRate = $dept['total_records'] > 0 ? ($dept['present'] / $dept['total_records']) * 100 : 0;
                ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($dept['department_name'] ?? 'N/A'); ?></strong></td>
                    <td><?php echo number_format($dept['employees']); ?></td>
                    <td><?php echo number_format($dept['total_records']); ?></td>
                    <td style="color: var(--success-color);"><?php echo number_format($dept['present']); ?></td>
                    <td style="color: var(--error-color);"><?php echo number_format($dept['absent']); ?></td>
                    <td><?php echo number_format($dept['avg_hours'], 2); ?></td>
                    <td>
                        <span style="color: <?php echo $deptRate >= 90 ? 'var(--success-color)' : ($deptRate >= 70 ? 'var(--warning-color)' : 'var(--error-color)'); ?>;">
                            <?php echo number_format($deptRate, 1); ?>%
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<script>
function exportReport(format) {
    const params = new URLSearchParams(window.location.search);
    params.append('export', format);
    window.location.href = '<?php echo BASE_URL; ?>/modules/reports/export_attendance.php?' + params.toString();
}
</script>

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

