<?php
/**
 * Enterprise HRM ERP System - Analytics Dashboard
 */

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

$pageTitle = 'Analytics Dashboard';
$currentModule = 'reports';

$siteId = getCurrentSiteId();
$period = $_GET['period'] ?? 'month'; // month, quarter, year

// Calculate date range based on period
$dateFrom = '';
$dateTo = date('Y-m-d');
switch ($period) {
    case 'week':
        $dateFrom = date('Y-m-d', strtotime('-7 days'));
        break;
    case 'month':
        $dateFrom = date('Y-m-01');
        break;
    case 'quarter':
        $quarter = ceil(date('n') / 3);
        $dateFrom = date('Y-m-d', mktime(0, 0, 0, ($quarter - 1) * 3 + 1, 1, date('Y')));
        break;
    case 'year':
        $dateFrom = date('Y-01-01');
        break;
}

try {
    $db = getDB();
    
    // Key Metrics
    $metrics = [];
    
    // Total Employees
    $stmt = $db->prepare("SELECT COUNT(*) FROM employees WHERE site_id = ? AND employment_status = 'active'");
    $stmt->execute([$siteId]);
    $metrics['total_employees'] = $stmt->fetchColumn();
    
    // Attendance Rate
    $stmt = $db->prepare("
        SELECT 
            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 ?
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $attData = $stmt->fetch();
    $metrics['attendance_rate'] = $attData['total'] > 0 ? ($attData['present'] / $attData['total']) * 100 : 0;
    
    // Leave Utilization
    $stmt = $db->prepare("
        SELECT COALESCE(SUM(total_days), 0) 
        FROM leave_applications 
        WHERE site_id = ? AND application_status = 'approved' 
        AND start_date BETWEEN ? AND ?
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo]);
    $metrics['leave_days'] = $stmt->fetchColumn();
    
    // Total Payroll Cost
    $stmt = $db->prepare("
        SELECT COALESCE(SUM(net_salary), 0) 
        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]);
    $metrics['payroll_cost'] = $stmt->fetchColumn();
    
    // Average Salary
    $stmt = $db->prepare("
        SELECT COALESCE(AVG(net_salary), 0) 
        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]);
    $metrics['avg_salary'] = $stmt->fetchColumn();
    
    // Pending Leave Applications
    $stmt = $db->prepare("SELECT COUNT(*) FROM leave_applications WHERE site_id = ? AND application_status = 'pending'");
    $stmt->execute([$siteId]);
    $metrics['pending_leaves'] = $stmt->fetchColumn();
    
    // Recent Hires (Last 30 days)
    $stmt = $db->prepare("
        SELECT COUNT(*) 
        FROM employees 
        WHERE site_id = ? AND joining_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    ");
    $stmt->execute([$siteId]);
    $metrics['recent_hires'] = $stmt->fetchColumn();
    
    // Department Performance
    $stmt = $db->prepare("
        SELECT 
            d.department_name,
            COUNT(DISTINCT e.employee_id) as employees,
            COUNT(DISTINCT CASE WHEN a.attendance_status = 'present' THEN a.employee_id END) as present_count,
            COUNT(DISTINCT a.employee_id) as total_attendance
        FROM departments d
        LEFT JOIN employees e ON d.department_id = e.department_id AND e.site_id = ?
        LEFT JOIN attendance a ON e.employee_id = a.employee_id AND a.attendance_date BETWEEN ? AND ?
        WHERE d.site_id = ?
        GROUP BY d.department_id, d.department_name
        HAVING employees > 0
        ORDER BY employees DESC
    ");
    $stmt->execute([$siteId, $dateFrom, $dateTo, $siteId]);
    $deptPerformance = $stmt->fetchAll();
    
    // Monthly Trends
    $stmt = $db->prepare("
        SELECT 
            DATE_FORMAT(attendance_date, '%Y-%m') as month,
            COUNT(*) as total,
            SUM(CASE WHEN attendance_status = 'present' THEN 1 ELSE 0 END) as present
        FROM attendance 
        WHERE site_id = ? AND attendance_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(attendance_date, '%Y-%m')
        ORDER BY month
    ");
    $stmt->execute([$siteId]);
    $monthlyTrends = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Analytics error: " . $e->getMessage());
    $metrics = [
        'total_employees' => 0,
        'attendance_rate' => 0,
        'leave_days' => 0,
        'payroll_cost' => 0,
        'avg_salary' => 0,
        'pending_leaves' => 0,
        'recent_hires' => 0
    ];
    $deptPerformance = [];
    $monthlyTrends = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Analytics Dashboard</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>
            <select class="form-control" style="width: auto;" onchange="window.location.href='?period=' + this.value">
                <option value="week" <?php echo $period === 'week' ? 'selected' : ''; ?>>Last 7 Days</option>
                <option value="month" <?php echo $period === 'month' ? 'selected' : ''; ?>>This Month</option>
                <option value="quarter" <?php echo $period === 'quarter' ? 'selected' : ''; ?>>This Quarter</option>
                <option value="year" <?php echo $period === 'year' ? 'selected' : ''; ?>>This Year</option>
            </select>
        </div>
    </div>
    
    <!-- Key Metrics -->
    <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($metrics['total_employees']); ?></div>
            <div style="margin-top: 5px; opacity: 0.9;">Total Employees</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($metrics['attendance_rate'], 1); ?>%</div>
            <div style="margin-top: 5px; opacity: 0.9;">Attendance Rate</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($metrics['leave_days']); ?></div>
            <div style="margin-top: 5px; opacity: 0.9;">Leave Days</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: 28px; font-weight: 600;"><?php echo formatCurrency($metrics['payroll_cost']); ?></div>
            <div style="margin-top: 5px; opacity: 0.9;">Payroll Cost</div>
        </div>
    </div>
    
    <!-- Secondary Metrics -->
    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px;">
        <div class="card" style="padding: 20px; text-align: center;">
            <div style="font-size: 28px; font-weight: 600; color: var(--primary-color);">
                <?php echo formatCurrency($metrics['avg_salary']); ?>
            </div>
            <div style="margin-top: 5px; color: var(--text-secondary);">Average Salary</div>
        </div>
        <div class="card" style="padding: 20px; text-align: center;">
            <div style="font-size: 28px; font-weight: 600; color: var(--warning-color);">
                <?php echo number_format($metrics['pending_leaves']); ?>
            </div>
            <div style="margin-top: 5px; color: var(--text-secondary);">Pending Leaves</div>
        </div>
        <div class="card" style="padding: 20px; text-align: center;">
            <div style="font-size: 28px; font-weight: 600; color: var(--success-color);">
                <?php echo number_format($metrics['recent_hires']); ?>
            </div>
            <div style="margin-top: 5px; color: var(--text-secondary);">Recent Hires (30 days)</div>
        </div>
    </div>
    
    <!-- Department Performance -->
    <?php if (count($deptPerformance) > 0): ?>
    <div class="card" style="margin-bottom: 30px;">
        <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Department Performance</h3>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Department</th>
                    <th>Employees</th>
                    <th>Present Count</th>
                    <th>Attendance Rate</th>
                    <th>Performance</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($deptPerformance as $dept): 
                    $deptRate = $dept['total_attendance'] > 0 ? ($dept['present_count'] / $dept['total_attendance']) * 100 : 0;
                    $performance = $deptRate >= 90 ? 'Excellent' : ($deptRate >= 75 ? 'Good' : ($deptRate >= 60 ? 'Average' : 'Needs Improvement'));
                    $performanceColor = $deptRate >= 90 ? 'var(--success-color)' : ($deptRate >= 75 ? 'var(--primary-color)' : ($deptRate >= 60 ? 'var(--warning-color)' : 'var(--error-color)'));
                ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($dept['department_name']); ?></strong></td>
                    <td><?php echo number_format($dept['employees']); ?></td>
                    <td><?php echo number_format($dept['present_count']); ?></td>
                    <td>
                        <span style="color: <?php echo $performanceColor; ?>; font-weight: 600;">
                            <?php echo number_format($deptRate, 1); ?>%
                        </span>
                    </td>
                    <td>
                        <span style="color: <?php echo $performanceColor; ?>;">
                            <?php echo $performance; ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
    
    <!-- Monthly Trends -->
    <?php if (count($monthlyTrends) > 0): ?>
    <div class="card">
        <h3 style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">6-Month Attendance Trend</h3>
        <div style="display: flex; flex-direction: column; gap: 15px;">
            <?php foreach ($monthlyTrends as $trend): 
                $rate = $trend['total'] > 0 ? ($trend['present'] / $trend['total']) * 100 : 0;
            ?>
            <div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                    <span><strong><?php echo date('M Y', strtotime($trend['month'] . '-01')); ?></strong></span>
                    <span style="font-weight: 600;">
                        <?php echo number_format($trend['present']); ?> / <?php echo number_format($trend['total']); ?> 
                        (<?php echo number_format($rate, 1); ?>%)
                    </span>
                </div>
                <div style="height: 12px; background: #e5e7eb; border-radius: 6px; overflow: hidden;">
                    <div style="height: 100%; width: <?php echo $rate; ?>%; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);"></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

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

