```php
<?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');

session_start();

// Check for valid session and role
if (!isset($_SESSION['user_id'], $_SESSION['role']) || $_SESSION['role'] !== 'employee') {
    error_log("Unauthorized access attempt in download_kpi_sample.php. Session data: user_id=" . ($_SESSION['user_id'] ?? 'not set') . ", role=" . ($_SESSION['role'] ?? 'not set'));
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode([
        'error' => 'Unauthorized access attempt',
        'details' => [
            'message' => 'You must be logged in as an employee to access this resource.',
            'code' => 403,
            'file' => __FILE__,
            'line' => __LINE__
        ]
    ]);
    exit();
}

$employee_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Unknown User';
error_log("KPI sample download initiated by ID: $employee_id, Username: $username");

// Include database configuration
if (!file_exists('config.php')) {
    error_log("Config file missing: config.php");
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'error' => 'Server configuration error',
        'details' => [
            'message' => 'Configuration file not found.',
            'code' => 500,
            'file' => __FILE__,
            'line' => __LINE__
        ]
    ]);
    exit();
}
include 'config.php';

// Verify database connection
if ($conn->connect_error) {
    error_log("Database connection failed: " . $conn->connect_error);
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'error' => 'Database connection error',
        'details' => [
            'message' => 'Unable to connect to the database.',
            'code' => 500,
            'file' => __FILE__,
            'line' => __LINE__
        ]
    ]);
    exit();
}

// Load PhpSpreadsheet
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

try {
    // Create new Spreadsheet object
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    
    // Set headers
    $sheet->setCellValue('A1', 'KPI ID');
    $sheet->setCellValue('B1', 'KPI Title');
    $sheet->setCellValue('C1', 'Employee ID');
    $sheet->setCellValue('D1', 'Start Value');
    $sheet->setCellValue('E1', 'Target Value');
    $sheet->setCellValue('F1', 'Current Value');
    $sheet->setCellValue('G1', 'Progress (%)');
    $sheet->setCellValue('H1', 'Status');
    $sheet->setCellValue('I1', 'Last Updated');

    // Sample data (replace with actual data if needed)
    $sample_data = [
        [
            'kpi_id' => 1,
            'kpi_title' => 'Goods Inspected and Organized Within 24 Hours',
            'employee_id' => $employee_id,
            'start_value' => 0,
            'target_value' => 95,
            'current_value' => 0,
            'progress' => 0,
            'status' => 'Pending',
            'last_updated' => date('Y-m-d H:i:s')
        ],
        [
            'kpi_id' => 2,
            'kpi_title' => 'Order Fulfillment Accuracy',
            'employee_id' => $employee_id,
            'start_value' => 0,
            'target_value' => 98,
            'current_value' => 0,
            'progress' => 0,
            'status' => 'Pending',
            'last_updated' => date('Y-m-d H:i:s')
        ]
    ];

    // Populate sheet with sample data
    $row = 2;
    foreach ($sample_data as $data) {
        $sheet->setCellValue("A$row", $data['kpi_id']);
        $sheet->setCellValue("B$row", $data['kpi_title']);
        $sheet->setCellValue("C$row", $data['employee_id']);
        $sheet->setCellValue("D$row", $data['start_value']);
        $sheet->setCellValue("E$row", $data['target_value']);
        $sheet->setCellValue("F$row", $data['current_value']);
        $sheet->setCellValue("G$row", $data['progress']);
        $sheet->setCellValue("H$row", $data['status']);
        $sheet->setCellValue("I$row", $data['last_updated']);
        $row++;
    }

    // Apply basic styling
    $sheet->getStyle('A1:I1')->getFont()->setBold(true);
    $sheet->getStyle('A1:I1')->getAlignment()->setHorizontal('center');
    foreach (range('A', 'I') as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
    }

    // Set headers for download
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="kpi_sample_' . $employee_id . '_' . date('Ymd_His') . '.xlsx"');
    header('Cache-Control: max-age=0');

    // Write to output
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit();

} catch (Exception $e) {
    error_log("Error generating KPI sample Excel: " . $e->getMessage());
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'error' => 'An error occurred while generating the report',
        'details' => [
            'message' => $e->getMessage(),
            'code' => 500,
            'file' => __FILE__,
            'line' => __LINE__,
            'trace' => $e->getTraceAsString()
        ]
    ]);
    exit();
}

$conn->close();
?>
