115 lines
4.4 KiB
PHP
115 lines
4.4 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../db/config.php';
|
|
require_once __DIR__ . '/../includes/functions.php';
|
|
require_once __DIR__ . '/../includes/WablasService.php';
|
|
|
|
// Enable error logging for cron
|
|
ini_set('log_errors', 1);
|
|
$logFile = __DIR__ . '/../storage/cron_debug.log';
|
|
ini_set('error_log', $logFile);
|
|
|
|
// Helper to log with timestamp
|
|
function cron_log($msg) {
|
|
global $logFile;
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] " . $msg . "\n", FILE_APPEND);
|
|
}
|
|
|
|
try {
|
|
$settings = get_company_settings();
|
|
|
|
if (empty($settings['whatsapp_report_enabled']) || empty($settings['whatsapp_report_number']) || empty($settings['whatsapp_report_time'])) {
|
|
// Silent exit if disabled or missing config
|
|
exit;
|
|
}
|
|
|
|
$timezone = !empty($settings['timezone']) ? $settings['timezone'] : 'UTC';
|
|
date_default_timezone_set($timezone);
|
|
|
|
$reportTime = $settings['whatsapp_report_time'];
|
|
|
|
$lastReportFile = __DIR__ . '/../storage/last_daily_report.txt';
|
|
$lastReportDate = file_exists($lastReportFile) ? trim(file_get_contents($lastReportFile)) : '';
|
|
|
|
$nowDt = new DateTime('now', new DateTimeZone($timezone));
|
|
|
|
$targetTodayDt = clone $nowDt;
|
|
$timeParts = explode(':', $reportTime);
|
|
$targetTodayDt->setTime((int)$timeParts[0], (int)($timeParts[1] ?? 0), 0);
|
|
|
|
$diffToday = $nowDt->getTimestamp() - $targetTodayDt->getTimestamp();
|
|
|
|
// Check if within 15 minutes (900 seconds) after the target time AND not sent today
|
|
if ($diffToday >= 0 && $diffToday <= 900 && $lastReportDate !== $nowDt->format('Y-m-d')) {
|
|
cron_log("Condition met: sending daily report for " . $nowDt->format('Y-m-d'));
|
|
|
|
$pdo = db();
|
|
$today = $nowDt->format('Y-m-d');
|
|
|
|
// 1. Calculate Stats
|
|
// Total Revenue Today
|
|
$stmt = $pdo->prepare("SELECT SUM(total_amount) FROM orders WHERE DATE(created_at) = ? AND status != 'cancelled'");
|
|
$stmt->execute([$today]);
|
|
$revenueToday = $stmt->fetchColumn() ?: 0;
|
|
|
|
// Total Orders Today
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE DATE(created_at) = ? AND status != 'cancelled'");
|
|
$stmt->execute([$today]);
|
|
$ordersToday = $stmt->fetchColumn();
|
|
|
|
// Total Expenses Today
|
|
$stmt = $pdo->prepare("SELECT SUM(amount) FROM expenses WHERE DATE(expense_date) = ?");
|
|
$stmt->execute([$today]);
|
|
$expensesToday = $stmt->fetchColumn() ?: 0;
|
|
|
|
// Currency
|
|
$currency = $settings['currency_symbol'] ?? '$';
|
|
|
|
// 2. Format Message
|
|
$message = "📅 *Daily Report* 📅\n";
|
|
$message .= "Date: " . $today . "\n\n";
|
|
$message .= "💰 *Sales:* " . format_currency_simple($revenueToday, $settings) . "\n";
|
|
$message .= "🧾 *Orders:* " . $ordersToday . "\n";
|
|
$message .= "💸 *Expenses:* " . format_currency_simple($expensesToday, $settings) . "\n";
|
|
$message .= "\n--------------------------\n";
|
|
$message .= "🤖 Auto-generated message";
|
|
|
|
// 3. Send Message
|
|
$wablas = new WablasService($pdo);
|
|
// Handle multiple recipients (comma separated)
|
|
$recipients = explode(',', $settings['whatsapp_report_number']);
|
|
$anySuccess = false;
|
|
|
|
foreach ($recipients as $recipient) {
|
|
$recipient = trim($recipient);
|
|
if (empty($recipient)) continue;
|
|
|
|
cron_log("Sending report to: " . $recipient);
|
|
$result = $wablas->sendMessage($recipient, $message);
|
|
|
|
if (!empty($result['success']) && $result['success'] == true) {
|
|
cron_log("Report sent successfully to " . $recipient);
|
|
$anySuccess = true;
|
|
} else {
|
|
cron_log("Failed to send report to " . $recipient . ": " . ($result['message'] ?? 'Unknown error'));
|
|
}
|
|
}
|
|
|
|
if ($anySuccess) {
|
|
file_put_contents($lastReportFile, $today);
|
|
}
|
|
}
|
|
// Else: silent skip
|
|
|
|
} catch (Exception $e) {
|
|
cron_log("CRITICAL ERROR: " . $e->getMessage());
|
|
}
|
|
|
|
function format_currency_simple($amount, $settings) {
|
|
$symbol = $settings['currency_symbol'] ?? '$';
|
|
$decimals = (int)($settings['currency_decimals'] ?? 2);
|
|
$position = $settings['currency_position'] ?? 'before';
|
|
|
|
$formatted = number_format((float)$amount, $decimals);
|
|
return ($position === 'after') ? "$formatted $symbol" : "$symbol $formatted";
|
|
}
|