<?php
// Enable error reporting for debugging
ini_set('display_errors', 0); // Set to 0 to prevent errors from displaying to users
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log'); // Ensure this path is writable

session_start();

// Include database configuration
if (!file_exists('config.php')) {
    error_log("Config file missing: config.php");
    $_SESSION['error_message'] = "Configuration file not found. Please contact the administrator.";
    header("Location: login.php");
    exit();
}
require_once 'config.php';

// Verify database connection
if (!isset($conn) || $conn->connect_error) {
    error_log("Database connection failed: " . ($conn ? $conn->connect_error : 'Connection not initialized'));
    $_SESSION['error_message'] = "Unable to connect to the database. Please contact the administrator.";
    header("Location: login.php");
    exit();
}

// Ensure only Employees can access this page
if (!isset($_SESSION['user_id'], $_SESSION['role']) || $_SESSION['role'] !== 'employee') {
    error_log("Unauthorized access attempt. Session data: user_id=" . ($_SESSION['user_id'] ?? 'not set') . ", role=" . ($_SESSION['role'] ?? 'not set'));
    $_SESSION['error_message'] = "Unauthorized access.";
    header("Location: login.php");
    exit();
}

$employee_id = (int)$_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Unknown User';
error_log("All KPIs page accessed by ID: $employee_id, Username: $username");

// Function to check table existence
function tableExists($conn, $table) {
    try {
        $result = $conn->query("SHOW TABLES LIKE '$table'");
        return $result && $result->num_rows > 0;
    } catch (Exception $e) {
        error_log("Table existence check failed for '$table': " . $e->getMessage());
        return false;
    }
}

// Function to check if a column exists in a table
function columnExists($conn, $table, $column) {
    try {
        $result = $conn->query("SHOW COLUMNS FROM `$table` LIKE '$column'");
        return $result && $result->num_rows > 0;
    } catch (Exception $e) {
        error_log("Column existence check failed for '$table.$column': " . $e->getMessage());
        return false;
    }
}

// Check required tables
$required_tables = ['employee_kpis', 'kpi', 'kpi_updates', 'users', 'notifications'];
$missing_tables = [];
foreach ($required_tables as $table) {
    if (!tableExists($conn, $table)) {
        $missing_tables[] = $table;
    }
}
if (!empty($missing_tables)) {
    error_log("Missing database tables: " . implode(', ', $missing_tables));
    $_SESSION['error_message'] = "Required database tables missing: " . implode(', ', $missing_tables);
    header("Location: dashboard_employee.php");
    exit();
}

// Handle KPI acceptance
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'accept_kpi') {
    $kpi_id = (int)($_POST['kpi_id'] ?? 0);
    if ($kpi_id <= 0) {
        error_log("Invalid KPI ID: $kpi_id");
        $_SESSION['error_message'] = "Invalid KPI ID.";
    } else {
        try {
            // Verify KPI belongs to employee
            $check_sql = "SELECT kpi_id FROM employee_kpis WHERE kpi_id = ? AND employee_id = ?";
            $stmt_check = $conn->prepare($check_sql);
            if (!$stmt_check) {
                error_log("KPI check query preparation failed: " . $conn->error);
                $_SESSION['error_message'] = "System error. Please try again later.";
            } else {
                $stmt_check->bind_param("ii", $kpi_id, $employee_id);
                if (!$stmt_check->execute()) {
                    error_log("KPI check query execution failed: " . $stmt_check->error);
                    $_SESSION['error_message'] = "Failed to validate KPI.";
                } else {
                    $result = $stmt_check->get_result();
                    if ($result->num_rows === 0) {
                        error_log("KPI ID $kpi_id not found for employee ID $employee_id");
                        $_SESSION['error_message'] = "KPI not found or not assigned to you.";
                    } else {
                        // Update KPI status
                        $update_sql = "UPDATE employee_kpis SET status = 'Accepted' WHERE kpi_id = ? AND employee_id = ?";
                        $stmt_update = $conn->prepare($update_sql);
                        if (!$stmt_update) {
                            error_log("KPI acceptance query preparation failed: " . $conn->error);
                            $_SESSION['error_message'] = "System error. Please try again later.";
                        } else {
                            $stmt_update->bind_param("ii", $kpi_id, $employee_id);
                            if ($stmt_update->execute()) {
                                // Notify admin
                                $message = "Employee {$username} (ID: {$employee_id}) has accepted KPI ID: {$kpi_id}";
                                $notif_sql = "INSERT INTO notifications (employee_id, message, status, created_at) 
                                              VALUES ((SELECT id FROM users WHERE role = 'superadmin' LIMIT 1), ?, 'Unread', NOW())";
                                $stmt_notif = $conn->prepare($notif_sql);
                                if ($stmt_notif) {
                                    $stmt_notif->bind_param("s", $message);
                                    $stmt_notif->execute() or error_log("Notification insert failed: " . $stmt_notif->error);
                                    $stmt_notif->close();
                                } else {
                                    error_log("Notification query preparation failed: " . $conn->error);
                                }
                                $_SESSION['success_message'] = "KPI accepted successfully!";
                            } else {
                                error_log("KPI acceptance update failed: " . $stmt_update->error);
                                $_SESSION['error_message'] = "Failed to accept KPI.";
                            }
                            $stmt_update->close();
                        }
                    }
                    $stmt_check->close();
                }
            }
        } catch (Exception $e) {
            error_log("Exception in KPI acceptance: " . $e->getMessage());
            $_SESSION['error_message'] = "An error occurred: " . htmlspecialchars($e->getMessage());
        }
    }
    header("Location: all_kpis.php");
    exit();
}

