telvero_whatson_talpa/api/sync_block.php

173 lines
5.3 KiB
PHP

<?php
/**
* Sync Block to Talpa
* Synchronizes all transmissions in a specific block to Talpa API
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../TalpaAPI.php';
require_once __DIR__ . '/../helpers.php';
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();
header('Content-Type: application/json');
$api = new TalpaApi();
$db = getDbConnection();
// Debug logging
$debugLog = [];
$debugLog[] = ['step' => 'Start', 'time' => date('Y-m-d H:i:s')];
// Get POST data
$input = json_decode(file_get_contents('php://input'), true);
$debugLog[] = ['step' => 'Input received', 'data' => $input];
if (!isset($input['date']) || !isset($input['channel'])) {
echo json_encode([
'success' => false,
'error' => 'Datum en channel zijn verplicht',
'debug' => $debugLog
]);
exit;
}
$date = $input['date'];
$channel = $input['channel'];
$debugLog[] = ['step' => 'Parameters', 'date' => $date, 'channel' => $channel];
try {
// Get all transmissions for this block that are not yet synced
$stmt = $db->prepare("
SELECT t.*, c.content_id, c.title as commercial_title
FROM transmissions t
JOIN commercials c ON t.commercial_id = c.id
WHERE t.start_date = ?
AND t.channel = ?
AND t.api_status != 'synced'
ORDER BY t.start_time ASC
");
$stmt->execute([$date, $channel]);
$transmissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
$debugLog[] = ['step' => 'Query executed', 'count' => count($transmissions)];
if (empty($transmissions)) {
echo json_encode([
'success' => true,
'message' => 'Geen uitzendingen om te synchroniseren',
'synced' => 0,
'failed' => 0,
'debug' => $debugLog
]);
exit;
}
$syncedCount = 0;
$failedCount = 0;
$errors = [];
$apiCalls = [];
// Sync each transmission
foreach ($transmissions as $tx) {
$txDebug = [
'transmission_id' => $tx['id'],
'title' => $tx['commercial_title'],
'time' => $tx['start_time']
];
try {
$requestData = [
"channel" => $tx['channel'],
"template" => $tx['template'],
"startDate" => $tx['start_date'],
"startTime" => $tx['start_time'],
"duration" => $tx['duration'],
"contentId" => $tx['content_id']
];
$txDebug['request'] = $requestData;
$res = $api->createTransmission($requestData);
$txDebug['response'] = $res;
$txDebug['lastResponse'] = $api->lastResponse;
// Check if sync was successful
$status = (isset($res['id']) || (isset($res['statusCode']) && $res['statusCode'] == 201)) ? 'synced' : 'error';
$txDebug['determined_status'] = $status;
// Update transmission status
$updateStmt = $db->prepare("
UPDATE transmissions
SET api_status = ?, api_response = ?
WHERE id = ?
");
$updateStmt->execute([$status, json_encode($res), $tx['id']]);
if ($status === 'synced') {
$syncedCount++;
$txDebug['result'] = 'success';
} else {
$failedCount++;
$txDebug['result'] = 'failed';
$errors[] = [
'transmission_id' => $tx['id'],
'title' => $tx['commercial_title'],
'time' => $tx['start_time'],
'error' => $res['message'] ?? json_encode($res)
];
}
} catch (Exception $e) {
$failedCount++;
$txDebug['result'] = 'exception';
$txDebug['exception'] = $e->getMessage();
$errors[] = [
'transmission_id' => $tx['id'],
'title' => $tx['commercial_title'],
'time' => $tx['start_time'],
'error' => $e->getMessage()
];
// Update status to error
$updateStmt = $db->prepare("
UPDATE transmissions
SET api_status = 'error', api_response = ?
WHERE id = ?
");
$updateStmt->execute([json_encode(['error' => $e->getMessage()]), $tx['id']]);
}
$apiCalls[] = $txDebug;
}
$debugLog[] = ['step' => 'Sync completed', 'synced' => $syncedCount, 'failed' => $failedCount];
echo json_encode([
'success' => true,
'message' => "Synchronisatie voltooid: {$syncedCount} geslaagd, {$failedCount} mislukt",
'synced' => $syncedCount,
'failed' => $failedCount,
'errors' => $errors,
'debug' => $debugLog,
'api_calls' => $apiCalls
]);
} catch (Exception $e) {
$debugLog[] = ['step' => 'Exception caught', 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString()];
echo json_encode([
'success' => false,
'error' => 'Database fout: ' . $e->getMessage(),
'debug' => $debugLog
]);
}