<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized Access']);
    exit;
}

$emp_id = $_GET['id'] ?? 0;
if (!$emp_id) {
    echo json_encode(['success' => false, 'message' => 'Missing employee ID']);
    exit;
}

$db = getDB();

try {
    // 1. Employee Core Details
    $stmt = $db->prepare("
        SELECT e.*, b.branch_name 
        FROM employees e 
        LEFT JOIN branches b ON e.branch_id = b.id 
        WHERE e.id = ?
    ");
    $stmt->execute([$emp_id]);
    $emp = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$emp) {
        echo json_encode(['success' => false, 'message' => 'Employee not found']);
        exit;
    }

    // 2. Bank Details
    $stmt = $db->prepare("SELECT * FROM employee_bank WHERE employee_id = ?");
    $stmt->execute([$emp_id]);
    $bank = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

    // 3. Salary Info
    $stmt = $db->prepare("SELECT * FROM employee_salary WHERE employee_id = ? ORDER BY effective_date DESC LIMIT 1");
    $stmt->execute([$emp_id]);
    $salary = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

    // 4. Documents Summary
    $stmt = $db->prepare("SELECT document_type, status, uploaded_at FROM employee_documents WHERE employee_id = ? ORDER BY uploaded_at DESC");
    $stmt->execute([$emp_id]);
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 5. Activity Logs
    $stmt = $db->prepare("SELECT action, ip_address, created_at FROM employee_activity_logs WHERE employee_id = ? ORDER BY created_at DESC LIMIT 10");
    $stmt->execute([$emp_id]);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'profile' => [
            'core' => $emp,
            'bank' => $bank,
            'salary' => $salary,
            'documents' => $documents,
            'logs' => $logs
        ]
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()]);
}
