<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../services/crm/CustomerService.php';
require_once '../../services/crm/CrmService.php';
require_once '../../services/crm/RestockForecastService.php';

require_login();
require_permission('module.customers');
header('Content-Type: application/json; charset=utf-8');

$respond = static function (array $payload, int $status = 200): void {
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
};

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    $respond(array('success' => false, 'message' => 'Método no permitido.'), 405);
}

csrf_require_valid_request();

try {
    $customerId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    if ($customerId <= 0) throw new RuntimeException('Cliente inválido.');

    $customerService = new CustomerService();
    $customer = $customerService->requireActiveById($customerId, 'Cliente no encontrado o desactivado.');
    $taxId = trim((string)($customer['customer_tax_id'] ?? ''));
    if ($taxId === '') throw new RuntimeException('El cliente no tiene RUT o ID tributario para buscar documentos en FACTO.');

    $crm = new CrmService();
    $result = $crm->updateCustomerRestockFrequency($customerId, $taxId);
    if (!$result) {
        throw new RuntimeException('Se requieren al menos dos facturas o boletas emitidas y aprobadas en FACTO para calcular el ciclo.');
    }

    $forecast = array('created' => false);
    try {
        $forecast = (new RestockForecastService(db()))->refreshFromCustomer($customerId, null, 'manual_cycle_recalculation');
    } catch (Throwable $forecastError) {
        error_log('Restock forecast after manual cycle recalculation ' . $customerId . ': ' . $forecastError->getMessage());
    }

    $respond(array(
        'success' => true,
        'message' => 'Ciclo recalculado y aplicado desde FACTO.',
        'restock_days' => (int)$result['restock_days'],
        'next_restock_date' => $result['next_restock_date'],
        'next_restock_date_display' => date('d-m-Y', strtotime($result['next_restock_date'])),
        'documents_used' => (int)($result['documents_used'] ?? 0),
        'source' => 'facto',
        'forecast' => $forecast,
    ));
} catch (Throwable $e) {
    $respond(array('success' => false, 'message' => $e->getMessage()), 422);
}
