<?php
/**
 * Cron / Task Scheduler: resumen matutino por correo.
 *
 * Uso (Windows Task Scheduler, todos los días a las 6:05):
 *   C:\xampp\php\php.exe C:\xampp\htdocs\SITIOSWEB\JORGEBORJA\jb-planeacion-app\public\cron-daily-digest.php
 *
 * Opcional: ?force=1 o argumento --force para reenviar el mismo día.
 *
 * @package Logistica
 */

require_once dirname( __DIR__ ) . '/core/bootstrap.php';

if ( ! class_exists( 'Logistica_User_Panel', false ) ) {
	require_once dirname( __DIR__ ) . '/src/includes/class-logistica-user-panel.php';
}

$force = false;
if ( PHP_SAPI === 'cli' ) {
	$force = in_array( '--force', $argv ?? array(), true );
} else {
	$force = isset( $_GET['force'] ) && '1' === (string) $_GET['force'];
	$token = defined( 'LOGISTICA_CRON_TOKEN' ) ? (string) LOGISTICA_CRON_TOKEN : '';
	$given = isset( $_GET['token'] ) ? (string) $_GET['token'] : '';
	if ( '' !== $token && ! hash_equals( $token, $given ) ) {
		status_header( 403 );
		header( 'Content-Type: text/plain; charset=utf-8' );
		echo "Forbidden\n";
		exit;
	}
}

$result = Logistica_User_Panel::send_daily_digest_to_all_users( $force );

header( 'Content-Type: application/json; charset=utf-8' );
echo wp_json_encode(
	array(
		'ok'      => true,
		'sent'    => (int) ( $result['sent'] ?? 0 ),
		'skipped' => (int) ( $result['skipped'] ?? 0 ),
		'force'   => $force,
		'at'      => gmdate( 'c' ),
	),
	JSON_UNESCAPED_UNICODE
);
echo "\n";
