<?php
/**
 * Enterprise HRM ERP System - Employee Dashboard
 * Employees can only see their own data
 */

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

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

$pageTitle = 'My Dashboard';
$currentModule = 'dashboard';

$employeeId = getCurrentEmployeeId();
$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 employee details and statistics
try {
    $db = getDB();
    
    // Get employee details
    $stmt = $db->prepare("
        SELECT e.*, d.department_name, des.designation_name, s.site_name
        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
        LEFT JOIN sites s ON e.site_id = s.site_id
        WHERE e.employee_id = ?
    ");
    $stmt->execute([$employeeId]);
    $employee = $stmt->fetch();
    
    if (!$employee) {
        $_SESSION['error'] = 'Employee record not found.';
        header('Location: ' . BASE_URL . '/logout.php');
        exit;
    }
    
    // My Attendance Summary (this month)
    $stmt = $db->prepare("
        SELECT 
            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 employee_id = ? AND MONTH(attendance_date) = ? AND YEAR(attendance_date) = ?
    ");
    $stmt->execute([$employeeId, $selectedMonth, $selectedYear]);
    $attendanceSummary = $stmt->fetch();
    
    // My Salary (this month)
    $stmt = $db->prepare("
        SELECT 
            pr.gross_salary,
            pr.net_salary,
            pr.total_earnings,
            pr.total_deductions,
            pp.start_date,
            pp.end_date
        FROM payroll_records pr
        INNER JOIN payroll_periods pp ON pr.period_id = pp.period_id
        WHERE pr.employee_id = ? AND MONTH(pp.start_date) = ? AND YEAR(pp.start_date) = ?
        AND pr.payroll_status IN ('calculated', 'approved', 'paid', 'locked')
        ORDER BY pp.start_date DESC
        LIMIT 1
    ");
    $stmt->execute([$employeeId, $selectedMonth, $selectedYear]);
    $salary = $stmt->fetch();
    
    // My Leave Applications
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM leave_applications 
        WHERE employee_id = ? AND application_status = 'pending'
    ");
    $stmt->execute([$employeeId]);
    $pendingLeaves = $stmt->fetchColumn();
    
    // My Leave Balance
    $stmt = $db->prepare("
        SELECT 
            SUM(CASE WHEN lt.leave_type_code = 'CL' THEN la.leave_days ELSE 0 END) as cl_used,
            SUM(CASE WHEN lt.leave_type_code = 'SL' THEN la.leave_days ELSE 0 END) as sl_used,
            SUM(CASE WHEN lt.leave_type_code = 'PL' THEN la.leave_days ELSE 0 END) as pl_used
        FROM leave_applications la
        INNER JOIN leave_types lt ON la.leave_type_id = lt.leave_type_id
        WHERE la.employee_id = ? AND la.application_status = 'approved'
        AND YEAR(la.leave_start_date) = ?
    ");
    $stmt->execute([$employeeId, $selectedYear]);
    $leaveUsed = $stmt->fetch();
    
    // Today's Attendance
    $stmt = $db->prepare("
        SELECT attendance_status, check_in_time, check_out_time
        FROM attendance 
        WHERE employee_id = ? AND attendance_date = CURDATE()
    ");
    $stmt->execute([$employeeId]);
    $todayAttendance = $stmt->fetch();
    
} catch (Exception $e) {
    error_log("Employee Dashboard error: " . $e->getMessage());
    $employee = null;
    $attendanceSummary = ['present_days' => 0, 'absent_days' => 0, 'leave_days' => 0];
    $salary = null;
    $pendingLeaves = 0;
    $leaveUsed = ['cl_used' => 0, 'sl_used' => 0, 'pl_used' => 0];
    $todayAttendance = null;
}

if (!$employee) {
    $_SESSION['error'] = 'Employee record not found.';
    header('Location: ' . BASE_URL . '/logout.php');
    exit;
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">My Dashboard</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>
    
    <!-- Employee Info -->
    <div style="background: white; padding: 20px; border-radius: 8px; margin-top: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <h3 style="margin-bottom: 15px;">My Information</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
            <div>
                <strong>Employee ID:</strong> <?php echo htmlspecialchars($employee['employee_code']); ?>
            </div>
            <div>
                <strong>Name:</strong> <?php echo htmlspecialchars($employee['first_name'] . ' ' . $employee['last_name']); ?>
            </div>
            <div>
                <strong>Department:</strong> <?php echo htmlspecialchars($employee['department_name'] ?? 'N/A'); ?>
            </div>
            <div>
                <strong>Designation:</strong> <?php echo htmlspecialchars($employee['designation_name'] ?? 'N/A'); ?>
            </div>
            <div>
                <strong>Site:</strong> <?php echo htmlspecialchars($employee['site_name'] ?? 'N/A'); ?>
            </div>
            <div>
                <strong>Status:</strong> 
                <span class="badge badge-<?php echo $employee['employment_status'] === 'active' ? 'success' : 'danger'; ?>">
                    <?php echo ucfirst($employee['employment_status']); ?>
                </span>
            </div>
        </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($salary['net_salary'] ?? 0); ?></div>
                <div class="stat-label">This Month Salary</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 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, #4facfe 0%, #00f2fe 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, #43e97b 0%, #38f9d7 100%); color: white;">
            <div class="stat-icon">⏰</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo $todayAttendance ? ucfirst($todayAttendance['attendance_status']) : 'N/A'; ?></div>
                <div class="stat-label">Today Status</div>
            </div>
        </div>
    </div>
    
    <!-- Quick Actions -->
    <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/attendance/my_attendance.php" class="quick-action-btn">
                <div class="quick-action-icon">⏰</div>
                <div class="quick-action-label">My Attendance</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/modules/leave/my_leaves.php" class="quick-action-btn">
                <div class="quick-action-icon">📅</div>
                <div class="quick-action-label">My Leaves</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/modules/payroll/my_payslip.php" class="quick-action-btn">
                <div class="quick-action-icon">💰</div>
                <div class="quick-action-label">My Payslip</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/modules/employee/my_profile.php" class="quick-action-btn">
                <div class="quick-action-icon">👤</div>
                <div class="quick-action-label">My Profile</div>
            </a>
        </div>
    </div>
    
    <!-- Attendance Summary -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">My Attendance - <?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>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>Pending Leave Applications</td>
                    <td style="text-align: right;"><?php echo number_format($pendingLeaves); ?></td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <!-- Today's Attendance -->
    <?php if ($todayAttendance): ?>
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Today's Attendance</h3>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Status</th>
                    <th>Check In</th>
                    <th>Check Out</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <span class="badge badge-<?php echo $todayAttendance['attendance_status'] === 'present' ? 'success' : 'warning'; ?>">
                            <?php echo ucfirst($todayAttendance['attendance_status']); ?>
                        </span>
                    </td>
                    <td><?php echo $todayAttendance['check_in_time'] ? formatTime($todayAttendance['check_in_time']) : 'N/A'; ?></td>
                    <td><?php echo $todayAttendance['check_out_time'] ? formatTime($todayAttendance['check_out_time']) : 'N/A'; ?></td>
                </tr>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</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'; ?>

