<?php
session_start();
header('Content-Type: application/json');

// Enable error reporting for debugging (disable in production)
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
if ($userRole !== 'M' && $userRole !== 'A') {
    echo json_encode(['success' => false, 'message' => 'Forbidden']);
    exit;
}

require_once __DIR__ . '/../../DataBase/koneksi.php';

// Check database connection
if (!$conn) {
    echo json_encode([
        'success' => false, 
        'message' => 'Database connection failed: ' . mysqli_connect_error()
    ]);
    exit;
}

try {
    // Get all SDM data
    $query = "SELECT 
        nip,
        nama,
        jenis_kelamin,
        tempat_lahir,
        tanggal_lahir,
        alamat,
        no_hp,
        email,
        jabatan,
        kantor,
        tanggal_masuk,
        status,
        pendidikan,
        jurusan
    FROM sdm 
    ORDER BY nama ASC";
    
    $result = mysqli_query($conn, $query);
    
    if (!$result) {
        throw new Exception('Query failed: ' . mysqli_error($conn));
    }
    
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    
    // Free result set
    mysqli_free_result($result);
    
    // Try to log activity (optional - won't fail if table doesn't exist)
    try {
        $username = $_SESSION['username'] ?? 'Unknown';
        $escapedUsername = mysqli_real_escape_string($conn, $username);
        
        // Check if activity_log table exists
        $checkTable = mysqli_query($conn, "SHOW TABLES LIKE 'activity_log'");
        if (mysqli_num_rows($checkTable) > 0) {
            $logQuery = "INSERT INTO activity_log (user, action, description, timestamp) 
                         VALUES ('$escapedUsername', 'EXPORT', 'Export data SDM ke Excel', NOW())";
            mysqli_query($conn, $logQuery);
        }
    } catch (Exception $logError) {
        // Silently fail logging - don't affect main export
    }
    
    // Close connection
    mysqli_close($conn);
    
    // Return success response
    echo json_encode([
        'success' => true, 
        'data' => $data,
        'total' => count($data)
    ]);
    
} catch (Exception $e) {
    // Make sure to close connection on error
    if (isset($conn) && $conn) {
        mysqli_close($conn);
    }
    
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ]);
}
?>