<?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 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>
                            <th>Action</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>
                            <td>
                                <?php
                                $actionStatus = '-';
                                if ($call['pressed_button'] === '1') {
                                    $actionStatus = '<span class="badge bg-success">Completed</span>';
                                } else if ($call['call_date'] && 
                                    $call['status'] === '-' && 
                                    $call['pressed_button'] === null &&
                                    $call['call_sid'] !== null) {
                                    $actionStatus = '<span class="badge bg-warning">Calling</span>';
                                }
                                echo $actionStatus;
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($calls)): ?>
                        <tr>
                            <td colspan="5" 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) {
                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);
            }
        });
    }

    // Variable untuk tracking status auto-call
    let isAutoCalling = false;
    let autoCallInterval;

    // Handle tombol Call 
    $('#btnStartCall').click(function() {
        var btn = $(this);
        if (isAutoCalling) {
            // Stop auto-calling
            clearInterval(autoCallInterval);
            isAutoCalling = false;
            btn.removeClass('btn-danger').addClass('btn-call');
            btn.find('span').text('Call');
        } else {
            // Start auto-calling
            isAutoCalling = true;
            btn.removeClass('btn-call').addClass('btn-danger');
            btn.find('span').text('Stop');
            
            // Mulai panggilan pertama
            makeCall();
            
            // Set interval untuk panggilan berikutnya setiap 5 detik
            autoCallInterval = setInterval(makeCall, 5000);
        }
    });

    function makeCall() {
        $.ajax({
            url: 'make_batch_calls.php',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    updateDashboard();
                    
                    // Jika tidak ada nomor tersisa, hentikan auto-calling
                    if (response.message === 'No numbers to call') {
                        clearInterval(autoCallInterval);
                        isAutoCalling = false;
                        $('#btnStartCall').removeClass('btn-danger').addClass('btn-call')
                            .find('span').text('Call');
                    }
                }
            },
            error: function() {
                // Jika terjadi error, tetap lanjutkan auto-calling
                console.log('Error in makeCall, continuing auto-calling');
            }
        });
    }

    // Update dashboard setiap 2 detik
    setInterval(updateDashboard, 2000);

    // 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);
            }
        });
    });

    // Pastikan membersihkan interval saat halaman unload
    $(window).on('unload', function() {
        stopChecking();
    });
});
</script> 