<?php
/**
 * Guarda un nuevo cliente desde el modal de creación.
 * P1: delega alta, normalizacion de RUT y duplicados a CustomerService.
 */
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.customers');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /modules/customers/');
    exit;
}

try {
    $legalName = trim((string)($_POST['legal_name'] ?? ($_POST['customer_name'] ?? '')));
    $commercialName = trim((string)($_POST['commercial_name'] ?? ''));
    if ($commercialName === '') {
        $commercialName = $legalName;
    }

    $businessActivity = trim((string)($_POST['business_activity'] ?? ''));
    if ($businessActivity === '') {
        throw new RuntimeException('Debe ingresar el giro o actividad económica del cliente.');
    }

    $customerService = new CustomerService();
    $result = $customerService->create(array(
        'customer_name' => $commercialName,
        'commercial_name' => $commercialName,
        'legal_name' => $legalName,
        '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',
        'default_income_center_id' => $_POST['default_income_center_id'] ?? null,
        'default_cost_center_id' => $_POST['default_cost_center_id'] ?? null,
        'supplier_default_cost_center_id' => $_POST['supplier_default_cost_center_id'] ?? ($_POST['default_cost_center_id'] ?? null),
        'counterparty_type' => $_POST['counterparty_type'] ?? 'customer',
        'is_supplier' => $_POST['is_supplier'] ?? 0,
        'supplier_status' => $_POST['supplier_status'] ?? 'inactive',
        'business_activity' => $businessActivity,
        'restock_days' => $_POST['restock_days'] ?? null,
        'source' => 'manual'
    ), array('reuse_existing' => true, 'require_location' => true));

    $customerId = (int)$result['customer_id'];
    $suffix = $result['status'] === 'reused' ? '&duplicate=1' : '';
    header('Location: /modules/customers/view.php?id=' . $customerId . $suffix);
    exit;
} catch (Throwable $e) {
    die($e->getMessage());
}
