<?php
// =============================================================================
// BRANCH SALES BILL SYNC MONITOR — Telegram Notification
// Schedule: Windows Task Scheduler OR cPanel Cron → 0 19 * * *
// =============================================================================

require_once __DIR__ . '/catchexception.php';
require_once __DIR__ . '/db_config.php';

// ─────────────────────────────────────────────────────────────────────────────
// TELEGRAM CONFIG
// ─────────────────────────────────────────────────────────────────────────────
$bot_token = '8468354464:AAG5V1SK_CCWnrnkexu6AZJYG58Zyc-Hrrw';   // 👈 from @BotFather
$chat_id   = '-5010367269';                   // 👈 your group/channel id
$threshold = 50;                                 // alert if sync count < 50

// ─────────────────────────────────────────────────────────────────────────────
// TIMEZONE & DATE  (same pattern as your existing code)
// ─────────────────────────────────────────────────────────────────────────────
date_default_timezone_set('Asia/Kolkata');
$today = date('d-m-Y');
$check_time = date('h:i A');

// ─────────────────────────────────────────────────────────────────────────────
// HELPER — Send Telegram message via cURL
// ─────────────────────────────────────────────────────────────────────────────
function sendTelegramMessage($bot_token, $chat_id, $message) {
    $url  = 'https://api.telegram.org/bot' . $bot_token . '/sendMessage';
    $data = json_encode([
        'chat_id'    => $chat_id,
        'text'       => $message,
        'parse_mode' => 'HTML'
    ]);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $data,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

// ─────────────────────────────────────────────────────────────────────────────
// HELPER — Send long text split into chunks (Telegram limit = 4096 chars)
// Each chunk gets a header so it's clear which part it is
// ─────────────────────────────────────────────────────────────────────────────
function sendChunkedMessage($bot_token, $chat_id, $header, $rows, $footer, $chunk_size = 60) {
    $chunks       = array_chunk($rows, $chunk_size);
    $total_chunks = count($chunks);
 
    foreach ($chunks as $index => $chunk) {
        $part_no   = $index + 1;
        // $part_label = $total_chunks > 1 ? " (Part {$part_no}/{$total_chunks})" : "";
        $part_label =  "";
        $message = $header . $part_label . "\n" . implode('', $chunk);
 
        // Add footer only on last chunk
        if ($part_no === $total_chunks) {
            $message .= $footer;
        }
 
        sendTelegramMessage($bot_token, $chat_id, $message);
 
        // 100ms gap between messages — avoid Telegram rate limit
        usleep(100000);
    }
}
 
// ─────────────────────────────────────────────────────────────────────────────
// MAIN
// ─────────────────────────────────────────────────────────────────────────────
try {
 
    echo "=== Branch Sync Monitor Started | Date: {$today} ===" . PHP_EOL;
 
    // ── STEP 1: Get all active branches below threshold ───────────────────────
    $sql_branches = "
        SELECT
            b.branchcode,
            b.branchname,
            COUNT(s.autonum)        AS sync_count,
            ($1 - COUNT(s.autonum)) AS shortfall
        FROM
            public.tblbranchmaster b
            LEFT JOIN public.tblsales s
                ON  s.branchcode = b.branchcode
                AND s.syncflag   = 1
                AND (s.cancelflag IS NULL OR s.cancelflag <> 1)
                AND TO_TIMESTAMP(s.syncdate / 1000.0)::DATE = CURRENT_DATE
        WHERE
            b.statuscode = 1
        GROUP BY
            b.branchcode,
            b.branchname
        HAVING
            COUNT(s.autonum) < $2
        ORDER BY
            COUNT(s.autonum) ASC,
            b.branchname ASC
    ";
 
    $result_branches = pg_prepare($con, "sql_branches", $sql_branches);
    $res_branches    = pg_execute($con, "sql_branches", [$threshold, $threshold]);
 
    // ── STEP 2: Count healthy branches ────────────────────────────────────────
    $sql_healthy = "
        SELECT COUNT(*) AS healthy_count
        FROM (
            SELECT b.branchcode
            FROM   public.tblbranchmaster b
            LEFT JOIN public.tblsales s
                ON  s.branchcode = b.branchcode
                AND s.syncflag   = 1
                AND (s.cancelflag IS NULL OR s.cancelflag <> 1)
                AND TO_TIMESTAMP(s.syncdate / 1000.0)::DATE = CURRENT_DATE
            WHERE  b.statuscode = 1
            GROUP  BY b.branchcode
            HAVING COUNT(s.autonum) >= $1
        ) ok
    ";
 
    $result_healthy = pg_prepare($con, "sql_healthy", $sql_healthy);
    $res_healthy    = pg_execute($con, "sql_healthy", [$threshold]);
 
    $healthy_count = 0;
    if (!empty($res_healthy) && pg_num_rows($res_healthy) > 0) {
        $row_healthy   = pg_fetch_assoc($res_healthy);
        $healthy_count = $row_healthy['healthy_count'];
    }
 
    // ── STEP 3: Collect all low-sync branches into rows array ─────────────────
    $low_count   = 0;
    $branch_rows = [];
    $serial_no   = 1;
 
    if (!empty($res_branches) && pg_num_rows($res_branches) > 0) {
        while ($row = pg_fetch_assoc($res_branches)) {
            $low_count++;
            $branchcode = $row['branchcode'];
            $branchname = $row['branchname'];
            $sync_count = $row['sync_count'];
            $shortfall  = $row['shortfall'];
 
            // Each branch = one row entry in the array
            $branch_rows[] =
                "\n{$serial_no}. <b>{$branchname}</b>"
              . "\n    📊 Synced: <b>{$sync_count}</b> / {$threshold}  \n";
 
            $serial_no++;
            echo "Found low branch: [{$branchcode}] {$branchname} | Sync: {$sync_count}" . PHP_EOL;
        }
    }
 
    // ── STEP 4: Send message(s) ───────────────────────────────────────────────
    if ($low_count === 0) {
 
        // ── All clear — single message ─────────────────────────────────────────
        $message =
            "✅ <b>Daily Sync Check — All Clear</b>\n"
          . "━━━━━━━━━━━━━━━━━━━━━━━━━\n"
          . "📅 <b>Date</b>              : {$today}\n"
          . "🏢 <b>Synced Branches</b>: {$healthy_count}\n"
          . "📊 All branches have ≥ {$threshold} synced bills.\n"
          . "━━━━━━━━━━━━━━━━━━━━━━━━━\n"
          . "⏰ Checked at {$check_time}";
 
        sendTelegramMessage($bot_token, $chat_id, $message);
        echo "All branches OK. All-clear message sent." . PHP_EOL;
 
    } else {
 
        // ── Header (sent at top of first chunk) ───────────────────────────────
        $header =
            "🔴 <b>Sales Bill Sync Alert</b>\n"
          . "━━━━━━━━━━━━━━━━━━━━━━━━━\n"
          . "📅 <b>Date</b>                 : {$today}\n"
          . "✅ <b>Synced Branches</b>      : {$healthy_count}\n"
          . "🔴 <b>Branches Not Synced / Below 50 Bills</b> : {$low_count}\n"
          . "📉 <b>Threshold</b>            : &lt; {$threshold} bills\n"
          . "━━━━━━━━━━━━━━━━━━━━━━━━━\n"
          . "📋 <b>Low Sync Branches:</b>";
 
        // ── Footer (sent at bottom of last chunk) ─────────────────────────────
        $footer =
            "\n━━━━━━━━━━━━━━━━━━━━━━━━━\n"
          . "⏰ Checked at {$check_time} — Please follow up.";
 
        // ── Send in chunks of 40 branches per message ─────────────────────────
        sendChunkedMessage($bot_token, $chat_id, $header, $branch_rows, $footer, 60);
 
        echo "Sent {$low_count} branch(es) across " . ceil($low_count / 60) . " message(s)." . PHP_EOL;
    }
 
    echo "=== Monitor Completed ===" . PHP_EOL;
 
    mch_db_release($con);
 
} catch (Exception $e) {
    mch_db_release($con);
    echo 'Message: ' . $e->getMessage();
}
?>