<?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: dashboard_employee.php");
    exit();
}
include 'config.php';

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

// Validate user session
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';

// Validate POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['kpi_id'], $_POST['action']) || $_POST['action'] !== 'accept_kpi') {
    error_log("Invalid request to accept_kpi.php. Method: {$_SERVER['REQUEST_METHOD']}, kpi_id: " . ($_POST['kpi_id'] ?? 'not set') . ", action: " . ($_POST['action'] ?? 'not set'));
    $_SESSION['error_message'] = "Invalid request.";
    header("Location: dashboard_employee.php");
    exit();
}

$kpi_id = (int)$_POST['kpi_id'];
if ($kpi_id <= 0) {
    error_log("Invalid KPI ID: $kpi_id");
    $_SESSION['error_message'] = "Invalid KPI ID.";
    header("Location: dashboard_employee.php");
    exit();
}

// 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 if employee_kpis table exists
if (!$conn->query("SHOW TABLES LIKE 'employee_kpis'")->num_rows) {
    error_log("Table employee_kpis does not exist.");
    $_SESSION['error_message'] = "KPI table not found.";
    header("Location: dashboard_employee.php");
    exit();
}

// Verify KPI belongs to the employee
try {
    $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'] = "Failed to validate KPI.";
        header("Location: dashboard_employee.php");
        exit();
    }
    $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.";
        header("Location: dashboard_employee.php");
        exit();
    }
    $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.";
        header("Location: dashboard_employee.php");
        exit();
    }
    $stmt_check->close();
} catch (Exception $e) {
    error_log("Exception in KPI check query: " . $e->getMessage());
    $_SESSION['error_message'] = "Error validating KPI: " . htmlspecialchars($e->getMessage());
    header("Location: dashboard_employee.php");
    exit();
}

// Check if status column exists
$status_column_exists = columnExists($conn, 'employee_kpis', 'status');
if (!$status_column_exists) {
    error_log("Warning: 'status' column missing in employee_kpis table for KPI ID $kpi_id. Accepting KPI without status update.");
    $_SESSION['success_message'] = "KPI accepted, but status tracking is not supported due to missing database configuration.";
    header("Location: dashboard_employee.php");
    exit();
}

// Update KPI status to Accepted
try {
    $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 update query preparation failed: " . $conn->error);
        $_SESSION['error_message'] = "Failed to prepare KPI update query.";
        header("Location: dashboard_employee.php");
        exit();
    }
    $stmt_update->bind_param("ii", $kpi_id, $employee_id);
    if ($stmt_update->execute()) {
        error_log("KPI ID $kpi_id accepted by employee ID $employee_id");
        // Notify admin
        try {
            $admin_sql = "SELECT id FROM users WHERE role = 'admin' LIMIT 1";
            $admin_result = $conn->query($admin_sql);
            if ($admin_result && $admin_result->num_rows > 0) {
                $admin = $admin_result->fetch_assoc();
                $admin_id = $admin['id'];
                $message = "Employee {$username} (ID: {$employee_id}) has accepted KPI ID: {$kpi_id}";
                $notif_sql = "INSERT INTO notifications (employee_id, message, status, created_at) VALUES (?, ?, 'Unread', NOW())";
                $stmt_notif = $conn->prepare($notif_sql);
                if ($stmt_notif) {
                    $stmt_notif->bind_param("is", $admin_id, $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);
                }
            } else {
                error_log("No admin found or query failed: " . $conn->error);
            }
        } catch (Exception $e) {
            error_log("Exception in admin notification: " . $e->getMessage());
        }
        $_SESSION['success_message'] = "KPI accepted successfully!";
    } else {
        error_log("KPI update query execution failed: " . $stmt_update->error);
        $_SESSION['error_message'] = "Failed to accept KPI: " . htmlspecialchars($stmt_update->error);
    }
    $stmt_update->close();
} catch (Exception $e) {
    error_log("Exception in KPI update query: " . $e->getMessage());
    $_SESSION['error_message'] = "Error accepting KPI: " . htmlspecialchars($e->getMessage());
}

// Close database connection
try {
    $conn->close();
} catch (Exception $e) {
    error_log("Error closing database connection: " . $e->getMessage());
}
header("Location: dashboard_employee.php");
exit();
?>