// Handle weekly KPI update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_kpi') {
    $kpi_id = (int)($_POST['kpi_id'] ?? 0);
    $weekly_update = (float)($_POST['weekly_update'] ?? -1);
    if ($kpi_id <= 0 || $weekly_update < 0) {
        error_log("Invalid KPI ID or update value: kpi_id=$kpi_id, weekly_update=$weekly_update");
        $_SESSION['error_message'] = "Invalid KPI ID or update value.";
    } else {
        try {
            // Verify KPI belongs to employee and is accepted
            $check_sql = "SELECT kpi_id FROM employee_kpis WHERE kpi_id = ? AND employee_id = ? AND status = 'Accepted'";
            $stmt_check = $conn->prepare($check_sql);
            if (!$stmt_check) {
                error_log("KPI update check query preparation failed: " . $conn->error);
                $_SESSION['error_message'] = "System error. Please try again later.";
            } else {
                $stmt_check->bind_param("ii", $kpi_id, $employee_id);
                if (!$stmt_check->execute()) {
                    error_log("KPI update check query execution failed: " . $stmt_check->error);
                    $_SESSION['error_message'] = "Failed to validate KPI.";
                } else {
                    $result = $stmt_check->get_result();
                    if ($result->num_rows === 0) {
                        error_log("KPI ID $kpi_id not found or not accepted for employee ID $employee_id");
                        $_SESSION['error_message'] = "KPI not found or not accepted.";
                    } else {
                        // Insert weekly update
                        $update_sql = "INSERT INTO kpi_updates (kpi_id, employee_id, update_value, update_date) 
                                       VALUES (?, ?, ?, NOW())";
                        $stmt_update = $conn->prepare($update_sql);
                        if (!$stmt_update) {
                            error_log("KPI update query preparation failed: " . $conn->error);
                            $_SESSION['error_message'] = "System error. Please try again later.";
                        } else {
                            $stmt_update->bind_param("iid", $kpi_id, $employee_id, $weekly_update);
                            if ($stmt_update->execute()) {
                                // Update current_value in employee_kpis
                                $current_sql = "UPDATE employee_kpis SET current_value = current_value + ?, last_updated = NOW() 
                                                WHERE kpi_id = ? AND employee_id = ?";
                                $stmt_current = $conn->prepare($current_sql);
                                if ($stmt_current) {
                                    $stmt_current->bind_param("dii", $weekly_update, $kpi_id, $employee_id);
                                    if ($stmt_current->execute()) {
                                        $_SESSION['success_message'] = "Weekly KPI updated successfully!";
                                    } else {
                                        error_log("Current value update failed: " . $stmt_current->error);
                                        $_SESSION['error_message'] = "Failed to update KPI current value.";
                                    }
                                    $stmt_current->close();
                                } else {
                                    error_log("Current value update query preparation failed: " . $conn->error);
                                    $_SESSION['error_message'] = "System error. Please try again later.";
                                }
                            } else {
                                error_log("KPI update insert failed: " . $stmt_update->error);
                                $_SESSION['error_message'] = "Failed to update KPI.";
                            }
                            $stmt_update->close();
                        }
                    }
                    $stmt_check->close();
                }
            }
        } catch (Exception $e) {
            error_log("Exception in KPI update: " . $e->getMessage());
            $_SESSION['error_message'] = "An error occurred: " . htmlspecialchars($e->getMessage());
        }
    }
    header("Location: all_kpis.php");
    exit();
}

