<?php
// Include session check for admin protection
include('session_check.php');

// Include database configuration
include('../../config/database.php');

// Fetch accepted proposals
$sql = "SELECT * FROM accepted_proposals";
$result = $conn->query($sql);

$conn->close();
?>

<?php include('../../includes/header.php'); ?>
<div class="container mt-5">
    <h2 class="mb-4">Accepted Proposals</h2>

    <!-- Buttons for exporting emails and sending SMS -->
    <div class="mb-3">
        <button class="btn btn-outline-primary me-2" onclick="exportEmails()">
            <i class="fas fa-file-export"></i> Export Emails
        </button>
        <button class="btn btn-outline-success" onclick="sendSMS('accept')">
            <i class="fas fa-sms"></i> Send SMS
        </button>
    </div>

    <table class="table table-striped">
        <thead class="table-dark">
            <tr>
                <th>Name</th>
                <th>Business Idea Title</th>
                <th>Phone</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td class="name"><?php echo htmlspecialchars($row['full_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['business_idea_title']); ?></td>
                        <td class="phone"><?php echo htmlspecialchars($row['phone']); ?></td>
                        <td class="email"><?php echo htmlspecialchars($row['email']); ?></td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="4">No accepted proposals found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php include('../../includes/footer.php'); ?>

<script>
function sendSMS(action) {
    const phones = Array.from(document.querySelectorAll('.phone')).map(td => td.innerText);
    const names = Array.from(document.querySelectorAll('.name')).map(td => td.innerText);

    fetch('../../config/send_sms.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phones, names, action }),
    })
    .then(response => response.json())
    .then(result => {
        console.log('SMS API Response:', result);
        if (result.some(res => res.status == 'success')) {
            alert('Messages sent successfully.');
        } else {
            alert('Failed to send messages. Error: ' + (result.message || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Error sending messages.');
        console.log('Fetch error:', error);
    });
}

function exportEmails() {
    const emails = Array.from(document.querySelectorAll('.email')).map(td => td.innerText);
    const emailList = emails.join(',');

    const blob = new Blob([emailList], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'accepted_emails.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
</script>
