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

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

if (!user_can('billing.manual.prepare') && !user_can('customers.create') && !user_can('module.customers') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para crear clientes desde el emisor.'));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Método no permitido.'));
    exit;
}

try {
    $name = trim((string)($_POST['legal_name'] ?? $_POST['customer_name'] ?? ''));
    $activity = trim((string)($_POST['business_activity'] ?? ''));
    if ($name === '') throw new InvalidArgumentException('Debes ingresar la razón social.');
    if ($activity === '') throw new InvalidArgumentException('Debes ingresar el giro o actividad económica.');

    $service = new CustomerService();
    $result = $service->create(array(
        'customer_name' => $name,
        'commercial_name' => trim((string)($_POST['commercial_name'] ?? $name)),
        'legal_name' => $name,
        'customer_tax_id' => trim((string)($_POST['customer_tax_id'] ?? '')),
        'contact_name' => trim((string)($_POST['contact_name'] ?? '')),
        'email' => trim((string)($_POST['email'] ?? '')),
        'phone' => trim((string)($_POST['phone'] ?? '')),
        'address' => trim((string)($_POST['address'] ?? '')),
        'district' => trim((string)($_POST['district'] ?? '')),
        'city' => trim((string)($_POST['city'] ?? '')),
        'region' => trim((string)($_POST['region'] ?? '')),
        'country' => trim((string)($_POST['country'] ?? 'Chile')) ?: 'Chile',
        'payment_terms' => trim((string)($_POST['payment_terms'] ?? 'contado')) ?: 'contado',
        'business_activity' => $activity,
        'source' => 'manual_billing'
    ), array('reuse_existing' => true, 'require_location' => true));

    $id = (int)$result['customer_id'];
    $stmt = db()->prepare("SELECT id,customer_name,commercial_name,legal_name,customer_tax_id,export_tax_id_code,export_tax_id_type,tax_id_type,email,email_dte,phone,address,district,city,region,country,country_id,export_country_id,business_activity,payment_terms,default_income_center_id FROM crm_customers WHERE id=? LIMIT 1");
    $stmt->execute(array($id));
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$customer) throw new RuntimeException('El cliente fue creado, pero no fue posible recuperarlo.');

    echo json_encode(array(
        'success' => true,
        'customer' => $customer,
        'message' => $result['status'] === 'reused' ? 'Se reutilizó el cliente existente con el mismo RUT.' : 'Cliente creado correctamente.'
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
