<?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.customers');

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || $id <= 0) {
    header('Location: /modules/suppliers/');
    exit;
}

try {
    $service = new CustomerService();
    $current = $service->requireActiveById($id, 'Proveedor no encontrado o desactivado.');
    $businessActivity = trim((string)($_POST['business_activity'] ?? ''));
    $selectedCostCenter = $_POST['supplier_default_cost_center_id'] ?? ($_POST['default_cost_center_id'] ?? null);
    if ($businessActivity === '') {
        throw new RuntimeException('Debe ingresar el giro o actividad económica del proveedor.');
    }

    $currentType = (string)($current['counterparty_type'] ?? 'supplier');
    $counterpartyType = $currentType === 'customer' || $currentType === 'both' ? 'both' : 'supplier';

    $service->update($id, array(
        'customer_name' => $_POST['customer_name'] ?? '',
        'commercial_name' => $_POST['commercial_name'] ?? ($_POST['customer_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'] ?? '',
        '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'] ?? '',
        'supplier_payment_terms_id' => $_POST['supplier_payment_terms_id'] ?? null,
        'default_income_center_id' => $_POST['default_income_center_id'] ?? null,
        'default_cost_center_id' => $selectedCostCenter,
        'supplier_default_cost_center_id' => $selectedCostCenter,
        'counterparty_type' => $counterpartyType,
        'is_supplier' => 1,
        'supplier_status' => $_POST['supplier_status'] ?? ($current['supplier_status'] ?? 'active'),
        'business_activity' => $businessActivity,
        'restock_days' => $_POST['restock_days'] ?? null
    ));

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