telvero_whatson_talpa/api/get_available_source_blocks.php
2026-02-19 15:58:15 +01:00

82 lines
2.5 KiB
PHP

<?php
/**
* API Endpoint: Get Available Source Blocks
* Returns available source blocks for a specific date, channel, and template
*/
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../auth/auth_functions.php';
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();
header('Content-Type: application/json');
if (!isLoggedIn()) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'Niet geautoriseerd.']);
exit;
}
try {
$db = getDbConnection();
// Validate input
$date = $_GET['date'] ?? null;
$channel = $_GET['channel'] ?? null;
$templateId = $_GET['template_id'] ?? null;
if (!$date || !$channel || !$templateId) {
jsonResponse(['success' => false, 'error' => 'Missing parameters'], 400);
}
if (!isValidDate($date)) {
jsonResponse(['success' => false, 'error' => 'Invalid date format'], 400);
}
// Ensure blocks exist for this date
ensureDailyBlocks($db, $date, $date);
// Get the template name from the target template
$stmt = $db->prepare("SELECT name FROM block_templates WHERE id = ?");
$stmt->execute([$templateId]);
$targetTemplateName = $stmt->fetchColumn();
if (!$targetTemplateName) {
jsonResponse(['success' => false, 'error' => 'Target template not found'], 404);
}
// Get blocks for this date and channel with matching template NAME (not ID)
// This allows copying between different template IDs that have the same name
$stmt = $db->prepare("
SELECT
db.*,
bt.name as template_name,
COUNT(t.id) as transmission_count
FROM daily_blocks db
LEFT JOIN block_templates bt ON db.template_id = bt.id
LEFT JOIN transmissions t ON t.start_date = db.block_date
AND t.channel = db.channel
AND t.start_time >= db.actual_start_time
AND t.start_time < COALESCE(db.actual_end_time, '23:59:59')
WHERE db.block_date = ?
AND db.channel = ?
AND bt.name = ?
GROUP BY db.id
ORDER BY db.actual_start_time
");
$stmt->execute([$date, $channel, $targetTemplateName]);
$blocks = $stmt->fetchAll();
jsonResponse([
'success' => true,
'blocks' => $blocks
]);
} catch (Exception $e) {
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}