<?php
session_start();
include 'config.php';

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

$employee_id = $_SESSION['user_id'];
$current_week = date('W');
$current_year = date('Y');

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($_POST['kpi'] as $kpi_id => $values) {
        $current_value = $values['value'];
        $comments = isset($values['comments']) ? $conn->real_escape_string($values['comments']) : '';
        
        // Check if entry exists for this week
        $check_sql = "SELECT id FROM employee_kpis 
                     WHERE employee_id = ? AND kpi_id = ? 
                     AND week_number = ? AND year = ?";
        $stmt = $conn->prepare($check_sql);
        if ($stmt === false) {
            die("Error preparing statement: " . $conn->error);
        }
        $stmt->bind_param("iiii", $employee_id, $kpi_id, $current_week, $current_year);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // Update existing entry
            $update_sql = "UPDATE employee_kpis 
                          SET current_value = ?, comments = ?, last_updated = NOW() 
                          WHERE employee_id = ? AND kpi_id = ? 
                          AND week_number = ? AND year = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("dsiiii", $current_value, $comments, $employee_id, $kpi_id, $current_week, $current_year);
        } else {
            // Insert new entry
            $insert_sql = "INSERT INTO employee_kpis 
                          (employee_id, kpi_id, current_value, comments, week_number, year) 
                          VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("iidsii", $employee_id, $kpi_id, $current_value, $comments, $current_week, $current_year);
        }
        
        if (!$stmt->execute()) {
            $_SESSION['error'] = "Error updating performance data: " . $conn->error;
        } else {
            $_SESSION['success'] = "Your performance data has been updated successfully!";
        }
    }
    
    header("Location: employee_performance.php");
    exit();
}

// Get employee's KPIs for the current week
$kpi_sql = "SELECT k.id, k.kpi_title, k.target_value, k.measuring_unit, 
                   k.scale, k.start_value, k.progress_limit,
                   ek.current_value, ek.comments
            FROM kpi k
            LEFT JOIN employee_kpis ek ON k.id = ek.kpi_id 
                AND ek.employee_id = ? 
                AND ek.week_number = ? 
                AND ek.year = ?
            WHERE EXISTS (
                SELECT 1 FROM employee_kpis 
                WHERE employee_id = ? AND kpi_id = k.id
            )";
$stmt = $conn->prepare($kpi_sql);
if ($stmt === false) {
    die("Error preparing statement: " . $conn->error);
}
$stmt->bind_param("iiii", $employee_id, $current_week, $current_year, $employee_id);
$stmt->execute();
$kpi_results = $stmt->get_result();

// Get performance history (last 12 entries)
$history_sql = "SELECT k.kpi_title, ek.current_value, ek.week_number, ek.year, 
                       ek.last_updated, k.target_value, k.measuring_unit
                FROM employee_kpis ek
                JOIN kpi k ON ek.kpi_id = k.id
                WHERE ek.employee_id = ?
                ORDER BY ek.year DESC, ek.week_number DESC, k.kpi_title
                LIMIT 12";
