<?php
$page_title = 'SMS Management | Admin Dashboard';
$page_description = 'Manage SMS communications and broadcast campaigns';
$page_content = function () { ?>

<div class="min-h-screen bg-[#F9FBF7]">
  <div class="max-w-7xl mx-auto grid md:grid-cols-[240px,1fr] gap-6 py-8">
    <!-- Sidebar -->
    <aside class="hidden md:block bg-white p-6 rounded-2xl shadow-sm border">
      <div class="flex items-center gap-3 mb-6">
        <div class="w-10 h-10 rounded-lg grid place-items-center text-white font-bold bg-gradient-to-br from-[#2f7a4f] to-[#51bfa8]">HW</div>
        <div><strong>Admin Portal</strong></div>
      </div>
      <nav class="space-y-2">
        <a href="/files/atasteofafricanmarketplace/dashboard/admin/index.php" class="block px-3 py-2 rounded-lg font-semibold hover:bg-amber-50">Overview</a>
        <a href="#" class="block px-3 py-2 rounded-lg font-semibold hover:bg-amber-50">Users</a>
        <a href="#" class="block px-3 py-2 rounded-lg font-semibold hover:bg-amber-50">Coaches</a>
        <a href="/files/atasteofafricanmarketplace/dashboard/admin/sms.php" class="block px-3 py-2 rounded-lg font-semibold bg-amber-50">SMS</a>
        <a href="#" class="block px-3 py-2 rounded-lg font-semibold hover:bg-amber-50">Analytics</a>
      </nav>
    </aside>

    <!-- Main -->
    <main>
      <header class="flex items-center justify-between bg-white p-4 rounded-2xl shadow-sm mb-6 border">
        <div><strong>SMS Management</strong></div>
        <button onclick="createCampaign()" class="bg-shining-green text-white px-4 py-2 rounded-lg font-semibold">New Campaign</button>
      </header>

      <div class="space-y-6">
        <!-- SMS Analytics -->
        <div class="grid md:grid-cols-4 gap-4">
          <div class="bg-white p-6 rounded-2xl shadow-sm border">
            <h3 class="font-bold text-gray-600">Total Sent</h3>
            <p class="text-2xl font-bold text-shining-green" id="total-sent">0</p>
          </div>
          <div class="bg-white p-6 rounded-2xl shadow-sm border">
            <h3 class="font-bold text-gray-600">Delivered</h3>
            <p class="text-2xl font-bold text-green-600" id="total-delivered">0</p>
          </div>
          <div class="bg-white p-6 rounded-2xl shadow-sm border">
            <h3 class="font-bold text-gray-600">Failed</h3>
            <p class="text-2xl font-bold text-red-600" id="total-failed">0</p>
          </div>
          <div class="bg-white p-6 rounded-2xl shadow-sm border">
            <h3 class="font-bold text-gray-600">Total Cost</h3>
            <p class="text-2xl font-bold text-amber-600" id="total-cost">$0.00</p>
          </div>
        </div>

        <!-- Recent Campaigns -->
        <div class="bg-white p-6 rounded-2xl shadow-sm border">
          <h2 class="font-bold mb-4">Recent Campaigns</h2>
          <div id="campaigns-list">
            <p class="text-gray-500">Loading campaigns...</p>
          </div>
        </div>

        <!-- Recent Messages -->
        <div class="bg-white p-6 rounded-2xl shadow-sm border">
          <h2 class="font-bold mb-4">Recent Messages</h2>
          <div id="messages-list">
            <p class="text-gray-500">Loading messages...</p>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<!-- Campaign Modal -->
<div id="campaign-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
  <div class="bg-white rounded-2xl p-6 max-w-lg w-full mx-4 max-h-[80vh] overflow-y-auto">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-bold">Create SMS Campaign</h3>
      <button onclick="closeCampaignModal()" class="text-gray-500 hover:text-gray-700">✕</button>
    </div>
    
    <form id="campaign-form" class="space-y-4">
      <div>
        <label class="block text-sm font-semibold text-gray-700 mb-2">Campaign Name</label>
        <input type="text" name="name" required class="w-full px-4 py-3 border border-gray-200 rounded-lg">
      </div>
      
      <div>
        <label class="block text-sm font-semibold text-gray-700 mb-2">Target Audience</label>
        <select name="target_audience" class="w-full px-4 py-3 border border-gray-200 rounded-lg">
          <option value="all_users">All Users</option>
          <option value="members_only">Members Only</option>
          <option value="coaches">Coaches</option>
          <option value="location_based">Location Based</option>
        </select>
      </div>
      
      <div>
        <label class="block text-sm font-semibold text-gray-700 mb-2">Message</label>
        <textarea name="message" rows="4" required class="w-full px-4 py-3 border border-gray-200 rounded-lg" placeholder="Use {{first_name}} for personalization"></textarea>
        <p class="text-xs text-gray-500 mt-1">Available variables: {{first_name}}</p>
      </div>
      
      <div>
        <label class="block text-sm font-semibold text-gray-700 mb-2">Schedule (Optional)</label>
        <input type="datetime-local" name="schedule_at" class="w-full px-4 py-3 border border-gray-200 rounded-lg">
      </div>
      
      <div class="flex gap-3">
        <button type="submit" class="flex-1 bg-shining-green text-white py-3 rounded-lg font-semibold">
          Create Campaign
        </button>
        <button type="button" onclick="closeCampaignModal()" class="px-6 py-3 border border-gray-200 rounded-lg font-semibold">
          Cancel
        </button>
      </div>
    </form>
  </div>
</div>

<script>
async function loadSMSData() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/sms/history.php?type=admin', {
      credentials: 'include'
    });
    
    const data = await response.json();
    
    if (data.success) {
      // Calculate totals from analytics
      let totalSent = 0, totalDelivered = 0, totalFailed = 0, totalCost = 0;
      
      data.analytics.forEach(stat => {
        totalSent += parseInt(stat.sent_count);
        totalDelivered += parseInt(stat.delivered_count);
        totalFailed += parseInt(stat.failed_count);
        totalCost += parseFloat(stat.total_cost);
      });
      
      // Update summary cards
      document.getElementById('total-sent').textContent = totalSent;
      document.getElementById('total-delivered').textContent = totalDelivered;
      document.getElementById('total-failed').textContent = totalFailed;
      document.getElementById('total-cost').textContent = `$${totalCost.toFixed(2)}`;
      
      // Update campaigns list
      const campaignsEl = document.getElementById('campaigns-list');
      if (data.campaigns && data.campaigns.length > 0) {
        campaignsEl.innerHTML = data.campaigns.map(campaign => `
          <div class="border rounded-lg p-4 mb-4">
            <div class="flex justify-between items-start">
              <div>
                <h3 class="font-semibold">${campaign.name}</h3>
                <p class="text-sm text-gray-600">${campaign.target_audience.replace('_', ' ')}</p>
                <p class="text-sm text-gray-500">${new Date(campaign.created_at).toLocaleDateString()}</p>
              </div>
              <div class="text-right">
                <span class="px-2 py-1 rounded text-xs ${getStatusColor(campaign.status)}">${campaign.status}</span>
                <div class="text-sm text-gray-600 mt-1">
                  Sent: ${campaign.sent_count} | Delivered: ${campaign.delivered_count}
                </div>
              </div>
            </div>
            <div class="mt-2 text-sm text-gray-700 bg-gray-50 p-2 rounded">
              "${campaign.message.substring(0, 100)}${campaign.message.length > 100 ? '...' : ''}"
            </div>
          </div>
        `).join('');
      } else {
        campaignsEl.innerHTML = '<p class="text-gray-500">No campaigns found</p>';
      }
      
      // Update messages list
      const messagesEl = document.getElementById('messages-list');
      if (data.recent_messages && data.recent_messages.length > 0) {
        messagesEl.innerHTML = data.recent_messages.slice(0, 10).map(msg => `
          <div class="flex justify-between items-start py-3 border-b">
            <div>
              <div class="font-semibold">${msg.phone_number}</div>
              <div class="text-sm text-gray-600">${msg.first_name || 'Unknown'} ${msg.last_name || ''}</div>
              <div class="text-sm text-gray-500">${new Date(msg.created_at).toLocaleString()}</div>
            </div>
            <div class="text-right">
              <span class="px-2 py-1 rounded text-xs ${getStatusColor(msg.status)}">${msg.status}</span>
              <div class="text-xs text-gray-500 mt-1">${msg.message_type}</div>
            </div>
          </div>
        `).join('');
      } else {
        messagesEl.innerHTML = '<p class="text-gray-500">No messages found</p>';
      }
    }
  } catch (error) {
    console.error('Error loading SMS data:', error);
  }
}

