<?php
// ============================================================
// LIFE CRM — Cron уведомления (cron.php)
//
// Настройка в cPanel → Cron Jobs:
//   Утренняя сводка:  0 9 * * *  /usr/bin/php /path/to/cron.php morning
//   Дедлайн-алерты:  0 */4 * * * /usr/bin/php /path/to/cron.php deadlines
//   Или через URL (если нет доступа к cron):
//   Поставь задание на сервисе cron-job.org → GET https://yourdomain.com/cron.php?mode=morning&secret=YOUR_SECRET
// ============================================================

define('DATA_DIR', __DIR__ . '/data/');
define('BOT_TOKEN', '');        // ← токен бота
define('ALLOWED_CHAT_ID', ''); // ← твой chat_id
define('CRON_SECRET', 'change_me_to_random_string'); // ← секрет для URL-вызова

// Определяем режим запуска
$mode = 'morning';
if (PHP_SAPI === 'cli') {
    $mode = $argv[1] ?? 'morning';
} else {
    // HTTP-вызов с секретом
    $secret = $_GET['secret'] ?? '';
    if ($secret !== CRON_SECRET) { http_response_code(403); exit('Forbidden'); }
    $mode = $_GET['mode'] ?? 'morning';
}

// ---- Helpers ------------------------------------------------
function readData($name) {
    $file = DATA_DIR . $name . '.json';
    if (!file_exists($file)) return [];
    $d = json_decode(file_get_contents($file), true);
    return is_array($d) ? $d : [];
}
function fmtMoney($n) { return number_format((float)$n, 0, '.', ' ') . ' ₽'; }
function fmtDate($d) { if (!$d) return ''; $dt = DateTime::createFromFormat('Y-m-d', $d); return $dt ? $dt->format('d.m.Y') : $d; }
function daysLeft($d) { if (!$d) return null; return (int)ceil((strtotime($d) - time()) / 86400); }
function daysAgo($d) { if (!$d) return 0; return (int)floor((time() - strtotime($d)) / 86400); }
function todayDate() { return date('Y-m-d'); }

function sendTg($text) {
    $url = 'https://api.telegram.org/bot' . BOT_TOKEN . '/sendMessage';
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['chat_id' => ALLOWED_CHAT_ID, 'text' => $text, 'parse_mode' => 'HTML']),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);
    curl_exec($ch);
    curl_close($ch);
}

