<?php
/**
 * Enterprise HRM ERP System - HR Admin Dashboard
 * Can only see their own employees and data
 */

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

// Only HR Admin can access
if (!isHRAdmin() || isSuperAdmin()) {
    $_SESSION['error'] = 'Access denied. HR Admin only.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'HR Admin Dashboard';
$currentModule = 'dashboard';

$siteId = getCurrentSiteId();
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Validate month and year
if ($selectedMonth < 1 || $selectedMonth > 12) {
    $selectedMonth = (int)date('m');
}
if ($selectedYear < 2020 || $selectedYear > 2100) {
    $selectedYear = (int)date('Y');
}

// Get statistics for selected month/year (only for this HR Admin's site)
try {
    $db = getDB();
    
    // Total Active Employees (only in this site)
    $stmt = $db->prepare("SELECT COUNT(*) FROM employees WHERE site_id = ? AND employment_status = 'active'");
    $stmt->execute([$siteId]);
    $totalEmployees = $stmt->fetchColumn();
    
    // Month-wise Attendance Summary (only this site)
    $stmt = $db->prepare("
        SELECT 
            COUNT(DISTINCT employee_id) as total_employees,
            SUM(CASE WHEN attendance_status = 'present' THEN 1 ELSE 0 END) as present_days,
            SUM(CASE WHEN attendance_status = 'absent' THEN 1 ELSE 0 END) as absent_days,
            SUM(CASE WHEN attendance_status IN ('on_leave', 'half_day') THEN 1 ELSE 0 END) as leave_days
        FROM attendance 
        WHERE site_id = ? AND MONTH(attendance_date) = ? AND YEAR(attendance_date) = ?
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $attendanceSummary = $stmt->fetch();
    
    // Earned CTC (from payroll for the month, only this site)
    $stmt = $db->prepare("
        SELECT 
            SUM(gross_salary) as earned_ctc,
            SUM(net_salary) as net_salary,
            SUM(total_earnings) as total_earnings,
            SUM(total_deductions) as total_deductions
        FROM payroll_records pr
        INNER JOIN payroll_periods pp ON pr.period_id = pp.period_id
        WHERE pr.site_id = ? AND MONTH(pp.start_date) = ? AND YEAR(pp.start_date) = ?
        AND pr.payroll_status IN ('calculated', 'approved', 'paid', 'locked')
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $payrollSummary = $stmt->fetch();
    
    // PF/ESIC Summary (only this site)
    $stmt = $db->prepare("
        SELECT 
            SUM(CASE WHEN sc.component_code = 'PF' THEN pd.amount ELSE 0 END) as pf_amount,
            SUM(CASE WHEN sc.component_code = 'ESIC' THEN pd.amount ELSE 0 END) as esic_amount
        FROM payroll_details pd
        INNER JOIN payroll_records pr ON pd.payroll_id = pr.payroll_id
        INNER JOIN payroll_periods pp ON pr.period_id = pp.period_id
        INNER JOIN salary_components sc ON pd.component_id = sc.component_id
        WHERE pr.site_id = ? AND MONTH(pp.start_date) = ? AND YEAR(pp.start_date) = ?
        AND sc.component_type = 'deduction'
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $deductionSummary = $stmt->fetch();
    
    // Pending Leave Applications (only this site)
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM leave_applications 
        WHERE site_id = ? AND application_status = 'pending'
    ");
    $stmt->execute([$siteId]);
    $pendingLeaves = $stmt->fetchColumn();
    
    // Today's Present Count (only this site)
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM attendance 
        WHERE site_id = ? AND attendance_date = CURDATE() AND attendance_status = 'present'
    ");
    $stmt->execute([$siteId]);
    $todayPresent = $stmt->fetchColumn();
    
} catch (Exception $e) {
    error_log("HR Admin Dashboard error: " . $e->getMessage());
    $totalEmployees = 0;
    $attendanceSummary = ['total_employees' => 0, 'present_days' => 0, 'absent_days' => 0, 'leave_days' => 0];
    $payrollSummary = ['earned_ctc' => 0, 'net_salary' => 0, 'total_earnings' => 0, 'total_deductions' => 0];
    $deductionSummary = ['pf_amount' => 0, 'esic_amount' => 0];
    $pendingLeaves = 0;
    $todayPresent = 0;
}

// Get site name
$siteName = $_SESSION['site_name'] ?? 'Site';

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">HR Admin Dashboard - <?php echo htmlspecialchars($siteName); ?></h2>
        <div style="display: flex; gap: 10px; align-items: center;">
            <select id="monthSelect" class="form-control" style="width: 120px;" onchange="updateDashboard()">
                <?php for ($m = 1; $m <= 12; $m++): ?>
                <option value="<?php echo $m; ?>" <?php echo $selectedMonth == $m ? 'selected' : ''; ?>>
                    <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                </option>
                <?php endfor; ?>
            </select>
            <select id="yearSelect" class="form-control" style="width: 100px;" onchange="updateDashboard()">
                <?php for ($y = date('Y') - 2; $y <= date('Y') + 1; $y++): ?>
                <option value="<?php echo $y; ?>" <?php echo $selectedYear == $y ? 'selected' : ''; ?>>
                    <?php echo $y; ?>
                </option>
                <?php endfor; ?>
            </select>
        </div>
    </div>
    
    <!-- Key Metrics -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 20px;">
        <div class="stat-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
            <div class="stat-icon">💰</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo formatCurrency($payrollSummary['earned_ctc'] ?? 0); ?></div>
                <div class="stat-label">Earned CTC</div>
            </div>
        </div>
        
        <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
            <div class="stat-icon">💵</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo formatCurrency($payrollSummary['net_salary'] ?? 0); ?></div>
                <div class="stat-label">Net Salary</div>
            </div>
        </div>
        
        <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white;">
            <div class="stat-icon">👥</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo number_format($totalEmployees); ?></div>
                <div class="stat-label">My Employees</div>
            </div>
        </div>
        
        <div class="stat-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); color: white;">
            <div class="stat-icon">✓</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo number_format($attendanceSummary['present_days'] ?? 0); ?></div>
                <div class="stat-label">Present Days</div>
            </div>
        </div>
        
        <div class="stat-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); color: white;">
            <div class="stat-icon">📅</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo number_format($attendanceSummary['leave_days'] ?? 0); ?></div>
                <div class="stat-label">Leave Days</div>
            </div>
        </div>
        
        <div class="stat-card" style="background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); color: white;">
            <div class="stat-icon">⏰</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo number_format($todayPresent); ?></div>
                <div class="stat-label">Today Present</div>
            </div>
        </div>
    </div>
    
    <!-- Quick Action Buttons -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 20px;">Quick Actions</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
            <a href="<?php echo BASE_URL; ?>/modules/employee/list.php" class="quick-action-btn">
                <div class="quick-action-icon">👤</div>
                <div class="quick-action-label">Employees</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/modules/attendance/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="quick-action-btn">
                <div class="quick-action-icon">⏰</div>
                <div class="quick-action-label">Attendance</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/modules/payroll/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="quick-action-btn">
                <div class="quick-action-icon">💰</div>
                <div class="quick-action-label">Payroll</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/modules/leave/list.php" 
               class="quick-action-btn">
                <div class="quick-action-icon">📅</div>
                <div class="quick-action-label">Leave</div>
            </a>
        </div>
    </div>
    
    <!-- Attendance Summary Table -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Attendance Summary - <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?></h3>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Metric</th>
                    <th style="text-align: right;">Count</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><strong>Total Employees</strong></td>
                    <td style="text-align: right;"><strong><?php echo number_format($totalEmployees); ?></strong></td>
                </tr>
                <tr>
                    <td>Present Days</td>
                    <td style="text-align: right;"><?php echo number_format($attendanceSummary['present_days'] ?? 0); ?></td>
                </tr>
                <tr>
                    <td>Absent Days</td>
                    <td style="text-align: right;"><?php echo number_format($attendanceSummary['absent_days'] ?? 0); ?></td>
                </tr>
                <tr>
                    <td>Leave Days</td>
                    <td style="text-align: right;"><?php echo number_format($attendanceSummary['leave_days'] ?? 0); ?></td>
                </tr>
                <tr>
                    <td>Today's Present</td>
                    <td style="text-align: right;"><?php echo number_format($todayPresent); ?></td>
                </tr>
                <tr>
                    <td>Pending Leaves</td>
                    <td style="text-align: right;"><?php echo number_format($pendingLeaves); ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<style>
.stat-card {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 15px;
    transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.stat-icon {
    font-size: 40px;
    opacity: 0.9;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 12px;
    opacity: 0.9;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.quick-action-btn {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    text-align: center;
    text-decoration: none;
    color: var(--text-primary);
    transition: all 0.2s;
    border: 2px solid transparent;
}

.quick-action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    border-color: var(--primary-color);
    color: var(--primary-color);
}

.quick-action-icon {
    font-size: 36px;
    margin-bottom: 10px;
}

.quick-action-label {
    font-size: 14px;
    font-weight: 500;
}
</style>

<script>
function updateDashboard() {
    const month = document.getElementById('monthSelect').value;
    const year = document.getElementById('yearSelect').value;
    window.location.href = '?month=' + month + '&year=' + year;
}
</script>

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

