<?php
// API: enable_show.php - Toggle Show and (if authenticated) attempt to send a "Show enabled" push.
require __DIR__ . '/../auth.php';
mvlog_require_login();

// Web-server side handler to toggle "Show" for an MVLog job and send a web-push immediately if appropriate.
// Usage (POST): job=<job> show=1|0

$MVLOG_ROOT = dirname(__DIR__);
$job = $_POST['job'] ?? '';
$show = isset($_POST['show']) ? filter_var($_POST['show'], FILTER_VALIDATE_BOOLEAN) : true;

// Basic validation
if (!preg_match('/^[0-9]{8}[-_][A-Za-z0-9._-]+$/', $job)) {
    http_response_code(400);
    echo 'invalid job';
    exit;
}

$jobdir = "$MVLOG_ROOT/in-dir/$job";
if (!is_dir($jobdir)) {
    http_response_code(404);
    echo 'job not found';
    exit;
}

$enabled_file = "$jobdir/.movmaker-enabled";
$cache_file = "$MVLOG_ROOT/cache/push_notifications.json";

if ($show) {
    file_put_contents($enabled_file, date(DATE_ATOM) . PHP_EOL, LOCK_EX);

    // Attempt to send push (non-fatal). Uses lib/send_push.php
    $sent = false;
    if (is_file(__DIR__ . '/../lib/send_push.php')) {
        include_once __DIR__ . '/../lib/send_push.php';
        try {
            $sent = try_send_show_notification($job, $jobdir, $MVLOG_ROOT, '/var/log/mvlog_notify.log');
        } catch (Throwable $e) {
            error_log("[mvlog] notify exception for $job: " . $e->getMessage() . "\n", 3, '/var/log/mvlog_notify.log');
            $sent = false;
        }
    } else {
        error_log("[mvlog] send_push helper missing, cannot send notification for $job\n", 3, '/var/log/mvlog_notify.log');
    }

    if ($sent) {
        echo 'enabled';
    } else {
        echo 'enabled (no notification)';
    }
} else {
    @unlink($enabled_file);
    echo 'disabled';
}

exit;