$stmt_history = $conn->prepare($history_sql);
if ($stmt_history === false) {
    die("Error preparing history statement: " . $conn->error);
}
$stmt_history->bind_param("i", $employee_id);
$stmt_history->execute();
$history_results = $stmt_history->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Performance Tracker</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        .sidebar {
            width: 250px;
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            background: #2c3e50;
            color: white;
            padding: 20px;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            transition: all 0.3s;
            z-index: 1000;
        }
        .sidebar.collapsed {
            left: -250px;
        }
        .sidebar h2 {
            color: white;
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        .sidebar a {
            display: block;
            color: white;
            padding: 10px 15px;
            margin-bottom: 5px;
            border-radius: 5px;
            text-decoration: none;
            transition: all 0.3s;
        }
        .sidebar a:hover {
            background: #34495e;
            color: #1abc9c;
        }
        .sidebar a i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        .sidebar a.text-danger {
            color: #e74c3c;
        }
        .sidebar a.text-danger:hover {
            background: #e74c3c;
            color: white;
        }
        .content {
            margin-left: 250px;
            transition: all 0.3s;
        }
        .content.expanded {
            margin-left: 0;
        }
        .performance-card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        .card-header {
            background-color: #2c3e50;
            color: white;
            border-radius: 10px 10px 0 0 !important;
            padding: 15px 20px;
        }
        .kpi-item {
            padding: 15px;
            margin-bottom: 15px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .progress {
            height: 20px;
            border-radius: 10px;
            background-color: #e9ecef;
        }
        .progress-bar {
            background-color: #1abc9c;
            transition: width 0.6s ease;
        }
        .history-item {
            border-left: 4px solid #1abc9c;
            padding-left: 15px;
            margin-bottom: 10px;
        }
        .target-badge {
            background-color: #3498db;
        }
        .week-indicator {
            background-color: #2c3e50;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.9rem;
        }
        .toggle-sidebar {
            position: fixed;
            left: 10px;
            top: 10px;
            z-index: 1001;
            background: #2c3e50;
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: none;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        @media (max-width: 992px) {
            .sidebar {
                left: -250px;
            }
            .sidebar.collapsed {
                left: 0;
            }
            .content {
                margin-left: 0;
            }
            .toggle-sidebar {
                display: flex;
            }
        }
    </style>
</head>
<body>
    <button class="toggle-sidebar" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <div class="sidebar" id="sidebar">
        <h2>Employee Portal</h2>
        <a href="dashboard_employee.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="personalinfo.php"><i class="fas fa-user"></i> Personal Info</a>
        <a href="employee_grievance.php"><i class="fas fa-comment-dots"></i> Grievance Portal</a>
        <a href="apply_leave.php"><i class="fas fa-calendar-alt"></i> Leave Portal</a>
        <a href="performance_management.php"><i class="fas fa-chart-line"></i> Performance</a>
        <a href="submit_habit_response.php"><i class="fas fa-heartbeat"></i> Habits</a>
        <a href="payslips.php"><i class="fas fa-file-invoice-dollar"></i> Payslips</a>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <div class="content" id="content">
        <div class="container py-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="mb-0">My Performance Tracker</h1>
                <span class="week-indicator">
                    Week <?php echo $current_week; ?>, <?php echo $current_year; ?>
                </span>
            </div>

            <?php if (isset($_SESSION['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if (isset($_SESSION['error'])): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <div class="row">
                <div class="col-lg-8">
                    <div class="performance-card card mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h3 class="mb-0"><i class="fas fa-tasks me-2"></i>This Week's KPIs</h3>
                            <small>Due: <?php echo date('F j', strtotime('next sunday')); ?></small>
                        </div>
                        <div class="card-body">
                            <?php if ($kpi_results->num_rows > 0): ?>
                                <form method="POST">
                                    <?php while ($kpi = $kpi_results->fetch_assoc()): ?>
                                        <div class="kpi-item">
                                            <h4><?php echo htmlspecialchars($kpi['kpi_title']); ?></h4>
                                            
                                            <div class="row align-items-center mb-3">
                                                <div class="col-md-6">
                                                    <div class="d-flex justify-content-between mb-2">
                                                        <span>Target:</span>
                                                        <span class="badge target-badge">
                                                            <?php echo $kpi['target_value'] . ' ' . htmlspecialchars($kpi['measuring_unit']); ?>
                                                        </span>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label for="value_<?php echo $kpi['id']; ?>" class="form-label">
                                                            Current Achievement:
                                                        </label>
                                                        <input type="number" step="0.01" 
                                                               class="form-control" 
                                                               id="value_<?php echo $kpi['id']; ?>" 
                                                               name="kpi[<?php echo $kpi['id']; ?>][value]"
                                                               value="<?php echo $kpi['current_value'] ?? $kpi['start_value']; ?>"
                                                               required
                                                               data-target="<?php echo $kpi['target_value']; ?>"
                                                               data-limit="<?php echo $kpi['progress_limit']; ?>">
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <div class="progress-container">
                                                        <div class="d-flex justify-content-between mb-1">
                                                            <small>Progress:</small>
                                                            <small id="progress-text_<?php echo $kpi['id']; ?>">
                                                                <?php 
                                                                $progress = 0;
                                                                if (isset($kpi['current_value']) && $kpi['target_value'] > 0) {
                                                                    $progress = ($kpi['current_value'] / $kpi['target_value']) * 100;
                                                                    if ($kpi['progress_limit'] == 'Limit to 100%' && $progress > 100) {
                                                                        $progress = 100;
                                                                    }
                                                                }
                                                                echo round($progress, 2) . '%';
                                                                ?>
                                                            </small>
                                                        </div>
                                                        <div class="progress" id="progress_<?php echo $kpi['id']; ?>">
                                                            <div class="progress-bar" 
                                                                 role="progressbar" 
                                                                 style="width: <?php echo $progress; ?>%" 
                                                                 aria-valuenow="<?php echo $progress; ?>" 
                                                                 aria-valuemin="0" 
                                                                 aria-valuemax="<?php echo $kpi['progress_limit'] == 'Limit to 100%' ? 100 : ''; ?>">
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="mt-3">
                                                        <label for="comments_<?php echo $kpi['id']; ?>" class="form-label">
                                                            <i class="fas fa-comment me-1"></i>Comments:
                                                        </label>
                                                        <textarea class="form-control" 
                                                                  id="comments_<?php echo $kpi['id']; ?>" 
                                                                  name="kpi[<?php echo $kpi['id']; ?>][comments]"
                                                                  rows="2" placeholder="Any notes about this KPI..."><?php echo htmlspecialchars($kpi['comments'] ?? ''); ?></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endwhile; ?>
                                    
                                    <div class="text-center mt-4">
                                        <button type="submit" class="btn btn-primary btn-lg px-4 py-2">
                                            <i class="fas fa-save me-2"></i>Submit Weekly Update
                                        </button>
                                    </div>
                                </form>
                            <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    You don't have any KPIs assigned for tracking yet. Please check with your manager.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <div class="performance-card card mb-4">
                        <div class="card-header">
                            <h3 class="mb-0"><i class="fas fa-chart-line me-2"></i>Recent Progress</h3>
                        </div>
                        <div class="card-body">
                            <?php if ($history_results->num_rows > 0): ?>
                                <?php 
                                $current_week_shown = false;
                                while ($history = $history_results->fetch_assoc()): 
                                    $progress = ($history['target_value'] > 0) ? ($history['current_value'] / $history['target_value']) * 100 : 0;
                                ?>
                                    <div class="history-item">
                                        <div class="d-flex justify-content-between">
                                            <strong><?php echo htmlspecialchars($history['kpi_title']); ?></strong>
                                            <small>W<?php echo $history['week_number']; ?></small>
                                        </div>
                                        <div class="d-flex justify-content-between mb-1">
                                            <span><?php echo $history['current_value']; ?> <?php echo htmlspecialchars($history['measuring_unit']); ?></span>
                                            <span><?php echo round($progress, 1); ?>%</span>
                                        </div>
                                        <div class="progress" style="height: 8px;">
                                            <div class="progress-bar" style="width: <?php echo $progress; ?>%"></div>
                                        </div>
                                        <small class="text-muted">
                                            <?php echo date('M j', strtotime($history['last_updated'])); ?>
                                        </small>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    No performance history recorded yet.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="performance-card card">
                        <div class="card-header">
                            <h3 class="mb-0"><i class="fas fa-lightbulb me-2"></i>Tips for Success</h3>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-success mb-3">
                                <i class="fas fa-check-circle me-2"></i>
                                <strong>Update weekly</strong> - Regular updates help track progress accurately
                            </div>
                            <div class="alert alert-info mb-3">
                                <i class="fas fa-check-circle me-2"></i>
                                <strong>Be honest</strong> - Accurate data helps identify areas for improvement
                            </div>
                            <div class="alert alert-warning mb-3">
                                <i class="fas fa-check-circle me-2"></i>
                                <strong>Add comments</strong> - Context helps your manager understand challenges
                            </div>
                            <div class="alert alert-primary">
                                <i class="fas fa-check-circle me-2"></i>
                                <strong>Review trends</strong> - Check your progress history to spot patterns
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-calculate progress when value changes
        document.querySelectorAll('input[type="number"]').forEach(input => {
            input.addEventListener('input', function() {
                const kpiId = this.name.match(/\[(\d+)\]\[value\]/)[1];
                const targetValue = parseFloat(this.dataset.target);
                const currentValue = parseFloat(this.value) || 0;
                const progressLimit = this.dataset.limit;
                
                let progress = 0;
                if (targetValue > 0) {
                    progress = (currentValue / targetValue) * 100;
                    if (progressLimit === 'Limit to 100%' && progress > 100) {
                        progress = 100;
                    }
                }
                
                const progressBar = document.querySelector(`#progress_${kpiId} .progress-bar`);
                const progressText = document.querySelector(`#progress-text_${kpiId}`);
                
                progressBar.style.width = `${progress}%`;
                progressBar.setAttribute('aria-valuenow', progress);
                progressText.textContent = `${progress.toFixed(2)}%`;
            });
        });
        
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('collapsed');
            document.getElementById('content').classList.toggle('expanded');
        }
        
        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function(event) {
            const sidebar = document.getElementById('sidebar');
            const toggleBtn = document.querySelector('.toggle-sidebar');
            
            if (window.innerWidth <= 992 && 
                !sidebar.contains(event.target) && 
                event.target !== toggleBtn && 
                !toggleBtn.contains(event.target)) {
                sidebar.classList.add('collapsed');
                document.getElementById('content').classList.add('expanded');
            }
        });
    </script>
</body>
</html>