<?php
// =============================================
// SHARK CRM - Campaigns Page
// =============================================

// Get filters
$filter_type = isset($_GET['type_id']) ? (int)$_GET['type_id'] : 0;
$filter_status = isset($_GET['status']) ? (int)$_GET['status'] : -1;

$where = "c.account_id = $account_id";
if ($filter_type) $where .= " AND c.message_type_id = $filter_type";
if ($filter_status >= 0) $where .= " AND c.status = $filter_status";

$campaigns = $conn->query("
    SELECT c.*, ct.name as type_name, u.name as creator_name,
           (SELECT COUNT(*) FROM campaign_audience WHERE campaign_id = c.id) as audience_count
    FROM campaign c
    LEFT JOIN message_type ct ON c.message_type_id = ct.id
    LEFT JOIN users u ON c.added_by = u.id
    WHERE $where
    ORDER BY c.date_created DESC
");

$message_types = $conn->query("SELECT id, name FROM message_type WHERE account_id = $account_id OR account_id IS NULL ORDER BY name");
$audience_list = $conn->query("SELECT id, name FROM audience WHERE account_id = $account_id OR account_id IS NULL ORDER BY name");
?>

<div class="fade-in">
<!-- Toolbar -->
<div class="toolbar">
    <div class="search-wrap">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
        <input type="text" id="campaignSearch" placeholder="Search campaigns...">
    </div>
    <select id="typeFilter" class="form-control" style="width:auto" onchange="applyFilters()">
        <option value="0">All Types</option>
        <?php $message_types->data_seek(0); while($type = $message_types->fetch_assoc()): ?>
        <option value="<?= $type['id'] ?>" <?= $filter_type == $type['id'] ? 'selected' : '' ?>><?= htmlspecialchars($type['name']) ?></option>
        <?php endwhile; ?>
    </select>
    <select id="statusFilter" class="form-control" style="width:auto" onchange="applyFilters()">
        <option value="-1">All Status</option>
        <option value="1" <?= $filter_status == 1 ? 'selected' : '' ?>>Active</option>
        <option value="0" <?= $filter_status == 0 ? 'selected' : '' ?>>Inactive</option>
    </select>
    <button class="btn btn-primary" onclick="openCampaignModal()">+ New Campaign</button>
</div>

<!-- Campaigns Table -->
<div class="card">
    <div class="table-wrapper">
        <table class="crm-table" id="campaignsTable">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Audiences</th>
                    <th>Status</th>
                    <th>Created By</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($campaigns->num_rows === 0): ?>
                <tr><td colspan="7" class="text-center text-muted" style="padding:40px">No campaigns found</td></tr>
                <?php else: ?>
                <?php while($camp = $campaigns->fetch_assoc()): ?>
                <tr id="camp_<?= $camp['id'] ?>">
                    <td class="font-bold"><?= htmlspecialchars($camp['name']) ?></td>
                    <td><span class="badge badge-blue"><?= htmlspecialchars($camp['type_name']) ?></span></td>
                    <td><span class="badge badge-purple"><?= $camp['audience_count'] ?> Audiences</span></td>
                    <td>
                        <span class="badge badge-<?= $camp['status'] ? 'green' : 'gray' ?>" 
                              onclick="toggleStatus(<?= $camp['id'] ?>, <?= $camp['status'] ?>)" 
                              style="cursor:pointer">
                            <?= $camp['status'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td><?= htmlspecialchars($camp['creator_name'] ?? 'System') ?></td>
                    <td class="text-muted text-xs"><?= formatDate($camp['date_created']) ?></td>
                    <td>
                        <div class="d-flex gap-8">
                            <button class="btn btn-secondary btn-sm" onclick="editCampaign(<?= $camp['id'] ?>)">Edit</button>
                            <button class="btn btn-primary btn-sm" onclick="viewCampaign(<?= $camp['id'] ?>)">View</button>
                            <button class="btn btn-danger btn-sm" onclick="deleteCampaign(<?= $camp['id'] ?>)">Del</button>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
</div>

<!-- Campaign Modal -->
<div class="modal-overlay" id="campaignModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <span class="modal-title" id="campaignModalTitle">New Campaign</span>
            <button class="modal-close">✕</button>
        </div>
        <div class="modal-body">
            <form id="campaignForm">
                <input type="hidden" name="campaign_id" id="campaignId">
                <div class="form-grid">
                    <div class="form-group span-2">
                        <label class="form-label">Campaign Name *</label>
                        <input type="text" name="name" class="form-control" required placeholder="e.g., Summer Sale 2024">
                    </div>
                    <div class="form-group span-2">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3" placeholder="Campaign description..."></textarea>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Campaign Type *</label>
                        <select name="message_type_id" class="form-control" required>
                            <option value="">Select type...</option>
                            <?php $message_types->data_seek(0); while($type = $message_types->fetch_assoc()): ?>
                            <option value="<?= $type['id'] ?>"><?= htmlspecialchars($type['name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                    <div class="form-group span-2">
                        <label class="form-label">Target Audiences</label>
                        <div id="audienceCheckboxes" style="max-height: 200px; overflow-y: auto; border: 1px solid var(--border); border-radius: 8px; padding: 12px;">
                            <?php $audience_list->data_seek(0); while($aud = $audience_list->fetch_assoc()): ?>
                            <label style="display: block; margin-bottom: 8px;">
                                <input type="checkbox" name="audience_ids[]" value="<?= $aud['id'] ?>">
                                <?= htmlspecialchars($aud['name']) ?>
                            </label>
                            <?php endwhile; ?>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal('campaignModal')">Cancel</button>
            <button class="btn btn-primary" onclick="saveCampaign()">Save Campaign</button>
        </div>
    </div>
</div>

<!-- View Campaign Modal -->
<div class="modal-overlay" id="viewCampaignModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <span class="modal-title" id="viewCampaignTitle">Campaign Details</span>
            <button class="modal-close">✕</button>
        </div>
        <div class="modal-body" id="viewCampaignBody">
            <div class="text-center"><div class="spinner"></div></div>
        </div>
    </div>
</div>

<script>
function applyFilters() {
    const type = document.getElementById('typeFilter').value;
    const status = document.getElementById('statusFilter').value;
    window.location.href = `?page=campaigns&type_id=${type}&status=${status}`;
}

function openCampaignModal() {
    document.getElementById('campaignForm').reset();
    document.getElementById('campaignId').value = '';
    document.querySelectorAll('#audienceCheckboxes input').forEach(cb => cb.checked = false);
    document.getElementById('campaignModalTitle').textContent = 'New Campaign';
    openModal('campaignModal');
}

async function saveCampaign() {
    const form = document.getElementById('campaignForm');
    const fd = new FormData(form);
    const campaignId = document.getElementById('campaignId').value;
    fd.append('action', campaignId ? 'edit' : 'add');
    if (campaignId) fd.append('campaign_id', campaignId);
    
    const res = await apiCall('handlers/campaigns.php', fd);
    if (res.success) {
        showToast(campaignId ? 'Campaign updated!' : 'Campaign created!', 'success');
        closeModal('campaignModal');
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function editCampaign(id) {
    const res = await apiCall('handlers/campaigns.php', { action: 'get', id });
    if (!res.success) { showToast('Error loading campaign', 'error'); return; }
    
    const data = res.data;
    document.getElementById('campaignId').value = data.id;
    document.querySelector('[name="name"]').value = data.name;
    document.querySelector('[name="description"]').value = data.description || '';
    document.querySelector('[name="message_type_id"]').value = data.message_type_id;
    document.querySelector('[name="status"]').value = data.status;
    
    // Check audiences
    document.querySelectorAll('#audienceCheckboxes input').forEach(cb => {
        cb.checked = data.audience_ids && data.audience_ids.includes(parseInt(cb.value));
    });
    
    document.getElementById('campaignModalTitle').textContent = 'Edit Campaign';
    openModal('campaignModal');
}

async function viewCampaign(id) {
    openModal('viewCampaignModal');
    document.getElementById('viewCampaignBody').innerHTML = '<div class="text-center"><div class="spinner"></div></div>';
    
    const res = await apiCall('handlers/campaigns.php', { action: 'get_full', id });
    if (!res.success) { document.getElementById('viewCampaignBody').innerHTML = '<p class="text-red">Error loading campaign</p>'; return; }
    
    const data = res.data;
    document.getElementById('viewCampaignTitle').textContent = data.name;
    
    let audiencesHtml = '<ul style="margin: 0; padding-left: 20px;">';
    data.audiences.forEach(aud => {
        audiencesHtml += `<li>${escapeHtml(aud.name)} - ${escapeHtml(aud.description || 'No description')}</li>`;
    });
    audiencesHtml += '</ul>';
    
    document.getElementById('viewCampaignBody').innerHTML = `
        <div class="form-grid mb-16">
            <div><label class="form-label">Campaign Name</label><p><strong>${escapeHtml(data.name)}</strong></p></div>
            <div><label class="form-label">Type</label><p><span class="badge badge-blue">${escapeHtml(data.type_name)}</span></p></div>
            <div class="span-2"><label class="form-label">Description</label><p>${escapeHtml(data.description || 'No description')}</p></div>
            <div><label class="form-label">Status</label><p><span class="badge badge-${data.status ? 'green' : 'gray'}">${data.status ? 'Active' : 'Inactive'}</span></p></div>
            <div><label class="form-label">Created By</label><p>${escapeHtml(data.creator_name || 'System')}</p></div>
            <div><label class="form-label">Created Date</label><p>${formatDate(data.date_created)}</p></div>
            <div class="span-2"><label class="form-label">Target Audiences (${data.audiences.length})</label>${audiencesHtml}</div>
        </div>
        <div class="hr"></div>
        <div class="d-flex gap-8">
            <button class="btn btn-primary btn-sm" onclick="closeModal('viewCampaignModal');editCampaign(${id})">Edit Campaign</button>
            <button class="btn btn-secondary btn-sm" onclick="closeModal('viewCampaignModal')">Close</button>
        </div>
    `;
}

async function deleteCampaign(id) {
    confirmAction('Delete this campaign? This cannot be undone.', async () => {
        const res = await apiCall('handlers/campaigns.php', { action: 'delete', id });
        if (res.success) {
            showToast('Campaign deleted', 'success');
            document.getElementById(`camp_${id}`)?.remove();
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}

async function toggleStatus(id, currentStatus) {
    const newStatus = currentStatus ? 0 : 1;
    const res = await apiCall('handlers/campaigns.php', { action: 'toggle_status', id, status: newStatus });
    if (res.success) {
        showToast(`Campaign ${newStatus ? 'activated' : 'deactivated'}`, 'success');
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// Search
document.getElementById('campaignSearch').addEventListener('input', function() {
    const q = this.value.toLowerCase();
    document.querySelectorAll('#campaignsTable tbody tr').forEach(row => {
        if (row.cells) {
            row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
        }
    });
});
</script>