<?php
/** WhatsApp communications hub (whatsapp_comms add-on). */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }

require_once 'config.php';
requireModule('whatsapp_comms');
require_once __DIR__ . '/includes/whatsapp_lib.php';

$conn = getDBConnection();
wa_ensure_tables($conn);
$role      = $_SESSION['role'] ?? '';
$isAdmin   = in_array($role, ['admin', 'headteacher'], true);
$configured = wa_is_configured();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WhatsApp — EduTrack</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 rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar"><?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?></nav>
    <div class="main-content">
        <header class="header">
            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div class="header-right"><span class="text-muted"><i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?></span></div>
        </header>
        <main class="content">
            <div class="content-header d-flex align-items-center gap-3">
                <div style="background:linear-gradient(135deg,#25D366,#128C7E);border-radius:12px;width:44px;height:44px;display:flex;align-items:center;justify-content:center;">
                    <i class="fab fa-whatsapp text-white fa-lg"></i>
                </div>
                <div>
                    <h2 class="mb-0">WhatsApp Communications</h2>
                    <p class="text-muted mb-0 small">Meta Cloud API · parent messaging &amp; report delivery</p>
                </div>
                <span class="ms-auto badge <?php echo $configured ? 'bg-success' : 'bg-secondary'; ?>">
                    <?php echo $configured ? 'Connected' : 'Not configured'; ?>
                </span>
            </div>

            <div class="row g-3">
                <!-- Broadcast -->
                <div class="col-lg-6">
                    <div class="card"><div class="card-body">
                        <h5><i class="fas fa-bullhorn me-2 text-success"></i>Send Message</h5>
                        <p class="text-muted small">Free-form text reaches parents who messaged the school number in the last 24h; others receive it when they next reply.</p>
                        <div class="mb-2"><label class="form-label small">Recipient number(s)</label>
                            <textarea id="bcNumbers" class="form-control" rows="2" placeholder="0241234567, 0209876543"></textarea></div>
                        <div class="mb-2"><label class="form-label small">Message</label>
                            <textarea id="bcMessage" class="form-control" rows="4"></textarea></div>
                        <button class="btn btn-success" id="bcSend"><i class="fab fa-whatsapp me-1"></i>Send</button>
                        <span id="bcMsg" class="ms-2 small"></span>
                    </div></div>
                </div>

                <!-- Settings -->
                <div class="col-lg-6">
                    <?php if ($isAdmin): ?>
                    <div class="card"><div class="card-body">
                        <h5><i class="fas fa-gear me-2 text-secondary"></i>Connection Settings</h5>
                        <div class="mb-2"><label class="form-label small">Phone Number ID</label>
                            <input id="stPhoneId" class="form-control" placeholder="Meta phone number ID"></div>
                        <div class="mb-2"><label class="form-label small">Access Token <span class="text-muted">(leave blank to keep existing)</span></label>
                            <input id="stToken" type="password" class="form-control" placeholder="Permanent access token"></div>
                        <div class="mb-2"><label class="form-label small">Webhook Verify Token</label>
                            <input id="stVerify" class="form-control" placeholder="A secret you choose"></div>
                        <div class="mb-2"><label class="form-label small">Default report recipients</label>
                            <input id="stRecipients" class="form-control" placeholder="Comma-separated numbers"></div>
                        <div class="alert alert-light border small py-2">
                            <b>Webhook URL:</b> <code id="hookUrl"></code><br>
                            Set this callback URL + the verify token in your Meta app.
                        </div>
                        <button class="btn btn-primary btn-sm" id="stSave">Save</button>
                        <hr>
                        <div class="input-group input-group-sm">
                            <input id="testTo" class="form-control" placeholder="Test number e.g. 0241234567">
                            <button class="btn btn-outline-success" id="testBtn">Send test</button>
                        </div>
                        <span id="testMsg" class="small"></span>
                    </div></div>
                    <?php endif; ?>
                </div>

                <!-- Log -->
                <div class="col-12">
                    <div class="card"><div class="card-body">
                        <h5><i class="fas fa-list me-2 text-muted"></i>Recent Messages</h5>
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead class="table-light"><tr><th>Time</th><th>To</th><th>Type</th><th>Preview</th><th>Status</th></tr></thead>
                                <tbody id="logBody"><tr><td colspan="5" class="text-center text-muted py-3">Loading…</td></tr></tbody>
                            </table>
                        </div>
                    </div></div>
                </div>
            </div>
        </main>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="js/main.js"></script>
<script>
const IS_ADMIN = <?php echo $isAdmin ? 'true' : 'false'; ?>;
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}

function loadLog(){
  fetch('ajax/whatsapp.php?action=get_log').then(r=>r.json()).then(d=>{
    const b=document.getElementById('logBody');
    if(!d.success||!d.data.length){b.innerHTML='<tr><td colspan="5" class="text-center text-muted py-3">No messages yet.</td></tr>';return;}
    b.innerHTML=d.data.map(x=>`<tr>
      <td class="small text-muted">${esc(x.sent_at)}</td><td>${esc(x.to_number)}</td>
      <td><span class="badge bg-light text-dark">${esc(x.message_type)}</span></td>
      <td class="small">${esc((x.message_preview||'').slice(0,60))}</td>
      <td>${x.status==='sent'?'<span class="badge bg-success">sent</span>':'<span class="badge bg-danger" title="'+esc(x.error_message||'')+'">failed</span>'}</td>
    </tr>`).join('');
  });
}
document.getElementById('bcSend').addEventListener('click',function(){
  const fd=new FormData();fd.append('action','broadcast');
  fd.append('numbers',document.getElementById('bcNumbers').value);
  fd.append('message',document.getElementById('bcMessage').value);
  this.disabled=true;
  fetch('ajax/whatsapp.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    this.disabled=false;document.getElementById('bcMsg').textContent=d.message;
    if(d.success){document.getElementById('bcMessage').value='';loadLog();}
  });
});
if(IS_ADMIN){
  fetch('ajax/whatsapp.php?action=get_settings').then(r=>r.json()).then(d=>{
    if(!d.success)return;
    document.getElementById('stPhoneId').value=d.phone_id||'';
    document.getElementById('stVerify').value=d.verify_token||'';
    document.getElementById('stRecipients').value=d.recipients||'';
    document.getElementById('hookUrl').textContent=d.webhook_url||'';
    if(d.has_token)document.getElementById('stToken').placeholder='•••••••• (saved — leave blank to keep)';
  });
  document.getElementById('stSave').addEventListener('click',function(){
    const fd=new FormData();fd.append('action','save_settings');
    fd.append('phone_id',document.getElementById('stPhoneId').value);
    fd.append('token',document.getElementById('stToken').value);
    fd.append('verify_token',document.getElementById('stVerify').value);
    fd.append('recipients',document.getElementById('stRecipients').value);
    fetch('ajax/whatsapp.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{alert(d.message);if(d.success)location.reload();});
  });
  document.getElementById('testBtn').addEventListener('click',function(){
    const fd=new FormData();fd.append('action','test_send');fd.append('to',document.getElementById('testTo').value);
    fetch('ajax/whatsapp.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{document.getElementById('testMsg').textContent=d.message;});
  });
}
loadLog();
</script>
</body>
</html>
