<?php
// callback.php
require_once 'db.php'; // File with your database connection

$data = json_decode(file_get_contents('php://input'), true);
$videoId = isset($_GET['video_id']) ? $_GET['video_id'] : null;

$texters = "Lets see call back data :";
$data_debugging = array($texters, $data);
echo json_encode($data_debugging, JSON_FORCE_OBJECT);
error_log('Callbak JSON Data: ' . $data);

if (isset($data['link']) && $videoId) {
    $downloadLink = $data['link'];
    
    try {
        saveAudioLinkToDatabase($downloadLink, $videoId);
        echo json_encode(['status' => 'success', 'message' => 'Callback processed successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid callback data or missing video ID']);
}

function saveAudioLinkToDatabase($audioLink, $videoId) {
    global $pdo;
    
    $stmt = $pdo->prepare("UPDATE tbl_videos SET audio_link = ? WHERE video_id = ?");
    if (!$stmt->execute([$audioLink, $videoId])) {
        throw new Exception('Failed to update database');
    }
    
    return true;
}
?>