<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';
$subtype = $_GET['subtype'] ?? $_POST['subtype'] ?? '';

if ($subtype === 'training') {
    if ($action === 'list') {
        $sql = "SELECT id AS __backendId, employee_name, cert_type, provider, expiry_date, status FROM competence_training ORDER BY id DESC";
        $result = $mysqli->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) { $data[] = $row; }
        }
        echo json_encode($data);
    } elseif ($action === 'create') {
        $emp_name = $_POST['emp_name'] ?? '';
        $cert_type = $_POST['cert_type'] ?? '';
        $provider = $_POST['provider'] ?? '';
        $expiry_date = $_POST['expiry_date'] ?? '';
        
        $stmt = $mysqli->prepare("INSERT INTO competence_training (employee_name, cert_type, provider, expiry_date, status) VALUES (?, ?, ?, ?, 'Active')");
        $stmt->bind_param("ssss", $emp_name, $cert_type, $provider, $expiry_date);
        $ok = $stmt->execute();
        echo json_encode(['success' => $ok]);
    }
} elseif ($subtype === 'medical') {
    if ($action === 'list') {
        $sql = "SELECT id AS __backendId, employee_name, medical_type, next_due, status FROM competence_medical ORDER BY id DESC";
        $result = $mysqli->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) { $data[] = $row; }
        }
        echo json_encode($data);
    } elseif ($action === 'create') {
        $emp_name = $_POST['emp_name'] ?? '';
        $medical_type = $_POST['medical_type'] ?? '';
        $next_due = $_POST['next_due'] ?? '';
        
        $stmt = $mysqli->prepare("INSERT INTO competence_medical (employee_name, medical_type, next_due, status) VALUES (?, ?, ?, 'Active')");
        $stmt->bind_param("sss", $emp_name, $medical_type, $next_due);
        $ok = $stmt->execute();
        echo json_encode(['success' => $ok]);
    }
}
?>
