<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['super_admin']);

$db   = getDBConnection();
$date = $_GET['date'] ?? date('Y-m-d');

$sent   = [];
$failed = [];
$done   = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && validateCsrfToken($_POST['csrf_token'] ?? '')) {
    $date    = $_POST['date'] ?? date('Y-m-d');
    $targets = $_POST['targets'] ?? 'all'; // all | mrs | admins

    $where = "WHERE is_active=1 AND phone IS NOT NULL AND phone != ''";
    if ($targets === 'mrs')    $where .= " AND role='mr'";
    if ($targets === 'admins') $where .= " AND role IN ('super_admin','exn','sdo','je')";

    $users = dbRows($db, "SELECT * FROM users {$where}");

    foreach ($users as $user) {
        $ok = sendDailyReport($db, $user, $date);
        if ($ok) $sent[]   = $user['full_name'] . ' (' . $user['phone'] . ')';
        else     $failed[] = $user['full_name'] . ' (' . ($user['phone'] ?: 'no phone') . ')';
    }
    $done = true;
}

// Stats for preview
$totalSolar = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='solar' AND reading_date=?", [$date]);
$totalKcc   = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='kcc'   AND reading_date=?", [$date]);
$totalBills = (int)safeDbVal($db, "SELECT COUNT(*) FROM bills    WHERE DATE(created_at)=?",                      [$date]);
$totalMRs   = (int)safeDbVal($db, "SELECT COUNT(DISTINCT user_id) FROM readings WHERE reading_date=?",           [$date]);

$mrStats = dbRows($db,
    "SELECT u.full_name, u.phone,
            SUM(CASE WHEN r.reading_type='solar' THEN 1 ELSE 0 END) AS solar,
            SUM(CASE WHEN r.reading_type='kcc'   THEN 1 ELSE 0 END) AS kcc,
            COUNT(b.id) AS bills
     FROM users u
     LEFT JOIN readings r ON r.user_id=u.id AND r.reading_date=?
     LEFT JOIN bills    b ON b.user_id=u.id AND DATE(b.created_at)=?
     WHERE u.role='mr' AND u.is_active=1
     GROUP BY u.id, u.full_name, u.phone
     ORDER BY (SUM(CASE WHEN r.reading_type='solar' THEN 1 ELSE 0 END) + SUM(CASE WHEN r.reading_type='kcc' THEN 1 ELSE 0 END)) DESC", [$date, $date]);

$pageTitle = 'WhatsApp Daily Report';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><h1><i class="bi bi-whatsapp me-2" style="color:#25d366;"></i>WhatsApp Daily Report</h1></div>
</div>

<?php if ($done): ?>
<div class="alert alert-success">
    <strong><i class="bi bi-check-circle-fill me-2"></i>Report Sent!</strong><br>
    ✅ Sent: <strong><?= count($sent) ?></strong> &nbsp;|&nbsp;
    ❌ Failed: <strong><?= count($failed) ?></strong>
    <?php if (!empty($sent)): ?>
    <div class="mt-2" style="font-size:.8rem;"><?= implode(', ', array_map('h', $sent)) ?></div>
    <?php endif; ?>
    <?php if (!empty($failed)): ?>
    <div class="mt-1 text-danger" style="font-size:.8rem;">Failed: <?= implode(', ', array_map('h', $failed)) ?></div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Date + Send Form -->
<div class="erp-card mb-4">
    <form method="POST" class="row g-3 align-items-end">
        <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
        <div class="col-12 col-md-4">
            <label class="form-label fw-semibold" style="font-size:.86rem;">Report Date</label>
            <input type="date" name="date" class="form-control" value="<?= h($date) ?>">
        </div>
        <div class="col-12 col-md-4">
            <label class="form-label fw-semibold" style="font-size:.86rem;">Send To</label>
            <select name="targets" class="form-select">
                <option value="all">All Users (MR + Admin/Staff)</option>
                <option value="mrs">Only Meter Readers (MR)</option>
                <option value="admins">Only Admin/Staff</option>
            </select>
        </div>
        <div class="col-12 col-md-4">
            <button type="submit" class="btn w-100 fw-bold py-2" style="background:#25d366;color:#fff;border-radius:8px;">
                <i class="bi bi-whatsapp me-2"></i>Send WhatsApp Reports
            </button>
        </div>
    </form>
</div>

<!-- Day Summary -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <div class="stat-card"><div class="stat-card-icon orange"><i class="bi bi-sun-fill"></i></div>
        <div><h3>Solar</h3><p><?= $totalSolar ?></p></div></div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card"><div class="stat-card-icon blue"><i class="bi bi-lightning-fill"></i></div>
        <div><h3>KCC</h3><p><?= $totalKcc ?></p></div></div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card"><div class="stat-card-icon green"><i class="bi bi-receipt"></i></div>
        <div><h3>Bills</h3><p><?= $totalBills ?></p></div></div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card"><div class="stat-card-icon teal"><i class="bi bi-people-fill"></i></div>
        <div><h3>Active MRs</h3><p><?= $totalMRs ?></p></div></div>
    </div>
</div>

<!-- MR wise table -->
<div class="erp-card">
    <h6 class="fw-bold mb-3">MR-wise Report — <?= date('d M Y', strtotime($date)) ?></h6>
    <div class="table-responsive">
        <table class="table table-hover" style="font-size:.84rem;">
            <thead class="table-dark">
                <tr><th>#</th><th>MR Name</th><th>Phone</th><th class="text-center">Solar</th><th class="text-center">KCC</th><th class="text-center">Bills</th><th class="text-center">Total</th><th>Send</th></tr>
            </thead>
            <tbody>
                <?php if (empty($mrStats)): ?>
                <tr><td colspan="8" class="text-center text-muted py-4">No MR data for this date.</td></tr>
                <?php endif; ?>
                <?php foreach ($mrStats as $i => $m): ?>
                <tr>
                    <td class="text-muted"><?= $i+1 ?></td>
                    <td class="fw-semibold"><?= h($m['full_name']) ?></td>
                    <td class="text-muted" style="font-size:.8rem;"><?= h($m['phone'] ?? '—') ?></td>
                    <td class="text-center"><span class="badge bg-warning text-dark"><?= (int)$m['solar'] ?></span></td>
                    <td class="text-center"><span class="badge bg-primary"><?= (int)$m['kcc'] ?></span></td>
                    <td class="text-center"><span class="badge bg-success"><?= (int)$m['bills'] ?></span></td>
                    <td class="text-center fw-bold"><?= (int)$m['solar']+(int)$m['kcc'] ?></td>
                    <td>
                        <?php if ($m['phone']): ?>
                        <a href="?send_single=<?= $i ?>&uid=<?= urlencode($m['full_name']) ?>&date=<?= $date ?>"
                           class="btn btn-sm" style="background:#25d366;color:#fff;"
                           onclick="return confirm('Send report to <?= h(addslashes($m['full_name'])) ?>?')">
                            <i class="bi bi-whatsapp"></i>
                        </a>
                        <?php else: ?>
                        <span class="text-muted" style="font-size:.75rem;">No phone</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
