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

$user = requireRole([1, 2, 5]); // Admin, Dev, HR
$db   = getDB();

$companyName = trim(post('company_name', ''));
if (empty($companyName)) apiError('Company name is required.', 422);

$db->prepare("
    INSERT INTO clients (company_name, trading_name, registration_no, vat_no, industry, status, website, notes, created_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
")->execute([
    $companyName,
    post('trading_name'),
    post('registration_no'),
    post('vat_no'),
    post('industry'),
    post('status', 'active'),
    post('website'),
    post('notes'),
    $user['id']
]);

$clientId = (int)$db->lastInsertId();

// Add primary contact if provided
$contactName = trim(post('contact_name', ''));
if ($contactName) {
    $db->prepare("
        INSERT INTO client_contacts (client_id, full_name, position, email, phone, is_primary)
        VALUES (?, ?, ?, ?, ?, 1)
    ")->execute([
        $clientId,
        $contactName,
        post('contact_position'),
        post('contact_email'),
        post('contact_phone')
    ]);
}

// Add physical address if provided
$addressLine1 = trim(post('address_line1', ''));
if ($addressLine1) {
    $db->prepare("
        INSERT INTO client_addresses (client_id, type, line1, line2, city, province, postal_code, country)
        VALUES (?, 'physical', ?, ?, ?, ?, ?, ?)
    ")->execute([
        $clientId,
        $addressLine1,
        post('address_line2'),
        post('city'),
        post('province'),
        post('postal_code'),
        post('country', 'South Africa')
    ]);
}

apiSuccess(['id' => $clientId], 'Client created successfully.', 201);
