<?php
// Enable error reporting for debugging
ini_set('display_errors', 0);
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();
}
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: 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("Download KPI (CSV) accessed by ID: $employee_id, Username: $username");

// Check if KPI ID is provided and valid
$kpi_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($kpi_id <= 0) {
    error_log("Invalid KPI ID: $kpi_id");
    $_SESSION['error_message'] = "Invalid KPI ID.";
    header("Location: all_kpis.php");
    exit();
}

// Verify KPI belongs to employee and is accepted
$status_column_exists = columnExists($conn, 'employee_kpis', 'status');
$status_condition = $status_column_exists ? "AND ek.status = 'Accepted'" : "";
$sql = "SELECT k.kpi_title, k.target_value, ek.current_value, ek.status
        FROM employee_kpis ek
        JOIN kpi k ON ek.kpi_id = k.id
        WHERE ek.kpi_id = ? AND ek.employee_id = ? $status_condition";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    error_log("KPI query preparation failed: " . $conn->error);
    $_SESSION['error_message'] = "System error. Please try again later.";
    header("Location: all_kpis.php");
    exit();
}
$stmt->bind_param("ii", $kpi_id, $employee_id);
if (!$stmt->execute()) {
    error_log("KPI query execution failed: " . $stmt->error);
    $_SESSION['error_message'] = "Failed to fetch KPI data.";
    header("Location: all_kpis.php");
    exit();
}
$result = $stmt->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.";
    header("Location: all_kpis.php");
    exit();
}
$kpi = $result->fetch_assoc();
$stmt->close();

// Generate CSV
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="kpi_' . $kpi_id . '.csv"');
header('Cache-Control: max-age=0');

$output = fopen('php://output', 'w');
fputcsv($output, ['KPI ID', 'KPI Title', 'Current Value', 'Target Value', 'Progress (%)', 'Status']);
$progress = $kpi['target_value'] > 0 ? round(($kpi['current_value'] / $kpi['target_value']) * 100, 2) : 0;
fputcsv($output, [
    $kpi_id,
    $kpi['kpi_title'],
    $kpi['current_value'],
    $kpi['target_value'],
    $progress,
    $kpi['status'] ?? 'Pending'
]);
fclose($output);
error_log("KPI CSV downloaded for KPI ID: $kpi_id, Employee ID: $employee_id, Username: $username");
$conn->close();
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;
    }
}
?>