<?php
error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/php_errors.log');
session_start();

// ── Config ─────────────────────────────────────────────────────────────────
const API_KEY              = 'KEY019DFF54FF6EA6AC0E3328883A1B0AFE_o5GukBjSOe6vfWY5NWJgSA';
const FROM_NUMBER          = '+18449614559';
const MESSAGING_PROFILE_ID = '40019d4f-df44-4d30-ac25-d95cd8ba22d9';
const DB_FILE              = __DIR__ . '/dashboard.db';

// ── Database ────────────────────────────────────────────────────────────────
function db(): PDO {
    static $pdo;
    if (!$pdo) {
        $pdo = new PDO('sqlite:' . DB_FILE);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS contacts (
                id         INTEGER PRIMARY KEY AUTOINCREMENT,
                name       TEXT,
                phone      TEXT UNIQUE NOT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS messages (
                id            INTEGER PRIMARY KEY AUTOINCREMENT,
                telnyx_id     TEXT UNIQUE,
                contact_phone TEXT NOT NULL,
                direction     TEXT NOT NULL,
                body          TEXT NOT NULL,
                status        TEXT DEFAULT 'queued',
                cost          REAL DEFAULT 0,
                created_at    DATETIME DEFAULT CURRENT_TIMESTAMP
            );
        ");
    }
    return $pdo;
}

// ── Telnyx API helper ───────────────────────────────────────────────────────
function telnyx(string $method, string $path, array $data = []): array {
    $url = 'https://api.telnyx.com/v2' . $path;
    if ($method === 'GET' && $data) $url .= '?' . http_build_query($data);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . API_KEY,
            'Content-Type: application/json',
        ],
    ]);
    if ($data && $method !== 'GET') curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['code' => $code, 'body' => json_decode($resp, true)];
}

function normalizePhone(string $phone): string {
    $phone  = preg_replace('/[^\x20-\x7E]/', '', $phone); // strip non-ASCII (invisible unicode chars)
    $digits = preg_replace('/\D/', '', $phone);
    if (strlen($digits) === 10) $digits = '1' . $digits;
    return '+' . $digits;
}

function sendSMS(string $to, string $text): array {
    $to   = normalizePhone($to);
    $webhookUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['PHP_SELF'] ?? '');
    $resp = telnyx('POST', '/messages', [
        'from'                 => FROM_NUMBER,
        'to'                   => $to,
        'text'                 => $text,
        'messaging_profile_id' => MESSAGING_PROFILE_ID,
        'webhook_url'          => $webhookUrl,
    ]);
    if ($resp['code'] < 300 && isset($resp['body']['data'])) {
        $msg = $resp['body']['data'];
        db()->prepare("INSERT OR IGNORE INTO contacts (phone) VALUES (?)")->execute([$to]);
        db()->prepare("
            INSERT OR IGNORE INTO messages (telnyx_id, contact_phone, direction, body, status)
            VALUES (?, ?, 'outbound', ?, ?)
        ")->execute([$msg['id'], $to, $text, $msg['to'][0]['status'] ?? 'queued']);
    }
    return $resp;
}

