<?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();

// Fetch Employee Profile
$stmt = $db->prepare("SELECT e.id, e.name, e.department, e.joining_date, e.verification_status, e.emp_code, b.branch_name 
                      FROM employees e 
                      LEFT JOIN branches b ON e.branch_id = b.id 
                      WHERE e.id = ?");
$stmt->execute([$emp_id]);
$employee = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Ensure default values
$employee['emp_code'] = $employee['emp_code'] ?? 'EMP-'.str_pad($employee['id'],4,'0',STR_PAD_LEFT);
$employee['branch_name'] = $employee['branch_name'] ?? 'Head Office';

// Fetch Documents
$stmt = $db->prepare("SELECT doc_id, category, document_type, document_number, file_url, status, remarks, uploaded_at 
                      FROM employee_documents 
                      WHERE employee_id = ? ORDER BY category, uploaded_at DESC");
$stmt->execute([$emp_id]);
$documents = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'success' => true,
    'employee' => $employee,
    'documents' => $documents
]);
