<?php
// ── WhatsApp Helper ───────────────────────────────────────────

// Normalize any phone format to +91XXXXXXXXXX
function normalizePhone(string $phone): string {
    $phone = preg_replace('/\D/', '', $phone); // remove non-digits
    // Remove leading zeros
    $phone = ltrim($phone, '0');
    // Remove country code 91 if present (10 digit number left)
    if (strlen($phone) === 12 && str_starts_with($phone, '91')) {
        $phone = substr($phone, 2);
    }
    // Must be 10 digits now
    if (strlen($phone) !== 10) return '';
    return '+91' . $phone;
}

// Send WhatsApp message via wa.bitseva.in
function waSend(string $recipient, string $message): bool {
    $url  = WA_API_URL . '/send/whatsapp';
    $data = [
        'secret'    => WA_SECRET,
        'account'   => WA_ACCOUNT,
        'recipient' => $recipient,
        'type'      => 'text',
        'message'   => $message,
        'priority'  => 1,
    ];
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
    ]);
    $res  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if (!$res) return false;
    $json = json_decode($res, true);
    return ($json['status'] ?? 0) === 200;
}

// Generate 6-digit OTP, store in DB
function generateOtp(PDO $db, int $userId): string {
    $otp     = str_pad(random_int(100000, 999999), 6, '0', STR_PAD_LEFT);
    $expires = date('Y-m-d H:i:s', time() + WA_OTP_EXPIRY);
    $db->prepare("UPDATE users SET otp_code=?, otp_expires=? WHERE id=?")
       ->execute([$otp, $expires, $userId]);
    return $otp;
}

// Verify OTP
function verifyOtp(PDO $db, int $userId, string $otp): bool {
    $user = dbRow($db, "SELECT otp_code, otp_expires FROM users WHERE id=?", [$userId]);
    if (!$user || $user['otp_code'] !== $otp) return false;
    if (strtotime($user['otp_expires']) < time()) return false;
    // Clear OTP after use
    $db->prepare("UPDATE users SET otp_code=NULL, otp_expires=NULL WHERE id=?")->execute([$userId]);
    return true;
}

// Send daily report to a user
function sendDailyReport(PDO $db, array $user, string $date): bool {
    if (empty($user['phone'])) return false;
    $phone = normalizePhone($user['phone']);
    if (!$phone) return false;

    $name = $user['full_name'];
    $role = strtoupper($user['role']);

    if ($user['role'] === 'mr') {
        // MR — apni readings
        $solar = (int)dbVal($db, "SELECT COUNT(*) FROM readings WHERE user_id=? AND reading_type='solar' AND reading_date=?", [$user['id'], $date]);
        $kcc   = (int)dbVal($db, "SELECT COUNT(*) FROM readings WHERE user_id=? AND reading_type='kcc'   AND reading_date=?", [$user['id'], $date]);
        $bills = (int)dbVal($db, "SELECT COUNT(*) FROM bills    WHERE user_id=? AND DATE(created_at)=?",                     [$user['id'], $date]);
        $total = $solar + $kcc;

        $msg = "📊 *EMRS Daily Report*\n";
        $msg .= "📅 Date: " . date('d M Y', strtotime($date)) . "\n";
        $msg .= "👤 MR: *{$name}*\n\n";
        $msg .= "☀️ Solar Readings: *{$solar}*\n";
        $msg .= "⚡ KCC Readings: *{$kcc}*\n";
        $msg .= "🧾 Bills Distributed: *{$bills}*\n";
        $msg .= "✅ Total Readings: *{$total}*\n\n";
        $msg .= "_EMRS — Electricity Meter Reading System_";

    } else {
        // Admin/Staff — full summary
        $totalSolar = (int)dbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='solar' AND reading_date=?", [$date]);
        $totalKcc   = (int)dbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='kcc'   AND reading_date=?", [$date]);
        $totalBills = (int)dbVal($db, "SELECT COUNT(*) FROM bills    WHERE DATE(created_at)=?",                      [$date]);
        $totalMRs   = (int)dbVal($db, "SELECT COUNT(DISTINCT user_id) FROM readings WHERE reading_date=?",           [$date]);

        // Top MRs
        $topMRs = dbRows($db,
            "SELECT u.full_name, COUNT(r.id) AS cnt
             FROM readings r JOIN users u ON u.id=r.user_id
             WHERE r.reading_date=?
             GROUP BY r.user_id ORDER BY cnt DESC LIMIT 5", [$date]);

        $msg = "📊 *EMRS Daily Summary Report*\n";
        $msg .= "📅 Date: " . date('d M Y', strtotime($date)) . "\n";
        $msg .= "👤 For: *{$name}* ({$role})\n\n";
        $msg .= "☀️ Solar Readings: *{$totalSolar}*\n";
        $msg .= "⚡ KCC Readings: *{$totalKcc}*\n";
        $msg .= "🧾 Bills Distributed: *{$totalBills}*\n";
        $msg .= "👷 Active MRs Today: *{$totalMRs}*\n\n";

        if (!empty($topMRs)) {
            $msg .= "🏆 *Top Performers:*\n";
            foreach ($topMRs as $i => $m) {
                $msg .= ($i+1) . ". {$m['full_name']} — {$m['cnt']} readings\n";
            }
            $msg .= "\n";
        }
        $msg .= "_EMRS — Electricity Meter Reading System_";
    }

    return waSend($phone, $msg);
}