// ---- Morning digest -----------------------------------------
function morningDigest() {
    $clients  = readData('clients');
    $finances = readData('finances');
    $tasks    = readData('tasks');

    $income   = array_sum(array_map(fn($f) => $f['type']==='income' ? (float)$f['amount'] : 0, $finances));
    $expenses = array_sum(array_map(fn($f) => $f['type']==='expense' ? (float)$f['amount'] : 0, $finances));

    $pushClients = array_filter($clients, fn($c) => $c['status']==='card_opened' && daysAgo($c['updated']??$c['created']) >= 2);
    $activeTasks = array_filter($tasks, fn($t) => !($t['done']??false));
    $overdueTasks = array_filter($tasks, fn($t) => !($t['done']??false) && ($t['due']??'') && daysLeft($t['due']) < 0);
    $todayTasks = array_filter($tasks, fn($t) => !($t['done']??false) && ($t['due']??'') === todayDate());
    $overdueFinances = array_filter($finances, fn($f) => ($f['due']??'') && !($f['paid']??false) && daysLeft($f['due']) < 0);
    $todayFinances = array_filter($finances, fn($f) => ($f['due']??'') === todayDate() && !($f['paid']??false));

    $dow = ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'];
    $dayName = $dow[date('w')];
    $text = "☀️ <b>Доброе утро! " . $dayName . ", " . date('d.m.Y') . "</b>\n\n";

    // Что нужно сделать сегодня
    $hasUrgent = false;
    if (count($todayTasks) > 0) {
        $hasUrgent = true;
        $text .= "📌 <b>Задачи на сегодня:</b>\n";
        foreach ($todayTasks as $t) $text .= "  • " . htmlspecialchars($t['title']) . "\n";
        $text .= "\n";
    }
    if (count($todayFinances) > 0) {
        $hasUrgent = true;
        $text .= "💳 <b>Платежи сегодня:</b>\n";
        foreach ($todayFinances as $f) $text .= "  • " . htmlspecialchars($f['name']) . " — " . fmtMoney($f['amount']) . "\n";
        $text .= "\n";
    }
    if (count($pushClients) > 0) {
        $hasUrgent = true;
        $text .= "🔔 <b>Push клиентам (" . count($pushClients) . "):</b>\n";
        foreach ($pushClients as $c) {
            $text .= "  • " . htmlspecialchars($c['name']);
            if ($c['phone']??'') $text .= " — " . htmlspecialchars($c['phone']);
            $text .= " (" . daysAgo($c['updated']??$c['created']) . "д)\n";
        }
        $text .= "\n";
    }

    // Просрочки
    if (count($overdueTasks) > 0) {
        $text .= "⚠️ <b>Просроченные задачи (" . count($overdueTasks) . "):</b>\n";
        foreach (array_slice($overdueTasks, 0, 3) as $t) $text .= "  • " . htmlspecialchars($t['title']) . "\n";
        $text .= "\n";
    }
    if (count($overdueFinances) > 0) {
        $text .= "⚠️ <b>Просроченные платежи:</b>\n";
        foreach ($overdueFinances as $f) $text .= "  • " . htmlspecialchars($f['name']) . " — " . fmtMoney($f['amount']) . "\n";
        $text .= "\n";
    }

    if (!$hasUrgent && !count($overdueTasks) && !count($overdueFinances)) {
        $text .= "✅ Срочных дел нет. Хороший день!\n\n";
    }

    // Финансовая сводка
    $text .= "💰 Баланс: <b>" . fmtMoney($income - $expenses) . "</b>";
    $text .= " | Активных задач: <b>" . count($activeTasks) . "</b>";

    sendTg($text);
    echo "Morning digest sent.\n";
}

// ---- Deadline alerts ----------------------------------------
function deadlineAlerts() {
    $tasks    = readData('tasks');
    $finances = readData('finances');

    $alerts = [];

    // Tasks due in 1 day
    foreach ($tasks as $t) {
        if ($t['done']??false) continue;
        $dl = daysLeft($t['due']??'');
        if ($dl === 1) $alerts[] = "📌 Задача <b>" . htmlspecialchars($t['title']) . "</b> — завтра дедлайн!";
        if ($dl === 0) $alerts[] = "⚡ Задача <b>" . htmlspecialchars($t['title']) . "</b> — дедлайн СЕГОДНЯ!";
    }

    // Finances due in 1-2 days
    foreach ($finances as $f) {
        if ($f['paid']??false) continue;
        $dl = daysLeft($f['due']??'');
        if ($dl === 2) $alerts[] = "💳 Платёж <b>" . htmlspecialchars($f['name']) . "</b> (" . fmtMoney($f['amount']) . ") — через 2 дня";
        if ($dl === 1) $alerts[] = "💳 Платёж <b>" . htmlspecialchars($f['name']) . "</b> (" . fmtMoney($f['amount']) . ") — ЗАВТРА!";
        if ($dl === 0) $alerts[] = "⚡ Платёж <b>" . htmlspecialchars($f['name']) . "</b> (" . fmtMoney($f['amount']) . ") — СЕГОДНЯ!";
    }

    if ($alerts) {
        $text = "⏰ <b>Напоминания</b>\n\n" . implode("\n", $alerts);
        sendTg($text);
        echo "Sent " . count($alerts) . " alerts.\n";
    } else {
        echo "No alerts.\n";
    }
}

// ---- Run ----------------------------------------------------
if ($mode === 'morning') morningDigest();
elseif ($mode === 'deadlines') deadlineAlerts();
else echo "Unknown mode: $mode\n";
