<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS Sent History</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.0.0-beta3/css/all.min.css">
    <style>
        .icon-small { font-size: 0.8em; }
        .text-pending { color: #ffc107; }
        .text-sent { color: #0dcaf0; }
        .text-delivered { color: #198754; }
        .text-failed { color: #dc3545; }
    </style>
</head>
<body>
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <h2 class="mb-4">SMS Management System</h2>
        </div>
    </div>
    
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card bg-light">
                <div class="card-body">
                    <h5 class="card-title">Available SMS Balance 📥</h5>
                    <p class="card-text fs-4 fw-bold" id="smsBalanceDisplay">Fetching...</p>
                    <div id="balanceMessage" class="mt-2 small text-muted"></div>
                    <button class="btn btn-sm btn-outline-primary mt-2" id="refreshBalance"><i class="fas fa-sync-alt"></i> Refresh Balance</button>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card bg-light">
                <div class="card-body">
                    <h5 class="card-title">Send a Test SMS 🧪</h5>
                    <p class="card-text">Quickly test the system with a pre-defined message.</p>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#testSmsModal">
                        <i class="fas fa-paper-plane"></i> Test SMS
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <hr>
    
    <div class="row">
        <div class="col-12">
            <h3 class="mb-3">SMS Sent History 📜</h3>
            <div class="card p-3 mb-3 shadow-sm">
                <form id="filterForm" class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label for="search" class="form-label">Search</label>
                        <input type="text" class="form-control" id="search" name="search" placeholder="Recipient, message content...">
                    </div>
                    <div class="col-md-2">
                        <label for="group" class="form-label">Group/Purpose</label>
                        <select class="form-select" id="group" name="group_id">
                            <option value="">All</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['sms_category_id']; ?>"><?php echo htmlspecialchars($cat['category_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="start_date" class="form-label">From Date</label>
                        <input type="date" class="form-control" id="start_date" name="start_date">
                    </div>
                    <div class="col-md-2">
                        <label for="end_date" class="form-label">To Date</label>
                        <input type="date" class="form-control" id="end_date" name="end_date">
                    </div>
                    <div class="col-md-2 d-flex justify-content-end">
                        <button type="submit" class="btn btn-success me-2"><i class="fas fa-filter"></i> Filter</button>
                        <button type="button" id="downloadPdfBtn" class="btn btn-danger"><i class="fas fa-file-pdf"></i> PDF</button>
                    </div>
                </form>
            </div>
            
            <div id="loadingIndicator" class="text-center my-3 d-none">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading SMS records...</p>
            </div>

            <div class="table-responsive">
                <table class="table table-hover table-striped table-bordered">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>Recipient</th>
                            <th>Message</th>
                            <th>Status</th>
                            <th>Date/Time</th>
                            <th>Group</th>
                            <th>Sent By</th>
                        </tr>
                    </thead>
                    <tbody id="smsTableBody">
                        <?php if (count($sms_records) > 0): ?>
                            <?php $index = ($current_page - 1) * $items_per_page + 1; ?>
                            <?php foreach ($sms_records as $record): ?>
                                <tr>
                                    <td><?php echo $index++; ?></td>
                                    <td><?php echo htmlspecialchars($record['recipient_phone']); ?></td>
                                    <td><?php echo htmlspecialchars(substr($record['message_content'], 0, 50)) . '...'; ?></td>
                                    <td>
                                        <span class="badge <?php 
                                            switch($record['sent_status']) {
                                                case 'Delivered': echo 'bg-success'; break;
                                                case 'Sent': echo 'bg-info'; break;
                                                case 'Pending': echo 'bg-warning'; break;
                                                case 'Failed': echo 'bg-danger'; break;
                                                default: echo 'bg-secondary';
                                            }
                                        ?>"><?php echo htmlspecialchars($record['sent_status']); ?></span>
                                    </td>
                                    <td><?php echo htmlspecialchars($record['sent_timestamp']); ?></td>
                                    <td><?php echo htmlspecialchars($record['category_name']); ?></td>
                                    <td><?php echo htmlspecialchars($record['sent_by']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="7" class="text-center text-muted">No SMS records found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <nav>
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo ($i === $current_page) ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        </div>
    </div>
</div>

<div class="modal fade" id="testSmsModal" tabindex="-1" aria-labelledby="testSmsModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="testSmsModalLabel">Send Test SMS</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="testSmsForm">
                    <div class="mb-3">
                        <label for="testPhoneNumber" class="form-label">Phone Number</label>
                        <input type="text" class="form-control" id="testPhoneNumber" name="recipient_phone" required>
                    </div>
                    <div class="mb-3">
                        <label for="testMessage" class="form-label">Message</label>
                        <textarea class="form-control" id="testMessage" rows="3" name="message" readonly>Test SMS</textarea>
                    </div>
                    <input type="hidden" name="action" value="send_sms">
                    <input type="hidden" name="sms_category_id" value="23">
                    <div id="testSmsMessage" class="mt-3"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="sendTestSmsBtn">Send SMS</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        // Function to fetch and display the balance
        function fetchBalance() {
            $.ajax({
                url: 'send_sms_with_all_report_responses.php',
                type: 'GET',
                data: { action: 'get_balance' },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#smsBalanceDisplay').text(response.balance);
                        $('#balanceMessage').html(response.message).removeClass('text-danger').addClass('text-muted');
                    } else {
                        $('#smsBalanceDisplay').text('N/A');
                        $('#balanceMessage').html(response.message).removeClass('text-muted').addClass('text-danger');
                    }
                },
                error: function() {
                    $('#smsBalanceDisplay').text('N/A');
                    $('#balanceMessage').text('Error connecting to the server.').removeClass('text-muted').addClass('text-danger');
                }
            });
        }

        // Initial balance fetch
        fetchBalance();

        // Refresh balance button click
        $('#refreshBalance').on('click', fetchBalance);

        // Handle Test SMS form submission via AJAX
        $('#sendTestSmsBtn').on('click', function() {
            const formData = $('#testSmsForm').serialize();
            const $btn = $(this);
            const originalText = $btn.html();
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Sending...');

            $.ajax({
                url: 'send_sms_with_all_report_responses.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    $('#testSmsMessage').html('<div class="alert ' + (response.success ? 'alert-success' : 'alert-danger') + '">' + response.message + '</div>');
                    if (response.success) {
                        setTimeout(function() {
                            $('#testSmsModal').modal('hide');
                            location.reload(); // Reload the page to show the new record
                        }, 2000);
                    }
                },
                error: function() {
                    $('#testSmsMessage').html('<div class="alert alert-danger">An unexpected error occurred. Please try again.</div>');
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalText);
                }
            });
        });
        
        // Handle PDF download button click
        $('#downloadPdfBtn').on('click', function() {
            const formUrl = new URLSearchParams($('#filterForm').serialize()).toString();
            window.location.href = 'send_sms_with_all_report_responses.php?action=generate_pdf&' + formUrl;
        });
        
        // Re-submit the form on filter button click
        $('#filterForm').on('submit', function(e) {
            e.preventDefault();
            const url = '?' + $(this).serialize();
            window.location.href = url;
        });

        // Set the current filter values back into the form fields
        const params = new URLSearchParams(window.location.search);
        params.forEach((value, key) => {
            if ($(`[name="${key}"]`).is(':checkbox')) {
                if (value === 'on') {
                    $(`[name="${key}"]`).prop('checked', true);
                }
            } else {
                $(`[name="${key}"]`).val(value);
            }
        });
    });
</script>
</body>
</html>