// ── Webhook handler ─────────────────────────────────────────────────────────
$rawInput = file_get_contents('php://input');
$webhook  = json_decode($rawInput, true);
if ($webhook && isset($webhook['data']['event_type'])) {
    // Log every webhook for debugging — tail webhook.log on your server to inspect
    file_put_contents(__DIR__ . '/webhook.log',
        date('Y-m-d H:i:s') . ' ' . json_encode($webhook) . "\n",
        FILE_APPEND | LOCK_EX
    );

    $event = $webhook['data'];
    $msg   = $event['payload'];
    $type  = $event['event_type'];

    if ($type === 'message.received') {
        $from = is_array($msg['from']) ? ($msg['from']['phone_number'] ?? '') : $msg['from'];
        $from = normalizePhone($from);
        $body = $msg['text'] ?? $msg['body'] ?? '';
        $id   = $msg['id'] ?? uniqid('in_', true);
        db()->prepare("INSERT OR IGNORE INTO contacts (phone) VALUES (?)")->execute([$from]);
        db()->prepare("
            INSERT OR IGNORE INTO messages (telnyx_id, contact_phone, direction, body, status)
            VALUES (?, ?, 'inbound', ?, 'received')
        ")->execute([$id, $from, $body]);
    }

    // message.sent fires first — update status + cost (cost is already available here)
    if ($type === 'message.sent') {
        $cost = $msg['cost']['amount'] ?? 0;
        db()->prepare("UPDATE messages SET status='sent', cost=? WHERE telnyx_id=?")
            ->execute([$cost, $msg['id']]);
    }

    // message.finalized fires last — final delivery status + cost
    if ($type === 'message.finalized') {
        $status = $msg['to'][0]['status'] ?? 'unknown';
        $cost   = $msg['cost']['amount'] ?? 0;
        if (!$cost && isset($msg['parts'])) {
            foreach ($msg['parts'] as $part) $cost += $part['cost']['amount'] ?? 0;
        }
        db()->prepare("UPDATE messages SET status=?, cost=? WHERE telnyx_id=?")
            ->execute([$status, $cost, $msg['id']]);
    }

    http_response_code(200);
    exit;
}

// ── Actions ─────────────────────────────────────────────────────────────────
$action = $_POST['action'] ?? $_GET['action'] ?? '';
$result = null;

if ($action === 'send') {
    $normalized = normalizePhone(trim($_POST['to']));
    $resp = sendSMS($normalized, trim($_POST['text']));
    if ($resp['code'] < 300) {
        $returnView = $_POST['return_view'] ?? 'dashboard';
        header("Location: ?view=$returnView&phone=" . urlencode($normalized) . "&sent=1");
        exit;
    }
    $result = ['error' => ($resp['body']['errors'][0]['detail'] ?? 'Send failed') . " (to: $normalized)"];
}

if ($action === 'broadcast') {
    $numbers = array_filter(array_map(fn($n) => normalizePhone(trim($n)), explode("\n", $_POST['numbers'])));
    $text    = trim($_POST['text']);
    $sent = $failed = 0;
    foreach ($numbers as $num) {
        sendSMS($num, $text)['code'] < 300 ? $sent++ : $failed++;
        usleep(100000); // 100 ms between sends
    }
    $result = ['broadcast' => true, 'sent' => $sent, 'failed' => $failed];
}

if ($action === 'add_contact') {
    db()->prepare("INSERT OR IGNORE INTO contacts (name, phone) VALUES (?, ?)")
        ->execute([trim($_POST['name']), normalizePhone(trim($_POST['phone']))]);
    $result = ['ok' => true];
}

if ($action === 'delete_contact') {
    db()->prepare("DELETE FROM contacts WHERE phone=?")->execute([$_POST['phone']]);
    $result = ['ok' => true];
}

if ($action === 'sync') {
    $stmt = db()->query("
        SELECT telnyx_id FROM messages
        WHERE direction='outbound' AND status IN ('queued','sent') AND telnyx_id IS NOT NULL
        ORDER BY created_at DESC LIMIT 50
    ");
    $rows = [];
    while ($stmt && $row = $stmt->fetch(PDO::FETCH_NUM)) {
        $rows[] = $row[0];
    }

    $synced = 0;
    foreach ($rows as $tid) {
        $resp = telnyx('GET', '/messages/' . urlencode($tid));
        if ($resp['code'] !== 200 || empty($resp['body']['data'])) continue;
        $msg    = $resp['body']['data'];
        $status = $msg['to'][0]['status'] ?? 'unknown';
        $cost   = $msg['cost']['amount'] ?? 0;
        if (!$cost && isset($msg['parts'])) {
            foreach ($msg['parts'] as $part) $cost += $part['cost']['amount'] ?? 0;
        }
        db()->prepare("UPDATE messages SET status=?, cost=? WHERE telnyx_id=?")
            ->execute([$status, $cost, $tid]);
        $synced++;
        usleep(50000);
    }
    $result = ['synced' => $synced];
}

// Recover a specific message by Telnyx ID (for messages that never got stored locally)
if ($action === 'recover' && !empty($_POST['telnyx_id'])) {
    $tid  = trim($_POST['telnyx_id']);
    $resp = telnyx('GET', '/messages/' . urlencode($tid));
    if ($resp['code'] === 200 && isset($resp['body']['data'])) {
        $msg    = $resp['body']['data'];
        $dir    = $msg['direction'];
        $phone  = $dir === 'outbound'
            ? normalizePhone($msg['to'][0]['phone_number'] ?? '')
            : normalizePhone(is_array($msg['from']) ? ($msg['from']['phone_number'] ?? '') : $msg['from']);
        $status = $dir === 'outbound' ? ($msg['to'][0]['status'] ?? 'unknown') : 'received';
        $cost   = $msg['cost']['amount'] ?? 0;
        db()->prepare("INSERT OR IGNORE INTO contacts (phone) VALUES (?)")->execute([$phone]);
        db()->prepare("
            INSERT OR REPLACE INTO messages (telnyx_id, contact_phone, direction, body, status, cost, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ")->execute([$tid, $phone, $dir, $msg['text'] ?? '', $status, $cost, $msg['created_at']]);
        $result = ['ok' => true, 'detail' => "Recovered: $dir to/from $phone — status: $status"];
    } else {
        $result = ['error' => 'ID not found on Telnyx (HTTP ' . $resp['code'] . ')'];
    }
}

// ── View data ────────────────────────────────────────────────────────────────
$view        = $_GET['view']  ?? 'dashboard';
$activePhone = $_GET['phone'] ?? null;

$contacts = db()->query("SELECT * FROM contacts ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);

$stats = db()->query("
    SELECT
        COUNT(*) as total,
        SUM(direction='outbound') as sent,
        SUM(direction='inbound')  as received,
        COALESCE(SUM(cost), 0)    as spend
    FROM messages
")->fetch(PDO::FETCH_ASSOC);

$recentMessages = db()->query("
    SELECT m.*, c.name FROM messages m
    LEFT JOIN contacts c ON c.phone = m.contact_phone
    ORDER BY m.created_at DESC LIMIT 100
")->fetchAll(PDO::FETCH_ASSOC);

$conversation = [];
if ($activePhone) {
    $stmt = db()->prepare("SELECT * FROM messages WHERE contact_phone=? ORDER BY created_at ASC");
    $stmt->execute([$activePhone]);
    $conversation = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$threads = db()->query("
    SELECT m.contact_phone,
           MAX(m.created_at) as last_at,
           (SELECT body      FROM messages x WHERE x.contact_phone=m.contact_phone ORDER BY created_at DESC LIMIT 1) as last_msg,
           (SELECT direction FROM messages x WHERE x.contact_phone=m.contact_phone ORDER BY created_at DESC LIMIT 1) as last_dir,
           c.name
    FROM messages m
    LEFT JOIN contacts c ON c.phone = m.contact_phone
    GROUP BY m.contact_phone
    ORDER BY last_at DESC
")->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SMS Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
:root { --accent:#7c6af7; --bg:#0f1117; --card:#1a1d27; --border:#2a2d3e; --muted:#a0a0b0; }
*{ box-sizing:border-box }
body { background:var(--bg); color:#e0e0e0; margin:0; font-family:system-ui,sans-serif }
.sidebar { background:var(--card); width:220px; min-height:100vh; position:fixed; top:0; left:0; display:flex; flex-direction:column; border-right:1px solid var(--border) }
.brand { padding:20px; font-size:1.1rem; font-weight:700; color:var(--accent) }
.nav-link { color:var(--muted); padding:10px 20px; display:flex; align-items:center; gap:10px; text-decoration:none; transition:.15s }
.nav-link:hover,.nav-link.active { background:#252838; color:#fff }
.nav-link.active { border-left:3px solid var(--accent) }
.main { margin-left:220px; padding:28px }
.card { background:var(--card); border:1px solid var(--border); border-radius:10px }
.stat-card { border-left:3px solid var(--accent) }
.form-control,.form-select { background:#252838; border-color:var(--border); color:#e0e0e0 }
.form-control:focus,.form-select:focus { background:#252838; border-color:var(--accent); color:#e0e0e0; box-shadow:none }
.form-control::placeholder { color:var(--muted) }
.btn-primary { background:var(--accent); border-color:var(--accent) }
.btn-primary:hover { background:#6a59d1; border-color:#6a59d1 }
.table-dark { --bs-table-bg:transparent; --bs-table-border-color:var(--border) }
/* Chat */
.chat-wrap { height:420px; overflow-y:auto; padding:14px; background:#13151f; border-radius:8px }
.bubble { max-width:72%; padding:9px 14px; border-radius:18px; margin-bottom:6px; font-size:.88rem; line-height:1.4 }
.bubble.out { background:var(--accent); color:#fff; margin-left:auto; border-bottom-right-radius:4px }
.bubble.in  { background:#252838; color:#e0e0e0; margin-right:auto; border-bottom-left-radius:4px }
.bubble-meta { font-size:.68rem; opacity:.55; margin-top:2px }
/* Thread list */
.thread-item { padding:10px 12px; border-radius:8px; cursor:pointer; text-decoration:none; display:block; color:inherit }
.thread-item:hover { background:#252838 }
.thread-item.active { background:#252838; border-left:3px solid var(--accent) }
textarea { resize:vertical }
</style>
</head>
<body>

<aside class="sidebar">
  <div class="brand"><i class="bi bi-chat-dots-fill"></i> SMS Hub</div>
  <nav>
    <a class="nav-link <?= $view==='dashboard'     ?'active':'' ?>" href="?view=dashboard">    <i class="bi bi-speedometer2"></i> Dashboard</a>
    <a class="nav-link <?= $view==='conversations' ?'active':'' ?>" href="?view=conversations"><i class="bi bi-chat-left-text"></i> Conversations</a>
    <a class="nav-link <?= $view==='broadcast'     ?'active':'' ?>" href="?view=broadcast">    <i class="bi bi-megaphone"></i> Broadcast</a>
    <a class="nav-link <?= $view==='contacts'      ?'active':'' ?>" href="?view=contacts">     <i class="bi bi-people"></i> Contacts</a>
    <a class="nav-link <?= $view==='history'       ?'active':'' ?>" href="?view=history">      <i class="bi bi-clock-history"></i> History</a>
    <a class="nav-link <?= $view==='debug'         ?'active':'' ?>" href="?view=debug">        <i class="bi bi-bug"></i> Debug</a>
  </nav>
</aside>

<main class="main">

<?php if ($result): ?>
  <div class="alert <?= isset($result['error'])?'alert-danger':'alert-success' ?> alert-dismissible fade show">
    <?php
    if (isset($result['error']))      echo htmlspecialchars($result['error']);
    elseif (isset($result['broadcast'])) echo "Broadcast complete — {$result['sent']} sent, {$result['failed']} failed.";
    elseif (isset($result['synced'])) echo "Synced {$result['synced']} messages from Telnyx.";
    else echo 'Done!';
    ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
<?php endif; ?>

<?php /* ── DASHBOARD ─────────────────────────────────────────────────────── */ ?>
<?php if ($view === 'dashboard'): ?>

<h4 class="mb-4">Dashboard</h4>
<div class="row g-3 mb-4">
  <?php foreach ([
    ['Total Messages','total','bi-envelope'],
    ['Sent','sent','bi-send'],
    ['Received','received','bi-inbox'],
  ] as [$label,$key,$icon]): ?>
  <div class="col-6 col-md-3">
    <div class="card stat-card p-3 d-flex flex-row align-items-center gap-3">
      <i class="bi <?= $icon ?> fs-3 text-secondary"></i>
      <div><div class="text-muted small"><?= $label ?></div><div class="fs-3 fw-bold"><?= $stats[$key] ?></div></div>
    </div>
  </div>
  <?php endforeach; ?>
  <div class="col-6 col-md-3">
    <div class="card stat-card p-3 d-flex flex-row align-items-center gap-3">
      <i class="bi bi-currency-dollar fs-3 text-secondary"></i>
      <div><div class="text-muted small">Spend (tracked)</div><div class="fs-3 fw-bold">$<?= number_format($stats['spend'],4) ?></div></div>
    </div>
  </div>
</div>

<div class="row g-3">
  <div class="col-md-5">
    <div class="card p-4">
      <h6 class="mb-3">Quick Send</h6>
      <form method="POST">
        <input type="hidden" name="action"      value="send">
        <input type="hidden" name="return_view" value="conversations">
        <div class="mb-2"><input type="text" name="to" class="form-control" placeholder="+12025550001" required></div>
        <div class="mb-3"><textarea name="text" class="form-control" rows="3" placeholder="Message…" required></textarea></div>
        <button class="btn btn-primary w-100"><i class="bi bi-send me-1"></i>Send</button>
      </form>
    </div>
  </div>
  <div class="col-md-7">
    <div class="card p-3">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <h6 class="mb-0">Recent Messages</h6>
        <form method="POST">
          <input type="hidden" name="action" value="sync">
          <button class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-repeat"></i> Sync</button>
        </form>
      </div>
      <?php foreach (array_slice($recentMessages,0,10) as $m): ?>
        <div class="d-flex align-items-start mb-2 pb-2 border-bottom" style="border-color:var(--border)!important">
          <span class="badge <?= $m['direction']==='outbound'?'bg-primary':'bg-success' ?> me-2 mt-1" style="font-size:.65rem"><?= $m['direction']==='outbound'?'OUT':'IN' ?></span>
          <div class="flex-grow-1 overflow-hidden">
            <div class="small text-muted"><?= htmlspecialchars($m['name'] ?? $m['contact_phone']) ?></div>
            <div class="small text-truncate"><?= htmlspecialchars($m['body']) ?></div>
          </div>
          <div class="small text-muted ms-2 text-nowrap"><?= date('H:i',strtotime($m['created_at'])) ?></div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<?php /* ── CONVERSATIONS ────────────────────────────────────────────────── */ ?>
<?php elseif ($view === 'conversations'): ?>

<h4 class="mb-4">Conversations</h4>
<div class="row g-0" style="height:580px">
  <div class="col-md-4 pe-3 h-100 overflow-auto">
    <div class="card h-100 p-2 overflow-auto">
      <?php foreach ($threads as $t): ?>
        <a href="?view=conversations&phone=<?= urlencode($t['contact_phone']) ?>"
           class="thread-item <?= $activePhone===$t['contact_phone']?'active':'' ?>">
          <div class="d-flex justify-content-between">
            <strong class="text-white small"><?= htmlspecialchars($t['name'] ?? $t['contact_phone']) ?></strong>
            <small class="text-muted"><?= date('M j',strtotime($t['last_at'])) ?></small>
          </div>
          <div class="small text-muted text-truncate"><?= ($t['last_dir']==='outbound'?'You: ':'')  .htmlspecialchars($t['last_msg']) ?></div>
        </a>
      <?php endforeach; ?>
    </div>
  </div>
  <div class="col-md-8 h-100">
    <?php if ($activePhone): ?>
      <div class="card h-100 d-flex flex-column p-3">
        <div class="mb-3 pb-2 d-flex justify-content-between align-items-center" style="border-bottom:1px solid var(--border)">
          <strong><?= htmlspecialchars($activePhone) ?></strong>
          <a href="?view=conversations" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left"></i></a>
        </div>
        <div class="chat-wrap flex-grow-1 mb-3" id="chatArea">
          <?php foreach ($conversation as $msg): ?>
            <div class="d-flex flex-column <?= $msg['direction']==='outbound'?'align-items-end':'align-items-start' ?>">
              <div class="bubble <?= $msg['direction']==='outbound'?'out':'in' ?>"><?= nl2br(htmlspecialchars($msg['body'])) ?></div>
              <div class="bubble-meta <?= $msg['direction']==='outbound'?'text-end':'' ?>">
                <?= date('M j, H:i',strtotime($msg['created_at'])) ?>
                <?php if ($msg['direction']==='outbound'): ?>
                  · <span class="badge bg-secondary" style="font-size:.6rem"><?= $msg['status'] ?></span>
                <?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
        <form method="POST" class="d-flex gap-2">
          <input type="hidden" name="action"      value="send">
          <input type="hidden" name="return_view" value="conversations">
          <input type="hidden" name="to"          value="<?= htmlspecialchars($activePhone) ?>">
          <textarea name="text" class="form-control" rows="2" placeholder="Type a reply…" required></textarea>
          <button class="btn btn-primary px-3"><i class="bi bi-send-fill"></i></button>
        </form>
      </div>
    <?php else: ?>
      <div class="card h-100 d-flex align-items-center justify-content-center text-muted">
        <div class="text-center"><i class="bi bi-chat-left-dots fs-1 mb-2 d-block"></i>Select a conversation</div>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php /* ── BROADCAST ────────────────────────────────────────────────────── */ ?>
<?php elseif ($view === 'broadcast'): ?>

<h4 class="mb-4">Broadcast</h4>
<div class="row g-3">
  <div class="col-md-7">
    <div class="card p-4">
      <form method="POST">
        <input type="hidden" name="action" value="broadcast">
        <div class="mb-3">
          <label class="form-label fw-semibold">Recipients <small class="text-muted fw-normal">(one number per line)</small></label>
          <textarea id="bcastNumbers" name="numbers" class="form-control font-monospace" rows="8"
                    placeholder="+12025550001&#10;+12025550002" required></textarea>
          <div class="text-muted small mt-1"><span id="rcptCount">0</span> recipients</div>
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Message</label>
          <textarea name="text" class="form-control" rows="4" placeholder="Your message…" required
                    oninput="document.getElementById('charCount').textContent=this.value.length"></textarea>
          <div class="text-muted small mt-1"><span id="charCount">0</span> characters</div>
        </div>
        <button class="btn btn-primary w-100"><i class="bi bi-megaphone me-1"></i>Send Broadcast</button>
      </form>
    </div>
  </div>
  <div class="col-md-5">
    <div class="card p-3">
      <h6 class="mb-2">Add from Contacts</h6>
      <p class="small text-muted mb-3">Click a contact to add to the recipient list.</p>
      <div style="max-height:380px;overflow-y:auto">
        <?php foreach ($contacts as $c): ?>
          <div class="thread-item d-flex justify-content-between align-items-center mb-1"
               onclick="addToList('<?= htmlspecialchars($c['phone'],ENT_QUOTES) ?>')">
            <div>
              <div class="small fw-semibold text-white"><?= htmlspecialchars($c['name'] ?? '—') ?></div>
              <div class="small text-muted"><?= htmlspecialchars($c['phone']) ?></div>
            </div>
            <i class="bi bi-plus-circle text-muted"></i>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</div>

<?php /* ── CONTACTS ─────────────────────────────────────────────────────── */ ?>
<?php elseif ($view === 'contacts'): ?>

<h4 class="mb-4">Contacts</h4>
<div class="row g-3">
  <div class="col-md-4">
    <div class="card p-4">
      <h6 class="mb-3">Add Contact</h6>
      <form method="POST">
        <input type="hidden" name="action" value="add_contact">
        <div class="mb-2"><input type="text" name="name"  class="form-control" placeholder="Name (optional)"></div>
        <div class="mb-3"><input type="text" name="phone" class="form-control" placeholder="+12025550001" required></div>
        <button class="btn btn-primary w-100"><i class="bi bi-person-plus me-1"></i>Add</button>
      </form>
    </div>
  </div>
  <div class="col-md-8">
    <div class="card p-3">
      <table class="table table-dark table-hover mb-0 small align-middle">
        <thead><tr><th>Name</th><th>Phone</th><th>Added</th><th></th></tr></thead>
        <tbody>
          <?php foreach ($contacts as $c): ?>
            <tr>
              <td><?= htmlspecialchars($c['name'] ?? '—') ?></td>
              <td><a href="?view=conversations&phone=<?= urlencode($c['phone']) ?>" class="text-white"><?= htmlspecialchars($c['phone']) ?></a></td>
              <td class="text-muted"><?= date('M j, Y',strtotime($c['created_at'])) ?></td>
              <td>
                <form method="POST">
                  <input type="hidden" name="action" value="delete_contact">
                  <input type="hidden" name="phone"  value="<?= htmlspecialchars($c['phone']) ?>">
                  <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Remove contact?')"><i class="bi bi-trash"></i></button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php /* ── HISTORY ──────────────────────────────────────────────────────── */ ?>
<?php elseif ($view === 'history'): ?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <h4 class="mb-0">Message History</h4>
  <form method="POST">
    <input type="hidden" name="action" value="sync">
    <button class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-repeat me-1"></i>Sync from Telnyx</button>
  </form>
</div>
<div class="card p-3">
  <table class="table table-dark table-hover mb-0 small align-middle">
    <thead><tr><th>Dir</th><th>Contact</th><th>Message</th><th>Status</th><th>Cost</th><th>Time</th></tr></thead>
    <tbody>
      <?php foreach ($recentMessages as $m): ?>
        <tr>
          <td><span class="badge <?= $m['direction']==='outbound'?'bg-primary':'bg-success' ?>"><?= $m['direction']==='outbound'?'OUT':'IN' ?></span></td>
          <td><a href="?view=conversations&phone=<?= urlencode($m['contact_phone']) ?>" class="text-white text-decoration-none"><?= htmlspecialchars($m['name'] ?? $m['contact_phone']) ?></a></td>
          <td class="text-truncate" style="max-width:280px"><?= htmlspecialchars($m['body']) ?></td>
          <td><span class="badge bg-secondary"><?= htmlspecialchars($m['status']) ?></span></td>
          <td><?= in_array($m['status'],['delivered','received','sent']) ? '$'.number_format($m['cost'],4) : '—' ?></td>
          <td class="text-muted text-nowrap"><?= date('M j H:i',strtotime($m['created_at'])) ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<?php /* ── DEBUG ──────────────────────────────────────────────────────────── */ ?>
<?php elseif ($view === 'debug'): ?>

<h4 class="mb-4">Debug</h4>
<div class="row g-3">

  <div class="col-md-6">
    <div class="card p-4">
      <h6 class="mb-3">Recover Missing Message by Telnyx ID</h6>
      <p class="small text-muted">If a sent message isn't in your history, paste its Telnyx message ID here to fetch and store it.</p>
      <form method="POST">
        <input type="hidden" name="action" value="recover">
        <div class="mb-2">
          <input type="text" name="telnyx_id" class="form-control font-monospace"
                 placeholder="0lQEtj10005309110000000000000000" required>
        </div>
        <button class="btn btn-primary w-100">Recover Message</button>
      </form>
      <?php if (isset($result['detail'])): ?>
        <div class="alert alert-success mt-3 mb-0 small"><?= htmlspecialchars($result['detail']) ?></div>
      <?php endif; ?>
    </div>
  </div>

  <div class="col-md-6">
    <div class="card p-4">
      <h6 class="mb-3">System Status</h6>

      <div class="small text-muted mb-1">Webhook URL (set in Telnyx Inbound):</div>
      <code class="d-block p-2 rounded small mb-3" style="background:#13151f;word-break:break-all">
        <?= htmlspecialchars('https://' . ($_SERVER['HTTP_HOST'] ?? 'yourdomain.com') . $_SERVER['PHP_SELF']) ?>
      </code>

      <?php
      $logFile  = __DIR__ . '/webhook.log';
      $errFile  = __DIR__ . '/php_errors.log';
      $testFile = __DIR__ . '/write_test.tmp';
      $canWrite = @file_put_contents($testFile, 'ok') !== false;
      if ($canWrite) @unlink($testFile);
      ?>

      <table class="table table-dark table-sm small mb-3">
        <tr><td>Folder writable</td><td><?= $canWrite ? '<span class="badge bg-success">YES</span>' : '<span class="badge bg-danger">NO — fix chmod</span>' ?></td></tr>
        <tr><td>dashboard.db</td><td><?= file_exists(DB_FILE) ? '<span class="badge bg-success">exists</span>' : '<span class="badge bg-danger">missing</span>' ?></td></tr>
        <tr><td>webhook.log</td><td><?= file_exists($logFile) ? '<span class="badge bg-success">exists ('.filesize($logFile).' bytes)</span>' : '<span class="badge bg-secondary">not created yet</span>' ?></td></tr>
        <tr><td>php_errors.log</td><td><?= file_exists($errFile) ? '<span class="badge bg-warning text-dark">exists — check it</span>' : '<span class="badge bg-secondary">none</span>' ?></td></tr>
        <tr><td>Messages (total / out / in)</td><td><?= db()->query("SELECT COUNT(*) FROM messages")->fetchColumn() ?> / <?= db()->query("SELECT COUNT(*) FROM messages WHERE direction='outbound'")->fetchColumn() ?> / <?= db()->query("SELECT COUNT(*) FROM messages WHERE direction='inbound'")->fetchColumn() ?></td></tr>
      </table>

      <?php if (file_exists($errFile)): ?>
        <div class="small text-warning mb-2">PHP errors detected — last 10 lines:</div>
        <pre style="background:#13151f;color:#f08080;padding:10px;border-radius:6px;font-size:.7rem;max-height:150px;overflow:auto"><?= htmlspecialchars(implode('', array_slice(file($errFile), -10))) ?></pre>
      <?php endif; ?>

      <a href="https://portal.telnyx.com/#/app/messaging/debugging" target="_blank" class="btn btn-sm btn-outline-secondary w-100 mt-1">
        <i class="bi bi-box-arrow-up-right me-1"></i>Open Telnyx Debugging Portal
      </a>
    </div>
  </div>

  <div class="col-12">
    <div class="card p-4">
      <h6 class="mb-3">Recent Webhook Log <small class="text-muted fw-normal">(last 30 lines of webhook.log)</small></h6>
      <?php
      $logFile = __DIR__ . '/webhook.log';
      if (file_exists($logFile)) {
          $lines = array_slice(file($logFile), -30);
          echo '<pre style="background:#13151f;color:#a0f0a0;padding:12px;border-radius:6px;font-size:.75rem;overflow-x:auto;max-height:400px">';
          foreach ($lines as $line) {
              // Pretty-print the JSON part
              $tab = strpos($line, ' {');
              if ($tab !== false) {
                  $ts   = substr($line, 0, $tab);
                  $json = json_decode(substr($line, $tab), true);
                  $type = $json['data']['event_type'] ?? '?';
                  echo htmlspecialchars($ts) . ' <span style="color:#7c6af7">[' . $type . ']</span> ' .
                       htmlspecialchars(json_encode($json, JSON_PRETTY_PRINT)) . "\n";
              } else {
                  echo htmlspecialchars($line);
              }
          }
          echo '</pre>';
      } else {
          echo '<p class="text-muted small mb-0">No webhook.log yet — Telnyx hasn\'t hit the webhook URL, or the file isn\'t writable.</p>';
      }
      ?>
    </div>
  </div>

</div>

<?php endif; ?>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Auto-scroll chat
const ca = document.getElementById('chatArea');
if (ca) {
  ca.scrollTop = ca.scrollHeight;
  // Poll for new messages every 10 seconds while a conversation is open
  setTimeout(() => location.reload(), 10000);
}

// Broadcast: add contact to textarea
function addToList(phone) {
  const ta = document.getElementById('bcastNumbers');
  if (!ta) return;
  const lines = ta.value.split('\n').map(l=>l.trim()).filter(Boolean);
  if (!lines.includes(phone)) lines.push(phone);
  ta.value = lines.join('\n');
  updateRcptCount();
}

// Count recipients
function updateRcptCount() {
  const ta = document.getElementById('bcastNumbers');
  const el = document.getElementById('rcptCount');
  if (!ta || !el) return;
  el.textContent = ta.value.split('\n').map(l=>l.trim()).filter(Boolean).length;
}
const bta = document.getElementById('bcastNumbers');
if (bta) { bta.addEventListener('input', updateRcptCount); updateRcptCount(); }
</script>
</body>
</html>