<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../app/Models/Customer.php';
require_once __DIR__ . '/../../../app/Config/functions.php';

require_login();

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

try {
    // Sanitize user input
    $data = [
        'name'    => trim($_POST['name'] ?? ''),
        'email'   => trim($_POST['email'] ?? ''),
        'contact' => trim($_POST['contact'] ?? ''),
        'status'  => $_POST['status'] ?? 'active',
    ];

    // Validation
    if ($data['name'] === '') {
        throw new Exception('Customer name is required.');
    }

    $model = new Customer();
    $success = $model->create($data);

    echo json_encode([
        'success' => $success,
        'message' => $success
            ? '✅ Customer added successfully!'
            : '❌ Failed to add customer. Please try again.',
    ]);
} catch (Throwable $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage(),
    ]);
}
