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

function getTableColumns($mysqli, $table) {
    $columns = [];
    $result = $mysqli->query("SHOW COLUMNS FROM {$table}");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $columns[] = $row['Field'];
        }
    }
    return $columns;
}

$id = $_POST['id'] ?? null;
$fields = [
    'full_name' => $_POST['full_name'] ?? null,
    'department' => $_POST['department'] ?? null,
    'position' => $_POST['position'] ?? null,
    'email' => $_POST['email'] ?? null,
    'phone' => $_POST['phone'] ?? null,
    'status' => $_POST['status'] ?? null,
    'employee_no' => $_POST['employee_no'] ?? null,
    'pin' => $_POST['pin'] ?? null,
    'password' => $_POST['password'] ?? null
];

if (!$id || !$fields['full_name']) {
    echo json_encode(['success' => false, 'error' => 'ID and name required']);
    exit;
}

$existing = getTableColumns($mysqli, 'personnel');
$updates = [];
$types = '';
$values = [];

foreach ($fields as $column => $value) {
    if (!in_array($column, $existing, true)) {
        continue;
    }
    $updates[] = "{$column} = ?";
    $types .= 's';
    $values[] = $value;
}

if (empty($updates)) {
    echo json_encode(['success' => false, 'error' => 'No valid fields to update']);
    exit;
}

$query = "UPDATE personnel SET " . implode(', ', $updates) . " WHERE id = ?";
$types .= 'i';
$values[] = $id;

$stmt = $mysqli->prepare($query);
$stmt->bind_param($types, ...$values);
$ok = $stmt->execute();

echo json_encode(['success' => $ok]);
?>
