<?php
session_start();

// Cek apakah user sudah login
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'marketing') {
    header("Location: login.php");
    exit();
}

require_once 'includes/config.php';

// Ambil data dari database
$numbers = getDistributedNumbers($_SESSION['user_id']);

// Hitung statistik
$total_numbers = count($numbers);
$followed_up = 0;
$pending = 0;

foreach ($numbers as $number) {
    if ($number['whatsapp_clicked'] == 1) {
        $followed_up++;
    } else {
        $pending++;
    }
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<title>Dashboard - Miracle-TECH Phone Call System</title>

<div class="content" id="content">
    <div class="container-fluid">
        <h1 class="h3 mb-4">Dashboard</h1>
        
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-icon">
                            <i class="fas fa-phone-volume"></i>
                        </div>
                        <div class="stat-details">
                            <h3>Target Number</h3>
                            <h2><?php echo $total_numbers; ?></h2>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-icon success">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stat-details">
                            <h3>Followed Up</h3>
                            <h2><?php echo $followed_up; ?></h2>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-icon failed">
                            <i class="fas fa-times-circle"></i>
                        </div>
                        <div class="stat-details">
                            <h3>Pending</h3>
                            <h2><?php echo $pending; ?></h2>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th>No.</th>
                            <th class="text-start">Target Number</th>
                            <th class="sortable" onclick="sortTable('action')">
                                Action 
                                <i class="fas fa-sort ms-1"></i>
                            </th>
                            <th>Note</th>
                            <th>ND</th>
                            <th>Edit</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <?php 
                        $no = 1;
                        foreach ($numbers as $number): 
                            $whatsapp_number = substr($number['phone_number'], 1); // Hapus + di depan nomor
                        ?>
                        <tr>
                            <td><?php echo $no++; ?></td>
                            <td class="text-start">
                                <canvas class="number-canvas" width="150" height="20" data-number="<?php echo $number['phone_number']; ?>"></canvas>
                            </td>
                            <td data-action="fu-<?php echo $number['whatsapp_clicked'] ? 'success' : 'danger'; ?>">
                                <a href="https://wa.me/<?php echo $whatsapp_number; ?>" 
                                   target="_blank" 
                                   class="text-success whatsapp-link" 
                                   data-id="<?php echo $number['id']; ?>">
                                    <i class="fab fa-whatsapp fa-lg"></i>
                                </a>
                                <span class="badge bg-<?php echo $number['whatsapp_clicked'] ? 'success' : 'danger'; ?>">FU</span>
                            </td>
                            <td><?php echo htmlspecialchars($number['note'] ?? ''); ?></td>
                            <td><i class="fas fa-check-circle text-<?php echo $number['nd_status'] === 'active' ? 'success' : 'secondary'; ?>"></i></td>
                            <td>
                                <a href="#" class="text-primary" data-bs-toggle="modal" data-bs-target="#editNoteModal<?php echo $number['id']; ?>">
                                    <i class="fas fa-edit"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <!-- Pagination -->
            <div class="card-footer bg-transparent">
                <?php if ($total_numbers > 10): ?>
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center mb-0">
                        <li class="page-item disabled">
                            <a class="page-link" href="#" tabindex="-1">Previous</a>
                        </li>
                        <?php 
                        $total_pages = ceil($total_numbers / 10);
                        for ($i = 1; $i <= $total_pages; $i++): 
                        ?>
                        <li class="page-item <?php echo $i === 1 ? 'active' : ''; ?>">
                            <a class="page-link" href="#"><?php echo $i; ?></a>
                        </li>
                        <?php endfor; ?>
                        <li class="page-item <?php echo $total_pages === 1 ? 'disabled' : ''; ?>">
                            <a class="page-link" href="#">Next</a>
                        </li>
                    </ul>
                </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Modal Edit Note -->
<?php foreach ($numbers as $number): ?>
<div class="modal fade" id="editNoteModal<?php echo $number['id']; ?>" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Note</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="noteText<?php echo $number['id']; ?>" class="form-label">Note</label>
                    <textarea class="form-control" id="noteText<?php echo $number['id']; ?>" rows="3"><?php echo htmlspecialchars($number['note'] ?? ''); ?></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary btn-sm save-note" data-id="<?php echo $number['id']; ?>">Save Changes</button>
            </div>
        </div>
    </div>
</div>
<?php endforeach; ?>

<script>
let sortDirection = 1; // 1 for ascending, -1 for descending

function sortTable(column) {
    const tbody = document.getElementById('tableBody');
    const rows = Array.from(tbody.getElementsByTagName('tr'));
    
    // Toggle sort direction
    sortDirection *= -1;
    
    // Update sort icon
    const th = document.querySelector(`th[onclick="sortTable('${column}')"]`);
    const icon = th.querySelector('i');
    icon.className = sortDirection === 1 ? 'fas fa-sort-up ms-1' : 'fas fa-sort-down ms-1';
    
    // Sort rows
    rows.sort((a, b) => {
        const aValue = a.querySelector(`td[data-action]`).getAttribute('data-action');
        const bValue = b.querySelector(`td[data-action]`).getAttribute('data-action');
        return aValue.localeCompare(bValue) * sortDirection;
    });
    
    // Reorder tbody
    rows.forEach(row => tbody.appendChild(row));
    
    // Update row numbers
    rows.forEach((row, index) => {
        row.querySelector('td:first-child').textContent = index + 1;
    });
}

// Function to draw numbers on canvas
function drawNumbers() {
    const canvases = document.querySelectorAll('.number-canvas');
    canvases.forEach(canvas => {
        const ctx = canvas.getContext('2d');
        const number = canvas.getAttribute('data-number');
        
        // Clear canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // Set font style
        ctx.font = '14px Arial';
        ctx.fillStyle = '#000000';
        
        // Draw number
        ctx.fillText(number, 10, 15);
    });
}

// Draw numbers when page loads
document.addEventListener('DOMContentLoaded', function() {
    drawNumbers();
    
    // Add cursor pointer to sortable columns
    const sortableColumns = document.querySelectorAll('.sortable');
    sortableColumns.forEach(column => {
        column.style.cursor = 'pointer';
    });
});

// Pagination functionality
document.addEventListener('DOMContentLoaded', function() {
    const itemsPerPage = 10;
    const rows = document.querySelectorAll('#tableBody tr');
    const pageCount = Math.ceil(rows.length / itemsPerPage);
    let currentPage = 1;

    function showPage(page) {
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;

        rows.forEach((row, index) => {
            row.style.display = (index >= start && index < end) ? '' : 'none';
        });

        // Update pagination UI
        document.querySelectorAll('.page-item').forEach(item => item.classList.remove('active'));
        document.querySelector(`.page-item:nth-child(${page + 1})`).classList.add('active');
        
        // Update Previous/Next buttons
        document.querySelector('.page-item:first-child').classList.toggle('disabled', page === 1);
        document.querySelector('.page-item:last-child').classList.toggle('disabled', page === pageCount);
    }

    // Add click handlers for pagination
    document.querySelectorAll('.page-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const text = this.textContent;
            if (text === 'Previous' && currentPage > 1) {
                currentPage--;
            } else if (text === 'Next' && currentPage < pageCount) {
                currentPage++;
            } else if (!isNaN(text)) {
                currentPage = parseInt(text);
            }
            showPage(currentPage);
        });
    });

    // Show first page initially
    showPage(1);
});

// Update WhatsApp clicked status
document.querySelectorAll('.whatsapp-link').forEach(link => {
    link.addEventListener('click', function(e) {
        const id = this.getAttribute('data-id');
        fetch('update_whatsapp.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `id=${id}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const badge = this.nextElementSibling;
                badge.classList.remove('bg-danger');
                badge.classList.add('bg-success');
                const td = this.parentElement;
                td.setAttribute('data-action', 'fu-success');
            }
        });
    });
});

// Save note
document.querySelectorAll('.save-note').forEach(button => {
    button.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        const note = document.getElementById(`noteText${id}`).value;
        
        fetch('update_note.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `id=${id}&note=${encodeURIComponent(note)}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const modal = bootstrap.Modal.getInstance(document.getElementById(`editNoteModal${id}`));
                modal.hide();
                // Update note in table
                const row = document.querySelector(`[data-bs-target="#editNoteModal${id}"]`).closest('tr');
                row.querySelector('td:nth-child(4)').textContent = note;
            }
        });
    });
});
</script>

<style>
.number-canvas {
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
}

.table td {
    padding-top: 0.3rem;
    padding-bottom: 0.3rem;
    vertical-align: middle;
}

.pagination {
    margin-bottom: 0;
}

.page-link {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
}
</style>

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