<?php
session_start();
require_once '../config/database.php';
require_once '../includes/sms_helper.php';

// Auth check
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin'])) {
    header('Location: ../login.php');
    exit();
}

$cfg = sms_config();
$sent = [];
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $session   = trim($_POST['session'] ?? '');
        $class_id  = trim($_POST['class_id'] ?? '');
        $min_due   = (float)($_POST['min_due'] ?? 1);
        $limit     = (int)($_POST['limit'] ?? 200);

        $where = ["s.status='active'"];
        $params = [];
        if ($session !== '') { $where[] = 's.session = ?'; $params[] = $session; }
        if ($class_id !== '') { $where[] = 's.class_id = ?'; $params[] = $class_id; }
        $whereSql = implode(' AND ', $where);

        $sql = "
            SELECT s.id, s.first_name, s.last_name, s.phone, s.guardian_phone,
                   c.name AS class_name, c.section AS class_section,
                   COALESCE(SUM(f.amount-COALESCE(f.paid_amount,0)),0) AS total_due
            FROM students s
            JOIN classes c ON c.id=s.class_id
            LEFT JOIN fees f ON f.student_id = s.id
            WHERE $whereSql
            GROUP BY s.id, s.first_name, s.last_name, s.phone, s.guardian_phone, c.name, c.section
            HAVING total_due >= ?
            ORDER BY total_due DESC
            LIMIT ?
        ";
        $params2 = array_merge($params, [$min_due, $limit]);
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params2);
        $rows = $stmt->fetchAll();

        foreach ($rows as $r) {
            $numbers = [];
            if (!empty($r['phone'])) $numbers[] = $r['phone'];
            if (($cfg['send_to_guardian_also'] ?? true) && !empty($r['guardian_phone'])) $numbers[] = $r['guardian_phone'];
            if (empty($numbers)) continue;

            $vars = [
                'name' => trim(($r['first_name'] ?? '').' '.($r['last_name'] ?? '')),
                'due_amount' => number_format((float)$r['total_due'], 2),
            ];
            $resp = sms_send_template($pdo, 'fee_due_reminder', $vars, $numbers);
            $sent[] = [
                'student' => $vars['name'],
                'to' => $numbers,
                'due' => $vars['due_amount'],
                'ok' => $resp['success'] ?? false,
            ];
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
        if (function_exists('sms_log')) sms_log('DUE REMINDER error: '.$e->getMessage());
    }
}

// Load dropdown data
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ফি বকেয়া স্মারক (SMS)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container py-3">
    <h4>ফি বকেয়া স্মারক (SMS)</h4>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <?php if (!empty($sent)): ?>
        <div class="alert alert-info">
            মোট পাঠানো: <?php echo count($sent); ?>
            <div class="small mt-2">
                <?php foreach ($sent as $s): ?>
                    <div>→ <?php echo htmlspecialchars($s['student']); ?> | Due: <?php echo htmlspecialchars($s['due']); ?> | <?php echo $s['ok']? 'OK':'FAIL'; ?></div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body">
            <form method="post">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">সেশন</label>
                        <select name="session" class="form-select">
                            <option value="">সব</option>
                            <?php foreach($sessions as $s): ?>
                                <option value="<?php echo htmlspecialchars($s['session_name']); ?>"><?php echo htmlspecialchars($s['session_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">ক্লাস</label>
                        <select name="class_id" class="form-select">
                            <option value="">সব</option>
                            <?php foreach($classes as $c): ?>
                                <option value="<?php echo (int)$c['id']; ?>"><?php echo htmlspecialchars($c['name'].' '.$c['section']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">মিনিমাম বকেয়া</label>
                        <input type="number" name="min_due" class="form-control" value="100" step="1">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">সর্বোচ্চ সংখ্যা</label>
                        <input type="number" name="limit" class="form-control" value="200" step="1">
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button class="btn btn-primary w-100" type="submit">স্মারক পাঠান</button>
                    </div>
                </div>
                <div class="form-text mt-2">নোট: config/sms.php এ enabled=true দিন। test_mode=true থাকলে শুধু লগ হবে (backups/sms.log)।</div>
            </form>
        </div>
    </div>
</body>
</html>