<?php
// ajax/create_affiliation.php
// Create a new affiliation if not found in table
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');
startSession();

$data = json_decode(file_get_contents('php://input'), true);
$name = trim($data['name'] ?? '');
if (!$name) { echo json_encode(['success'=>false,'message'=>'Name required']); exit; }

try {
    $stmt = db()->prepare(
        "INSERT INTO affiliations (name, department, city, country, is_institutional_partner)
         VALUES (?, ?, ?, ?, 0)"
    );
    $stmt->execute([
        $name,
        trim($data['department'] ?? ''),
        trim($data['city']       ?? ''),
        trim($data['country']    ?? ''),
    ]);
    $id = db()->lastInsertId();
    echo json_encode(['success'=>true,'affiliation_id'=>$id,'name'=>$name]);
} catch (PDOException $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}