<?php
// POST /api/clients/add_contact.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$clientId = (int)post('client_id', 0);
$fullName = trim(post('full_name', ''));

if (!$clientId) apiError('Client ID required.', 422);
if (!$fullName) apiError('Contact name required.', 422);

$isPrimary = (bool)post('is_primary', false);

if ($isPrimary) {
    $db->prepare("UPDATE client_contacts SET is_primary = 0 WHERE client_id = ?")->execute([$clientId]);
}

$db->prepare("
    INSERT INTO client_contacts (client_id, full_name, position, email, phone, is_primary)
    VALUES (?, ?, ?, ?, ?, ?)
")->execute([
    $clientId, $fullName, post('position'), post('email'), post('phone'), $isPrimary ? 1 : 0
]);

apiSuccess(['id' => (int)$db->lastInsertId()], 'Contact added.');