function getStatusColor(status) {
  const colors = {
    'sent': 'bg-green-100 text-green-800',
    'delivered': 'bg-green-100 text-green-800',
    'failed': 'bg-red-100 text-red-800',
    'pending': 'bg-yellow-100 text-yellow-800',
    'completed': 'bg-blue-100 text-blue-800',
    'scheduled': 'bg-purple-100 text-purple-800',
    'draft': 'bg-gray-100 text-gray-800'
  };
  return colors[status] || 'bg-gray-100 text-gray-800';
}

function createCampaign() {
  document.getElementById('campaign-modal').classList.remove('hidden');
  document.getElementById('campaign-modal').classList.add('flex');
}

function closeCampaignModal() {
  document.getElementById('campaign-modal').classList.add('hidden');
  document.getElementById('campaign-modal').classList.remove('flex');
  document.getElementById('campaign-form').reset();
}

document.getElementById('campaign-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const formData = new FormData(e.target);
  const data = Object.fromEntries(formData);
  
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/sms/broadcast.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    });
    
    const result = await response.json();
    
    if (result.success) {
      alert(`Campaign created successfully! Sent to ${result.target_count} recipients.`);
      closeCampaignModal();
      loadSMSData(); // Refresh data
    } else {
      alert(result.message || 'Campaign creation failed');
    }
  } catch (error) {
    alert('Network error. Please try again.');
  }
});

// Initialize
loadSMSData();
</script>

<?php };
include __DIR__ . '/../../partials/layout.php';
?>