<?php 
require_once 'includes/config.php';
include 'includes/header.php';
include 'includes/sidebar.php';

// Get statistics
$stmt = $db->query("SELECT 
    COUNT(*) as total_calls,
    SUM(CASE WHEN status = 'Success' THEN 1 ELSE 0 END) as success_calls,
    SUM(CASE WHEN status = '-' THEN 1 ELSE 0 END) as failed_calls
FROM target_numbers");
$stats = $stmt->fetch(PDO::FETCH_ASSOC);

// Get latest calls
$stmt = $db->query("SELECT * FROM target_numbers 
    ORDER BY call_date DESC LIMIT 10");
$calls = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<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">
            <!-- Card Call -->
            <div class="col-md-2">
                <div class="card">
                    <div class="card-body text-center">
                        <div class="d-grid">
                            <button class="btn btn-call mb-2" id="btnStartCall">
                                <i class="fas fa-phone"></i>
                                <span>Call</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Card Status Window -->
            <div class="col-md-2">
                <div class="card">
                    <div class="card-body">
                        <div class="status-window-system mt-2" style="background-color: #E6FFE6; padding: 8px 12px; border-radius: 4px;">
                            <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Card Total Calls -->
            <div class="col-md-2">
                <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>Total Calls</h3>
                            <h2><?php echo $stats['total_calls'] ?? 0; ?></h2>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Card Success Calls -->
            <div class="col-md-2">
                <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>Success Calls</h3>
                            <h2><?php echo $stats['success_calls'] ?? 0; ?></h2>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Card Pendings -->
            <div class="col-md-2">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-icon failed">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="stat-details">
                            <h3>Pendings</h3>
                            <h2><?php echo $stats['failed_calls'] ?? 0; ?></h2>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Card Share -->
            <div class="col-md-2">
                <div class="card">
                    <div class="card-body text-center">
                        <button class="btn btn-share" data-bs-toggle="modal" data-bs-target="#shareModal">
                            <i class="fas fa-share-alt"></i>
                            <span>Share</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-end mb-3">
            <a href="download_template.php" class="btn btn-outline-secondary btn-sm me-2">
                <i class="fas fa-file-excel me-1"></i> .xlsx Template
            </a>
            
            <button type="button" class="btn btn-outline-primary btn-sm me-2" data-bs-toggle="modal" data-bs-target="#importModal">
                <i class="fas fa-file-import me-1"></i> Import .xlsx
            </button>
            
            <a href="export_report.php" class="btn btn-outline-success btn-sm me-2">
                <i class="fas fa-file-export me-1"></i> Export Report
            </a>
            
            <button type="button" class="btn btn-outline-danger btn-sm" data-bs-toggle="modal" data-bs-target="#clearDataModal">
                <i class="fas fa-trash me-1"></i> Clear Data
            </button>
        </div>

        <div class="card">
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Target Number</th>
                            <th>Pressed Button</th>
                            <th>Status</th>
                            <th>Date and Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($calls as $call): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($call['phone_number']); ?></td>
                            <td><?php echo htmlspecialchars($call['pressed_button'] ?? '-'); ?></td>
                            <td>
                                <?php 
                                $badgeClass = 'bg-secondary';
                                if ($call['status'] === 'Success') {
                                    $badgeClass = 'bg-success';
                                } else if ($call['status'] === '-') {
                                    $badgeClass = 'bg-warning';
                                }
                                ?>
                                <span class="badge <?php echo $badgeClass; ?>"><?php echo htmlspecialchars($call['status']); ?></span>
                            </td>
                            <td><?php echo $call['call_date'] ? date('d-M-Y H:i:s', strtotime($call['call_date'])) : '-'; ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($calls)): ?>
                        <tr>
                            <td colspan="4" class="text-center">No data available</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Import Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="importForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="fileImport" class="form-label">Choose file to import</label>
                        <input type="file" class="form-control form-control-sm" id="fileImport" name="file" accept=".xlsx,.xls" required>
                    </div>
                </form>
            </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" id="btnImport">Import</button>
            </div>
        </div>
    </div>
</div>

<!-- Clear Data Modal -->
<div class="modal fade" id="clearDataModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Clear Data Confirmation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to clear all data? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger btn-sm" id="btnClearData">Clear Data</button>
            </div>
        </div>
    </div>
</div>

<!-- Share Modal -->
<div class="modal fade" id="shareModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Share Data Confirmation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>You will share phone numbers with successful status to all marketers, this will cause the target numbers to move. Make sure you have exported the report. Do you want to continue?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary btn-sm" id="btnShare">Confirm</button>
            </div>
        </div>
    </div>
</div>

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

<script>
$(document).ready(function() {
    // Fungsi untuk memperbarui tabel dan statistik
    function updateDashboard() {
        $.ajax({
            url: 'get_latest_calls.php',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                // Update tabel
                if (response.table_html) {
                    $('table tbody').html(response.table_html);
                }
                
                // Update statistik
                $('.stat-details h2').eq(0).text(response.stats.total_calls);
                $('.stat-details h2').eq(1).text(response.stats.success_calls);
                $('.stat-details h2').eq(2).text(response.stats.pending_calls);
                
                // Update status window
                var activeCallsCount = response.active_calls || 0;
                if (activeCallsCount > 0) {
                    // Ada panggilan aktif
                    $('.status-window-system').html(`
                        <div style="display: flex; flex-direction: column; gap: 8px;">
                            <div class="text-success small">Call in progress:</div>
                            <div class="text-primary small">${activeCallsCount} active calls</div>
                        </div>
                    `).show();
                } else if (response.recent_batch) {
                    // Batch panggilan baru saja selesai
                    $('.status-window-system').html(`
                        <div class="text-success small">All calls completed</div>
                    `).fadeOut(3000);
                    $('#btnStartCall').prop('disabled', false);
                } else {
                    // Tidak ada panggilan
                    $('.status-window-system').empty();
                    $('#btnStartCall').prop('disabled', false);
                }
            }
        });
    }

    // Perbarui data lebih sering (setiap 2 detik)
    setInterval(updateDashboard, 2000);

    // Handle Call Button
    $('#btnStartCall').click(function() {
        var btn = $(this);
        if (btn.prop('disabled')) return;
        
        btn.prop('disabled', true);
        
        $.ajax({
            url: 'make_batch_calls.php',
            type: 'POST',
            data: {
                batch_size: 10
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    if (response.numbers && response.numbers.length > 0) {
                        // Update status window dengan informasi batch call
                        var statusHtml = '<div style="display: flex; flex-direction: column; gap: 8px;">' +
                            '<div class="text-success small">Making batch calls:</div>';
                        
                        response.numbers.forEach(function(number) {
                            statusHtml += '<div style="display: flex; align-items: center; gap: 8px;">' +
                                '<i class="fas fa-phone-volume"></i>' +
                                '<span class="small">Calling: ' + number + '</span>' +
                                '</div>';
                        });
                        
                        statusHtml += '</div>';
                        $('.status-window-system').html(statusHtml);
                        
                        // Panggil updateDashboard segera setelah panggilan dimulai
                        updateDashboard();
                        
                        // Set timeout untuk membersihkan status window setelah 10 detik
                        setTimeout(function() {
                            $('.status-window-system').empty();
                            btn.prop('disabled', false);
                        }, 10000);
                    } else {
                        // Tidak ada nomor yang perlu dipanggil
                        $('.status-window-system').empty();
                        btn.prop('disabled', false);
                        alert('There is no number to call');
                    }
                } else {
                    alert('Error: ' + response.message);
                    btn.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                var errorMessage = 'Error occurred while making batch calls';
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch(e) {
                    console.error('Error parsing response:', e);
                }
                alert(errorMessage);
                btn.prop('disabled', false);
            }
        });
    });
    
    // Handle Import Excel
    $('#btnImport').click(function() {
        var formData = new FormData($('#importForm')[0]);
        
        $.ajax({
            url: 'import_excel.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert(response.message);
                    $('#importModal').modal('hide');
                    location.reload();
                } else {
                    alert('Error: ' + (response.message || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('XHR Status:', status);
                console.error('Error:', error);
                console.error('Response:', xhr.responseText);
                
                var errorMsg = 'Error occurred while importing data';
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response && response.message) {
                        errorMsg = response.message;
                    }
                } catch(e) {
                    console.error('Parse error:', e);
                    errorMsg = xhr.responseText || error;
                }
                alert('Import failed: ' + errorMsg);
            }
        });
    });
    
    // Handle Clear Data
    $('#btnClearData').click(function() {
        $.ajax({
            url: 'clear_data.php',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert(response.message);
                    $('#clearDataModal').modal('hide');
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function() {
                alert('Error occurred while clearing data');
            }
        });
    });

    // Handle Share Data
    $('#btnShare').click(function() {
        var btn = $(this);
        btn.prop('disabled', true);
        
        $.ajax({
            url: 'distribute_numbers.php',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert(response.message);
                    $('#shareModal').modal('hide');
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
                btn.prop('disabled', false);
            },
            error: function() {
                alert('Error occurred while distributing data');
                btn.prop('disabled', false);
            }
        });
    });
});
</script> 