<?php
// admin/sms-manager.php - Smart Bulk SMS Manager
session_start();
require_once '../includes/config.php';
require_once '../includes/sms_config.php';

if(!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
    header('Location: ../auth.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$tab = $_GET['tab'] ?? 'send';
$message = '';
$msg_type = 'info';

// ==================== SEND SMS ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_sms'])) {
    $sms_text = trim($_POST['sms_message']);
    $filter_type = $_POST['filter_type'];
    $course_id = $_POST['course_id'] ?? null;
    $category_id = $_POST['category_id'] ?? null;
    $single_phone = trim($_POST['single_phone'] ?? '');
    $schedule = isset($_POST['schedule_sms']);
    $schedule_time = $_POST['schedule_time'] ?? null;
    
    if(empty($sms_text)) {
        $message = 'মেসেজ লিখুন';
        $msg_type = 'danger';
    } elseif($filter_type == 'single' && empty($single_phone)) {
        $message = 'ফোন নম্বর লিখুন';
        $msg_type = 'danger';
    } else {
        if($schedule && $schedule_time) {
            $pdo->prepare("INSERT INTO scheduled_sms (sender_id, recipient_type, course_id, recipient_phone, message, scheduled_at) VALUES (?, ?, ?, ?, ?, ?)")
                ->execute([$user_id, $filter_type, $course_id, $single_phone, $sms_text, $schedule_time]);
            $message = '✅ SMS শিডিউল করা হয়েছে!';
            $msg_type = 'success';
        } else {
            $sent = 0;
            if($filter_type == 'single') {
                if(isset($sms) && $sms->sendSMS($single_phone, $sms_text)) $sent = 1;
            } else {
                $query = "SELECT u.id, u.full_name, u.phone FROM users u WHERE u.role='student' AND u.phone IS NOT NULL AND u.phone != ''";
                $params = [];
                if($filter_type == 'course' && $course_id) { $query .= " AND u.id IN (SELECT user_id FROM enrollments WHERE course_id=? AND payment_status='completed')"; $params[] = $course_id; }
                elseif($filter_type == 'category' && $category_id) { $query .= " AND u.id IN (SELECT e.user_id FROM enrollments e JOIN courses c ON e.course_id=c.id WHERE c.category_id=? AND e.payment_status='completed')"; $params[] = $category_id; }
                $stmt = $pdo->prepare($query); $stmt->execute($params);
                if(isset($sms)) foreach($stmt->fetchAll() as $r) { if($sms->sendSMS($r['phone'], str_replace('{name}', $r['full_name'], $sms_text))) $sent++; }
            }
            $pdo->prepare("INSERT INTO bulk_sms_logs (admin_id, course_id, recipient_count, message) VALUES (?, ?, ?, ?)")->execute([$user_id, $course_id, $sent, $sms_text]);
            $message = "✅ $sent জনকে SMS পাঠানো হয়েছে!";
            $msg_type = 'success';
        }
    }
}

// ==================== DELETE SCHEDULED ====================
if(isset($_GET['delete_scheduled'])) {
    $pdo->prepare("DELETE FROM scheduled_sms WHERE id = ?")->execute([$_GET['delete_scheduled']]);
    header('Location: sms-manager.php?tab=scheduled&msg=শিডিউল+ডিলিট+হয়েছে&type=success');
    exit;
}

$msg = $_GET['msg'] ?? $message;
$msg_type = $_GET['type'] ?? $msg_type;

$courses = $pdo->query("SELECT id, title_bn FROM courses WHERE status='published' ORDER BY title_bn")->fetchAll();
$categories = $pdo->query("SELECT * FROM categories ORDER BY name_bn")->fetchAll();
$sms_logs = $pdo->query("SELECT * FROM bulk_sms_logs ORDER BY sent_at DESC LIMIT 20")->fetchAll();
$scheduled = $pdo->query("SELECT ss.*, c.title_bn as course_name FROM scheduled_sms ss LEFT JOIN courses c ON ss.course_id=c.id WHERE ss.is_sent=0 ORDER BY ss.scheduled_at ASC")->fetchAll();

// Test SMS balance
$balance = null;
if(!empty($sms->api_key)) {
    $ch = curl_init('https://bulksmsbd.net/api/getBalanceApi?api_key=' . $sms->api_key);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $res = curl_exec($ch); curl_close($ch);
    $data = json_decode($res, true);
    $balance = $data['balance'] ?? null;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS ম্যানেজার - বাংলা LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    <style>
        :root { --primary: #6C5CE7; --g1: linear-gradient(135deg, #667eea, #764ba2); --g2: linear-gradient(135deg, #f093fb, #f5576c); --g3: linear-gradient(135deg, #4facfe, #00f2fe); --g4: linear-gradient(135deg, #43e97b, #38f9d7); --g5: linear-gradient(135deg, #fa709a, #fee140); --shadow: 0 3px 15px rgba(0,0,0,0.08); --dark: #1a1a2e; }
        * { margin:0; padding:0; box-sizing:border-box; }
        body { background:#f0f2f8; font-family:'Segoe UI','Hind Siliguri',Arial,sans-serif; }
        .navbar { background:white; box-shadow:0 2px 10px rgba(0,0,0,0.06); padding:12px 0; position:sticky; top:0; z-index:1000; }
        .navbar-brand { font-weight:800; font-size:1.2rem; color:var(--primary)!important; text-decoration:none; }
        .container { max-width:1200px; margin:0 auto; padding:20px; }
        
        .page-header { background:var(--g1); color:white; border-radius:20px; padding:25px 30px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:15px; margin-bottom:20px; position:relative; overflow:hidden; }
        .page-header::after { content:''; position:absolute; right:-20px; top:-20px; width:120px; height:120px; background:rgba(255,255,255,0.1); border-radius:50%; }
        .page-header h3 { font-weight:700; position:relative; z-index:1; margin:0; }
        
        .nav-pills { gap:8px; margin-bottom:20px; }
        .nav-pills .nav-link { border-radius:50px; padding:10px 22px; font-weight:600; border:2px solid #e0e0e0; color:#555; }
        .nav-pills .nav-link.active { background:var(--g1); color:white; border-color:transparent; }
        
        .balance-card { background:white; border-radius:15px; padding:20px; box-shadow:var(--shadow); display:flex; align-items:center; gap:15px; margin-bottom:15px; transition:0.3s; }
        .balance-card:hover { transform:translateY(-3px); }
        .balance-icon { width:55px; height:55px; border-radius:14px; display:flex; align-items:center; justify-content:center; font-size:1.5rem; color:white; }
        .balance-value { font-size:1.8rem; font-weight:800; color:var(--dark); }
        .balance-label { color:#888; font-size:0.8rem; }
        
        .main-card { background:white; border-radius:15px; padding:25px; box-shadow:var(--shadow); margin-bottom:20px; }
        .section-title { font-weight:700; font-size:1.1rem; margin-bottom:18px; display:flex; align-items:center; gap:8px; }
        
        .form-control,.form-select,textarea { border-radius:10px; padding:10px 15px; border:2px solid #e8eaef; width:100%; margin-bottom:10px; font-size:0.9rem; background:#fafbfd; }
        .form-control:focus,.form-select:focus { border-color:var(--primary); outline:none; background:white; }
        
        .btn { border-radius:50px; padding:10px 24px; font-weight:600; cursor:pointer; transition:0.3s; border:none; }
        .btn-primary { background:var(--g1); color:white; }
        .btn-primary:hover { transform:translateY(-2px); box-shadow:0 8px 20px rgba(108,92,231,0.3); }
        .btn-sm { padding:6px 14px; font-size:0.8rem; }
        .btn-outline { border:2px solid var(--primary); color:var(--primary); background:white; }
        
        .char-count { font-size:0.8rem; color:#888; text-align:right; }
        .template-chip { display:inline-block; padding:8px 14px; border-radius:50px; background:#f8f9ff; border:1px solid #e0e0e0; cursor:pointer; font-size:0.8rem; margin:3px; transition:0.3s; }
        .template-chip:hover { background:var(--primary); color:white; border-color:var(--primary); }
        
        .log-item { padding:12px 15px; border-radius:10px; margin-bottom:6px; background:#f8f9fa; font-size:0.85rem; display:flex; justify-content:space-between; align-items:center; }
        .log-item:hover { background:#f0f0ff; }
        
        .status-dot { width:10px; height:10px; border-radius:50%; display:inline-block; }
        .toggle-switch { position:relative; display:inline-block; width:48px; height:24px; }
        .toggle-switch input { opacity:0; width:0; height:0; }
        .toggle-slider { position:absolute; cursor:pointer; top:0; left:0; right:0; bottom:0; background:#ccc; transition:0.3s; border-radius:24px; }
        .toggle-slider:before { content:""; position:absolute; height:18px; width:18px; left:3px; bottom:3px; background:white; transition:0.3s; border-radius:50%; }
        input:checked + .toggle-slider { background:var(--primary); }
        input:checked + .toggle-slider:before { transform:translateX(24px); }
        
        @media (max-width:768px) { .page-header { text-align:center; justify-content:center; } }
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container" style="display:flex;justify-content:space-between;align-items:center;">
        <a href="dashboard.php" class="navbar-brand"><i class="fas fa-graduation-cap me-2"></i>অ্যাডমিন প্যানেল</a>
        <div class="d-flex gap-2">
            <a href="dashboard.php" class="btn btn-outline btn-sm rounded-pill">ড্যাশবোর্ড</a>
            <a href="../logout.php" class="btn btn-sm rounded-pill" style="background:#ff4757;color:white;">লগআউট</a>
        </div>
    </div>
</nav>

<div class="container">
    
    <!-- Header -->
    <div class="page-header" data-aos="fade-down">
        <div>
            <h3><i class="fas fa-sms me-2"></i>Bulk SMS ম্যানেজার</h3>
            <p style="opacity:0.9;margin:5px 0 0;">BulkSMSBD এর মাধ্যমে শিক্ষার্থীদের SMS পাঠান</p>
        </div>
        <div style="position:relative;z-index:1;">
            <span style="background:rgba(255,255,255,0.2);padding:8px 18px;border-radius:50px;font-weight:600;font-size:0.9rem;">
                <span class="status-dot" style="background:<?= $balance !== null ? '#43e97b' : '#ff4757' ?>;"></span>
                <?= $balance !== null ? '✅ কানেক্টেড' : '⚠️ API সেট করুন' ?>
            </span>
        </div>
    </div>
    
    <!-- Balance Cards -->
    <div class="row g-3 mb-3">
        <div class="col-md-4" data-aos="fade-up"><div class="balance-card"><div class="balance-icon" style="background:var(--g1);"><i class="fas fa-coins"></i></div><div><div class="balance-value"><?= $balance !== null ? number_format($balance) : 'N/A' ?></div><div class="balance-label">SMS ব্যালেন্স</div></div></div></div>
        <div class="col-md-4" data-aos="fade-up" data-aos-delay="100"><div class="balance-card"><div class="balance-icon" style="background:var(--g2);"><i class="fas fa-paper-plane"></i></div><div><div class="balance-value"><?= count($sms_logs) ?></div><div class="balance-label">ক্যাম্পেইন</div></div></div></div>
        <div class="col-md-4" data-aos="fade-up" data-aos-delay="200"><div class="balance-card"><div class="balance-icon" style="background:var(--g3);"><i class="fas fa-clock"></i></div><div><div class="balance-value"><?= count($scheduled) ?></div><div class="balance-label">শিডিউলকৃত</div></div></div></div>
    </div>
    
    <!-- Tabs -->
    <ul class="nav nav-pills" data-aos="fade-up">
        <li class="nav-item"><a class="nav-link <?= $tab=='send'?'active':'' ?>" href="?tab=send"><i class="fas fa-paper-plane me-1"></i> SMS পাঠান</a></li>
        <li class="nav-item"><a class="nav-link <?= $tab=='config'?'active':'' ?>" href="?tab=config"><i class="fas fa-cog me-1"></i> কনফিগারেশন</a></li>
        <li class="nav-item"><a class="nav-link <?= $tab=='logs'?'active':'' ?>" href="?tab=logs"><i class="fas fa-history me-1"></i> লগ (<?= count($sms_logs) ?>)</a></li>
        <li class="nav-item"><a class="nav-link <?= $tab=='scheduled'?'active':'' ?>" href="?tab=scheduled"><i class="fas fa-clock me-1"></i> শিডিউল (<?= count($scheduled) ?>)</a></li>
    </ul>
    
    <!-- Message -->
    <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> rounded-3"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
    
    <!-- SEND TAB -->
    <?php if($tab == 'send'): ?>
        <div class="row">
            <div class="col-lg-7" data-aos="fade-right">
                <div class="main-card">
                    <div class="section-title"><i class="fas fa-paper-plane text-primary"></i> নতুন SMS ক্যাম্পেইন</div>
                    <form method="POST">
                        <input type="hidden" name="send_sms" value="1">
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">পাঠানোর ধরণ</label>
                                <select name="filter_type" class="form-select" onchange="toggleFilter(this.value)" required>
                                    <option value="all">🌐 সকল শিক্ষার্থী</option>
                                    <option value="course">📚 নির্দিষ্ট কোর্স</option>
                                    <option value="category">📂 নির্দিষ্ট ক্যাটাগরি</option>
                                    <option value="single">👤 একক নম্বর</option>
                                </select>
                            </div>
                            <div class="col-md-6" id="courseSelect" style="display:none;">
                                <label class="form-label fw-bold small">কোর্স</label>
                                <select name="course_id" class="form-select"><?php foreach($courses as $c): ?><option value="<?=$c['id']?>"><?=htmlspecialchars($c['title_bn'])?></option><?php endforeach; ?></select>
                            </div>
                            <div class="col-md-6" id="categorySelect" style="display:none;">
                                <label class="form-label fw-bold small">ক্যাটাগরি</label>
                                <select name="category_id" class="form-select"><?php foreach($categories as $cat): ?><option value="<?=$cat['id']?>"><?=htmlspecialchars($cat['name_bn'])?></option><?php endforeach; ?></select>
                            </div>
                            <div class="col-md-6" id="phoneInput">
                                <label class="form-label fw-bold small">ফোন নম্বর</label>
                                <input type="text" name="single_phone" class="form-control" placeholder="01XXXXXXXXX">
                            </div>
                        </div>
                        <label class="form-label fw-bold small mt-2">মেসেজ</label>
                        <textarea name="sms_message" id="smsMsg" class="form-control" rows="5" placeholder="মেসেজ লিখুন...&#10;{name} = শিক্ষার্থীর নাম" oninput="countChars()" required></textarea>
                        <div class="char-count" id="charCount">০ / ৪৮০ অক্ষর (০ SMS)</div>
                        
                        <div class="d-flex align-items-center gap-3 mt-3 p-3 rounded-3" style="background:#f8f9ff;">
                            <label class="form-check-label fw-bold small" for="scheduleCheck">
                                <input type="checkbox" name="schedule_sms" id="scheduleCheck" class="form-check-input" onchange="toggleSchedule()"> ⏰ শিডিউল করে পাঠান
                            </label>
                            <input type="datetime-local" name="schedule_time" id="scheduleTime" class="form-control" style="width:250px;display:none;">
                        </div>
                        <button type="submit" class="btn btn-primary w-100 mt-3"><i class="fas fa-paper-plane me-2"></i>SMS পাঠান</button>
                    </form>
                </div>
            </div>
            <div class="col-lg-5" data-aos="fade-left">
                <div class="main-card">
                    <div class="section-title"><i class="fas fa-clipboard-list text-primary"></i> টেমপ্লেট</div>
                    <div>
                        <span class="template-chip" onclick="setTemplate('প্রিয় {name},\n\nআপনার এনরোলমেন্ট অনুমোদিত হয়েছে। এখনই কোর্স শুরু করুন!\n\n- বাংলা LMS')">✅ এনরোলমেন্ট</span>
                        <span class="template-chip" onclick="setTemplate('প্রিয় {name},\n\nআপনার কোর্সে নতুন কন্টেন্ট যোগ হয়েছে। ভিজিট: onesbd.com/LMS\n\n- বাংলা LMS')">🆕 কন্টেন্ট</span>
                        <span class="template-chip" onclick="setTemplate('প্রিয় {name},\n\nপেমেন্ট পেন্ডিং আছে। সম্পন্ন করুন।\n\n- বাংলা LMS')">💳 পেমেন্ট</span>
                        <span class="template-chip" onclick="setTemplate('🔴 লাইভ ক্লাস!\n\nপ্রিয় {name}, আগামীকাল রাত ৯টায় লাইভ ক্লাস।\n\n- বাংলা LMS')">🔴 লাইভ ক্লাস</span>
                        <span class="template-chip" onclick="setTemplate('প্রিয় {name},\n\nকোর্সের মেয়াদ শেষ হতে চলেছে। রিনিউ করুন।\n\n- বাংলা LMS')">⏰ মেয়াদ</span>
                        <span class="template-chip" onclick="setTemplate('শুভেচ্ছা {name},\n\nঈদ মোবারক! বাংলা LMS পরিবারের পক্ষ থেকে শুভেচ্ছা।')">🎉 উৎসব</span>
                    </div>
                    <hr>
                    <div class="section-title"><i class="fas fa-info-circle text-info"></i> তথ্য</div>
                    <ul class="small text-muted"><li>১ SMS = ১৬০ অক্ষর</li><li>৪৮০ অক্ষর = ৩ SMS</li><li><code>{name}</code> = শিক্ষার্থীর নাম</li><li>সর্বোচ্চ ১০,০০০/দিন</li></ul>
                </div>
            </div>
        </div>
    <?php endif; ?>
    
    <!-- CONFIG TAB -->
    <?php if($tab == 'config'): ?>
        <div class="main-card" data-aos="fade-up">
            <div class="section-title"><i class="fas fa-cog text-primary"></i> BulkSMSBD কনফিগারেশন</div>
            <form method="POST" action="save-sms-config.php">
                <div class="row">
                    <div class="col-md-6"><div class="p-4 rounded-4 mb-3" style="background:#f8f9ff;"><h6 class="fw-bold mb-3"><i class="fas fa-key text-primary me-2"></i>API Credentials</h6><label class="form-label fw-bold small">API Key *</label><input type="text" name="api_key" class="form-control" value="<?= htmlspecialchars($sms->api_key ?? '') ?>" placeholder="BulkSMSBD API Key"><small class="text-muted"><a href="https://bulksmsbd.net/panel" target="_blank">bulksmsbd.net/panel</a> থেকে পান</small><label class="form-label fw-bold small mt-2">Sender ID *</label><input type="text" name="sender_id" class="form-control" value="<?= htmlspecialchars($sms->sender_id ?? '') ?>" placeholder="অনুমোদিত Sender ID"><small class="text-muted">সর্বোচ্চ ১১ অক্ষর</small></div></div>
                    <div class="col-md-6"><div class="p-4 rounded-4 mb-3" style="background:#f8f9ff;"><h6 class="fw-bold mb-3"><i class="fas fa-toggle-on text-success me-2"></i>সেটিংস</h6>
                        <div class="d-flex justify-content-between align-items-center mb-3"><span>OTP ভেরিফিকেশন</span><label class="toggle-switch"><input type="checkbox" name="enable_otp" <?= ($sms->enable_otp ?? true) ? 'checked' : '' ?>><span class="toggle-slider"></span></label></div>
                        <div class="d-flex justify-content-between align-items-center mb-3"><span>কেনাকাটার SMS</span><label class="toggle-switch"><input type="checkbox" name="enable_purchase" <?= ($sms->enable_purchase ?? true) ? 'checked' : '' ?>><span class="toggle-slider"></span></label></div>
                        <div class="d-flex justify-content-between align-items-center mb-3"><span>রিমাইন্ডার SMS</span><label class="toggle-switch"><input type="checkbox" name="enable_reminder" <?= ($sms->enable_reminder ?? false) ? 'checked' : '' ?>><span class="toggle-slider"></span></label></div>
                        <div class="d-flex justify-content-between align-items-center"><span>লাইভ ক্লাস SMS</span><label class="toggle-switch"><input type="checkbox" name="enable_live_class" <?= ($sms->enable_live_class ?? false) ? 'checked' : '' ?>><span class="toggle-slider"></span></label></div>
                    </div></div>
                </div>
                <button type="submit" class="btn btn-primary w-100"><i class="fas fa-save me-2"></i>কনফিগারেশন সংরক্ষণ</button>
            </form>
        </div>
    <?php endif; ?>
    
    <!-- LOGS TAB -->
    <?php if($tab == 'logs'): ?>
        <div class="main-card" data-aos="fade-up">
            <div class="section-title"><i class="fas fa-history text-primary"></i> SMS লগ (<?= count($sms_logs) ?>)</div>
            <?php if(count($sms_logs) > 0): ?>
                <?php foreach($sms_logs as $log): ?><div class="log-item"><div><strong><?= $log['recipient_count'] ?> জন</strong><br><small class="text-muted"><?= mb_substr($log['message'], 0, 50) ?>...</small></div><small class="text-muted"><?= date('d/m/y H:i', strtotime($log['sent_at'])) ?></small></div><?php endforeach; ?>
            <?php else: ?><p class="text-muted text-center py-4">কোন SMS লগ নেই</p><?php endif; ?>
        </div>
    <?php endif; ?>
    
    <!-- SCHEDULED TAB -->
    <?php if($tab == 'scheduled'): ?>
        <div class="main-card" data-aos="fade-up">
            <div class="section-title"><i class="fas fa-clock text-primary"></i> শিডিউলকৃত SMS (<?= count($scheduled) ?>)</div>
            <?php if(count($scheduled) > 0): ?>
                <?php foreach($scheduled as $s): ?><div class="log-item"><div><span class="badge bg-warning text-dark me-2">⏰ <?= date('d/m/y H:i', strtotime($s['scheduled_at'])) ?></span> <?= mb_substr($s['message'], 0, 40) ?>...</div><a href="?delete_scheduled=<?=$s['id']?>&tab=scheduled" class="btn btn-danger btn-sm" onclick="return confirm('ডিলিট?')"><i class="fas fa-trash"></i></a></div><?php endforeach; ?>
            <?php else: ?><p class="text-muted text-center py-4">কোন শিডিউলকৃত SMS নেই</p><?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script>
AOS.init({duration:700,once:true});
function toggleFilter(v){document.getElementById('courseSelect').style.display=v==='course'?'block':'none';document.getElementById('categorySelect').style.display=v==='category'?'block':'none';document.getElementById('phoneInput').style.display=v==='single'?'block':'none';}
function toggleSchedule(){document.getElementById('scheduleTime').style.display=document.getElementById('scheduleCheck').checked?'block':'none';}
function setTemplate(t){document.getElementById('smsMsg').value=t;countChars();document.querySelector('[href="?tab=send"]').click();}
function countChars(){var l=document.getElementById('smsMsg').value.length;var s=Math.ceil(l/160);document.getElementById('charCount').textContent=l+' / ৪৮০ অক্ষর ('+s+' SMS)';}
</script>
</body>
</html>