<?php
// api/customer_create.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

header('Content-Type: application/json');

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
    exit;
}

$name = trim((string)($data['name'] ?? ''));
$phone = trim((string)($data['phone'] ?? ''));
$email = trim((string)($data['email'] ?? ''));
$address = trim((string)($data['address'] ?? ''));

if ($name === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Name is required']);
    exit;
}

try {
    $stmt = $pdo->prepare("
      INSERT INTO customers (name, phone, email, address)
      VALUES (:name, :phone, :email, :address)
    ");
    $stmt->execute([
        ':name' => $name,
        ':phone' => ($phone !== '' ? $phone : null),
        ':email' => ($email !== '' ? $email : null),
        ':address' => ($address !== '' ? $address : null),
    ]);

    $id = (int)$pdo->lastInsertId();

    echo json_encode(['ok' => true, 'customer' => [
        'id' => $id,
        'name' => $name,
        'phone' => $phone,
        'email' => $email,
        'address' => $address
    ]]);
} catch (Throwable $t) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $t->getMessage()]);
}
