<?php
/**
 * Actualiza un cliente existente.
 * P1: delega edicion, normalizacion de RUT, duplicados y sincronizacion snapshot 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;
}

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
    die('ID de cliente inválido.');
}

try {
    $customerService = new CustomerService();
    $payload = array(
        'customer_name' => $_POST['customer_name'] ?? '',
        'commercial_name' => $_POST['commercial_name'] ?? '',
        'legal_name' => $_POST['legal_name'] ?? ($_POST['customer_name'] ?? ''),
        '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'] ?? '',
        'website' => $_POST['website'] ?? '',
        'payment_terms' => $_POST['payment_terms'] ?? 'contado',
        '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'] ?? ''
    );

    if (array_key_exists('restock_days', $_POST)) {
        $payload['restock_days'] = $_POST['restock_days'];
    }

    $customerService->update($id, $payload);

    header('Location: /modules/customers/view.php?id=' . $id . '&updated=1');
    exit;
} catch (Throwable $e) {
    die($e->getMessage());
}