// Fetch all KPIs for the employee
$kpi_results = false;
$kpi_error = null;
$status_column_exists = columnExists($conn, 'employee_kpis', 'status');
if (!in_array('employee_kpis', $missing_tables) && !in_array('kpi', $missing_tables)) {
    try {
        $status_select = $status_column_exists ? 'ek.status' : "'Pending' AS status";
        $kpi_sql = "SELECT k.kpi_title AS kpi_name, k.target_value AS target, 
                           ek.current_value, ek.kpi_id, 
                           CASE 
                               WHEN k.target_value = 0 THEN 0 
                               ELSE ROUND((ek.current_value/k.target_value)*100, 2) 
                           END AS progress,
                           $status_select
                    FROM employee_kpis ek
                    JOIN kpi k ON ek.kpi_id = k.id
                    WHERE ek.employee_id = ? 
                    ORDER BY ek.last_updated DESC";
        $stmt_kpi = $conn->prepare($kpi_sql);
        if (!$stmt_kpi) {
            $kpi_error = "KPI query preparation failed: " . $conn->error;
            error_log($kpi_error . " | Query: $kpi_sql");
        } else {
            $stmt_kpi->bind_param("i", $employee_id);
            if (!$stmt_kpi->execute()) {
                $kpi_error = "KPI query execution failed: " . $stmt_kpi->error;
                error_log($kpi_error . " | Query: $kpi_sql");
            } else {
                $kpi_results = $stmt_kpi->get_result();
                if ($kpi_results->num_rows === 0) {
                    $kpi_error = "No KPIs assigned yet.";
                    error_log($kpi_error);
                } else {
                    while ($kpi = $kpi_results->fetch_assoc()) {
                        error_log("KPI fetched: ID={$kpi['kpi_id']}, Name={$kpi['kpi_name']}, Status=" . ($kpi['status'] ?? 'null'));
                    }
                    $kpi_results->data_seek(0); // Reset result pointer for HTML rendering
                }
            }
            $stmt_kpi->close();
        }
    } catch (Exception $e) {
        $kpi_error = "Exception in KPI query: " . $e->getMessage();
        error_log($kpi_error . " | Query: $kpi_sql");
    }
} else {
    $kpi_error = "KPI data unavailable due to missing tables: " . implode(', ', $missing_tables);
    error_log($kpi_error);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>All KPIs</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background: #2c3e50; color: #fff; padding: 15px; transition: transform 0.3s ease; position: fixed; top: 0; bottom: 0; z-index: 1000; transform: translateX(-250px); }
        .sidebar.active { transform: translateX(0); }
        .sidebar h2 { font-size: 1rem; margin-bottom: 15px; }
        .sidebar a { color: #fff; text-decoration: none; padding: 8px 10px; display: block; border-radius: 4px; margin-bottom: 5px; font-size: 0.9rem; }
        .sidebar a:hover { background: #1abc9c; }
        .sidebar a.active { background: #1abc9c; }
        .hamburger { position: fixed; top: 10px; left: 10px; z-index: 1100; background: #2c3e50; color: #fff; border: none; padding: 8px; border-radius: 4px; cursor: pointer; }
        .content { flex: 1; padding: 15px; margin-left: 0; transition: margin-left 0.3s ease; }
        .content.active { margin-left: 250px; }
        h1 { font-size: 1.5rem; margin-bottom: 15px; color: #333; }
        .card { background: #fff; border: 1px solid #ddd; border-radius: 5px; padding: 15px; margin-bottom: 20px; }
        .progress { height: 10px; border-radius: 5px; background: #ecf0f1; margin-top: 5px; }
        .progress-bar { border-radius: 5px; }
        .progress-bar-heaven-blue { background: #87CEEB; }
        .progress-bar-green { background: #28a745; }
        .progress-bar-amber { background: #ffc107; }
        .progress-bar-red { background: #dc3545; }
        .kpi-item { padding: 10px; border-radius: 5px; background-color: #f8f9fa; margin-bottom: 15px; }
        .badge { padding: 6px 10px; font-weight: 500; font-size: 0.75rem; letter-spacing: 0.5px; text-transform: capitalize; }
        .badge-pending { background-color: #ffc107; color: #212529; }
        .badge-approved { background-color: #28a745; color: white; }
        .btn { padding: 6px 12px; font-size: 0.85rem; touch-action: manipulation; }
        .form-control-sm { display: inline-block; width: auto; }
        @media (max-width: 576px) {
            .card { padding: 10px; }
            h1 { font-size: 1.2rem; }
            .btn { padding: 4px 8px; font-size: 0.75rem; }
            .form-control-sm { width: 100px; }
        }
    </style>
</head>
<body>
    <button class="hamburger" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <div class="sidebar" id="sidebar">
        <h2>WhiteHouse</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="all_kpis.php" class="active"><i class="fas fa-tasks"></i> All KPIs</a>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <div class="content" id="content">
        <h1 class="text-primary text-center">All KPIs</h1>

        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['success_message']); unset($_SESSION['success_message']); ?></div>
        <?php endif; ?>
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['error_message']); unset($_SESSION['error_message']); ?></div>
        <?php endif; ?>

        <div class="card">
            <h3><i class="fas fa-tasks"></i> Your KPIs</h3>
            <?php if ($kpi_error): ?>
                <div class="alert alert-warning"><?php echo htmlspecialchars($kpi_error); ?></div>
            <?php elseif ($kpi_results && $kpi_results->num_rows > 0): ?>
                <div class="text-end mb-3">
                    <a href="download_all_kpis.php" class="btn btn-sm btn-info">
                        <i class="fas fa-file-excel"></i> Download All KPIs
                    </a>
                </div>
                <?php while ($kpi = $kpi_results->fetch_assoc()): ?>
                    <div class="kpi-item mb-3">
                        <div class="d-flex justify-content-between">
                            <strong><?php echo htmlspecialchars($kpi['kpi_name']); ?></strong>
                            <span><?php echo htmlspecialchars($kpi['progress']); ?>%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar <?php
                                if ($kpi['progress'] > 100) {
                                    echo 'progress-bar-heaven-blue';
                                } elseif ($kpi['progress'] >= 90) {
                                    echo 'progress-bar-green';
                                } elseif ($kpi['progress'] >= 70) {
                                    echo 'progress-bar-amber';
                                } else {
                                    echo 'progress-bar-red';
                                }
                            ?>" role="progressbar" 
                                 style="width: <?php echo htmlspecialchars($kpi['progress']); ?>%" 
                                 aria-valuenow="<?php echo htmlspecialchars($kpi['progress']); ?>" 
                                 aria-valuemin="0" 
                                 aria-valuemax="100">
                            </div>
                        </div>
                        <small class="text-muted">
                            Current: <?php echo htmlspecialchars($kpi['current_value']); ?> | Target: <?php echo htmlspecialchars($kpi['target']); ?>
                            | Status: <span class="badge <?php echo ($kpi['status'] === 'Accepted') ? 'badge-approved' : 'badge-pending'; ?>">
                                <?php echo htmlspecialchars($kpi['status']); ?>
                            </span>
                        </small>
                        <div class="mt-2">
                            <a href="view_kpi.php?id=<?php echo htmlspecialchars($kpi['kpi_id']); ?>" class="btn btn-sm btn-primary">
                                <i class="fas fa-eye"></i> View KPI
                            </a>
                            <?php if ($status_column_exists && (!isset($kpi['status']) || $kpi['status'] !== 'Accepted')): ?>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="action" value="accept_kpi">
                                    <input type="hidden" name="kpi_id" value="<?php echo htmlspecialchars($kpi['kpi_id']); ?>">
                                    <button type="submit" class="btn btn-sm btn-success">
                                        <i class="fas fa-check"></i> Accept KPI
                                    </button>
                                </form>
                            <?php endif; ?>
                            <?php if ($status_column_exists && isset($kpi['status']) && $kpi['status'] === 'Accepted'): ?>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="action" value="update_kpi">
                                    <input type="hidden" name="kpi_id" value="<?php echo htmlspecialchars($kpi['kpi_id']); ?>">
                                    <input type="number" name="weekly_update" class="form-control form-control-sm" 
                                           placeholder="Weekly update" min="0" step="0.01" required>
                                    <button type="submit" class="btn btn-sm btn-warning">
                                        <i class="fas fa-upload"></i> Update
                                    </button>
                                </form>
                                <a href="download_kpi.php?id=<?php echo htmlspecialchars($kpi['kpi_id']); ?>" class="btn btn-sm btn-info">
                                    <i class="fas fa-file-excel"></i> Download Excel
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p class="text-muted">No KPIs assigned yet. Please contact your administrator to assign KPIs.</p>
            <?php endif; ?>
            <div class="text-center mt-3">
                <a href="dashboard_employee.php" class="btn btn-outline-primary btn-sm">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById('content');
            sidebar.classList.toggle('active');
            content.classList.toggle('active');
        }
    </script>
</body>
<?php 
try {
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
} catch (Exception $e) {
    error_log("Error closing database connection: " . $e->getMessage());
}
?>
</html>