<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../services/crm/CustomerService.php';

require_login();
require_permission('module.crm');

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(array('success' => false, 'message' => 'Método no permitido.'));
    exit;
}

try {
    $service = new CustomerService();
    $customerName = $_POST['customer_name'] ?? '';
    $result = $service->create(array(
        'customer_name' => $customerName,
        'commercial_name' => $_POST['commercial_name'] ?? $customerName,
        'legal_name' => $_POST['legal_name'] ?? $customerName,
        'customer_tax_id' => $_POST['customer_tax_id'] ?? '',
        'contact_name' => $_POST['contact_name'] ?? '',
        'email' => $_POST['email'] ?? '',
        'phone' => $_POST['phone'] ?? '',
        'address' => $_POST['address'] ?? '',
        'district' => $_POST['district'] ?? '',
        'city' => $_POST['city'] ?? '',
        'region' => $_POST['region'] ?? '',
        'country' => $_POST['country'] ?? 'Chile',
        'latitude' => $_POST['latitude'] ?? '',
        'longitude' => $_POST['longitude'] ?? '',
        'geocode_status' => $_POST['geocode_status'] ?? '',
        'geocode_source' => $_POST['geocode_source'] ?? '',
        'geocode_query' => $_POST['geocode_query'] ?? '',
        'website' => $_POST['website'] ?? '',
        'payment_terms' => $_POST['payment_terms'] ?? 'contado',
        'restock_days' => $_POST['restock_days'] ?? null,
        'source' => 'manual'
    ), array('reuse_existing' => true, 'require_location' => true));

    $message = $result['status'] === 'reused'
        ? 'Ya existía un cliente activo con ese RUT; se reutilizó el registro existente.'
        : 'Cliente creado correctamente.';

    echo json_encode(array(
        'success' => true,
        'customer' => $service->publicPayload($result['customer']),
        'message' => $message
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
