<?php
require_once 'includes/config.php';

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

// Get latest call status
$latest_call = null;
if (!empty($calls)) {
    $latest_call = $calls[0];
}

$html = '';
foreach ($calls as $call) {
    $badgeClass = 'bg-secondary';
    if ($call['status'] === 'Success') {
        $badgeClass = 'bg-success';
    } else if ($call['status'] === '-') {
        $badgeClass = 'bg-warning';
    }
    
    $html .= '<tr>';
    $html .= '<td>' . htmlspecialchars($call['phone_number']) . '</td>';
    $html .= '<td>' . htmlspecialchars($call['pressed_button'] ?? '-') . '</td>';
    $html .= '<td><span class="badge ' . $badgeClass . '">' . htmlspecialchars($call['status']) . '</span></td>';
    $html .= '<td>' . ($call['call_date'] ? date('d-M-Y H:i:s', strtotime($call['call_date'])) : '-') . '</td>';
    $html .= '</tr>';
}

if (empty($calls)) {
    $html = '<tr><td colspan="4" class="text-center">No data available</td></tr>';
}

// Get updated 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 pending_calls
FROM target_numbers");
$stats = $stmt->fetch(PDO::FETCH_ASSOC);

// Tambahkan query untuk menghitung panggilan aktif
$stmt = $db->query("SELECT COUNT(*) as active_calls 
    FROM target_numbers 
    WHERE status = '-' 
    AND call_date IS NOT NULL 
    AND pressed_button IS NULL
    AND call_date >= DATE_SUB(NOW(), INTERVAL 30 SECOND)");
$active_calls = $stmt->fetch(PDO::FETCH_ASSOC)['active_calls'];

// Cek apakah ada batch yang baru selesai
$stmt = $db->query("SELECT COUNT(*) as recent_completed 
    FROM target_numbers 
    WHERE call_date IS NOT NULL 
    AND call_date >= DATE_SUB(NOW(), INTERVAL 30 SECOND)
    AND (status = 'Success' OR pressed_button IS NOT NULL)");
$recent_batch = $stmt->fetch(PDO::FETCH_ASSOC)['recent_completed'] > 0;

echo json_encode([
    'table_html' => $html,
    'stats' => [
        'total_calls' => $stats['total_calls'],
        'success_calls' => $stats['success_calls'],
        'pending_calls' => $stats['pending_calls']
    ],
    'active_calls' => $active_calls,
    'recent_batch' => $recent_batch,
    'latest_call' => $latest_call
]); 