<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !isset($data['phone_name'])) {
    http_response_code(400);
    echo json_encode(['error' => 'phone_name is required']);
    exit;
}

$conn = getDBConnection();

// Create sync_heartbeat table if not exists
$sql = "CREATE TABLE IF NOT EXISTS sync_heartbeat (
    id INT AUTO_INCREMENT PRIMARY KEY,
    phone_name VARCHAR(100),
    last_heartbeat TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    sync_status VARCHAR(50) DEFAULT 'active',
    sms_count INT DEFAULT 0,
    calls_count INT DEFAULT 0,
    INDEX idx_phone_name (phone_name),
    INDEX idx_last_heartbeat (last_heartbeat)
)";

if (!$conn->query($sql)) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to create sync_heartbeat table']);
    exit;
}

$phoneName = $data['phone_name'];
$syncStatus = $data['sync_status'] ?? 'active';
$smsCount = $data['sms_count'] ?? 0;
$callsCount = $data['calls_count'] ?? 0;

// Insert or update heartbeat
$stmt = $conn->prepare("INSERT INTO sync_heartbeat (phone_name, sync_status, sms_count, calls_count) 
                       VALUES (?, ?, ?, ?) 
                       ON DUPLICATE KEY UPDATE 
                       last_heartbeat = CURRENT_TIMESTAMP,
                       sync_status = VALUES(sync_status),
                       sms_count = VALUES(sms_count),
                       calls_count = VALUES(calls_count)");

$stmt->bind_param("ssii", $phoneName, $syncStatus, $smsCount, $callsCount);

if ($stmt->execute()) {
    echo json_encode([
        'success' => true,
        'message' => 'Heartbeat recorded successfully',
        'phone_name' => $phoneName,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
} else {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to record heartbeat']);
}

$stmt->close();
$conn->close();
?>

