<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=UTF-8');

$tenant = ltrim((string)($_REQUEST['tenant'] ?? ''), '/');

if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once '../../../' . $tenant . '/config.php';
}

require_once __DIR__ . '/cron_functions.php';

if (!defined('TENANT_URL')) {
    echo json_encode(['ok' => false, 'message' => 'TENANT_URL is not defined.']);
    exit;
}

if (!isset($con) || !($con instanceof mysqli)) {
    echo json_encode(['ok' => false, 'message' => 'Database connection is not available.']);
    exit;
}

$action = (string)($_POST['cron_action'] ?? '');

if ($action === 'save_job') {
    $filename = basename((string)($_POST['filename'] ?? ''));
    $time = trim((string)($_POST['time'] ?? ''));

    if (!cronDbTableExists($con)) {
        echo json_encode(['ok' => false, 'message' => 'Missing automation_jobs table.']);
        exit;
    }

    if (!cronIsValidAutomationFile($filename)) {
        echo json_encode(['ok' => false, 'message' => 'Invalid automation file.']);
        exit;
    }

    if (!cronValidateTime($time)) {
        echo json_encode(['ok' => false, 'message' => 'Invalid send time.']);
        exit;
    }

    $recipients = cronNormaliseEmailList((string)($_POST['recipients'] ?? ''));
    $cc = cronNormaliseEmailList((string)($_POST['cc'] ?? ''));
    $bcc = cronNormaliseEmailList((string)($_POST['bcc'] ?? ''));

    if (count($recipients) === 0) {
        echo json_encode(['ok' => false, 'message' => 'At least one recipient is required.']);
        exit;
    }

    $ok = cronDbSaveJob($con, $filename, $time, $recipients, $cc, $bcc);

    echo json_encode([
        'ok' => $ok,
        'message' => $ok ? 'Cron job saved successfully.' : 'Cron job could not be saved.'
    ]);
    exit;
}

if ($action === 'toggle_job') {
    $filename = basename((string)($_POST['filename'] ?? ''));
    $status = (int)($_POST['status'] ?? 0);

    if (!cronDbTableExists($con)) {
        echo json_encode(['ok' => false, 'message' => 'Missing automation_jobs table.']);
        exit;
    }

    if (!cronIsValidAutomationFile($filename)) {
        echo json_encode(['ok' => false, 'message' => 'Invalid automation file.']);
        exit;
    }

    $ok = cronDbToggleJob($con, $filename, $status);

    echo json_encode([
        'ok' => $ok,
        'message' => $ok ? 'Cron job status updated.' : 'Cron job status could not be updated.'
    ]);
    exit;
}

echo json_encode(['ok' => false, 'message' => 'Unknown cron action.']);
exit;