<?php
require_once __DIR__ . '/../core/cron_guard.php';
icylab_require_cron_access();
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../services/crm/RestockForecastService.php';

if (PHP_SAPI !== 'cli') header('Content-Type: text/plain; charset=utf-8');
$pdo = db();
$service = new RestockForecastService($pdo);
$days = isset($_GET['days']) ? max(30, min(365, (int)$_GET['days'])) : 90;
$validDocument = "fd.received_issued_flag=1 AND fd.document_status=1
    AND COALESCE(fd.payment_status,'')<>'anulado'
    AND COALESCE(fd.document_type_taxbureau,'') IN ('33','34','39','110')";
$taxMatch = "REPLACE(REPLACE(REPLACE(UPPER(fd.receiver_tax_id_code),'.',''),'-',''),' ','') =
    REPLACE(REPLACE(REPLACE(UPPER(c.customer_tax_id),'.',''),'-',''),' ','')";

$sql = "
    SELECT c.id AS customer_id,
           (
               SELECT fd.document_id
               FROM facto_documents fd
               WHERE $validDocument
                 AND fd.issue_date >= DATE_SUB(CURDATE(),INTERVAL " . $days . " DAY)
                 AND (fd.crm_customer_id=c.id OR $taxMatch)
               ORDER BY fd.issue_date DESC, fd.id DESC
               LIMIT 1
           ) AS facto_document_id
    FROM crm_customers c
    WHERE c.deleted_at IS NULL
      AND c.counterparty_type<>'supplier'
      AND EXISTS (
          SELECT 1 FROM facto_documents fd
          WHERE $validDocument
            AND fd.issue_date >= DATE_SUB(CURDATE(),INTERVAL " . $days . " DAY)
            AND (fd.crm_customer_id=c.id OR $taxMatch)
      )
    ORDER BY c.id
";
$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$created = 0;
$skipped = 0;
$errors = 0;
foreach ($rows as $row) {
    try {
        $result = $service->refreshFromCustomer(
            (int)$row['customer_id'],
            !empty($row['facto_document_id']) ? (string)$row['facto_document_id'] : null,
            'v8_5_historical_backfill'
        );
        if (!empty($result['created'])) $created++; else $skipped++;
    } catch (Throwable $e) {
        $errors++;
        error_log('Restock backfill customer ' . (int)$row['customer_id'] . ': ' . $e->getMessage());
    }
}

echo 'RESTOCK BACKFILL COMPLETED' . PHP_EOL;
echo 'Clientes recientes evaluados: ' . count($rows) . PHP_EOL;
echo 'Pronosticos creados/actualizados: ' . $created . PHP_EOL;
echo 'Omitidos por reglas: ' . $skipped . PHP_EOL;
echo 'Errores: ' . $errors . PHP_EOL;
