<?php
// POST { import_id, action: 'repoint'|'dismiss', domain? }
// 'repoint' rewrites the imported zone's apex MX to WHP's mail server.
// 'dismiss' just marks the choice in the JSON summary (no DNS change).

require_once('../auto-prepend.php');
require_once('../libs/CpanelImportSummary.php');
require_once('../libs/mysqlmgmt.php');

if (!defined('AUTH_USER')) {
    http_response_code(401); header('Content-Type: application/json');
    echo json_encode(['error' => 'Not authenticated']); exit;
}
header('Content-Type: application/json');
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    http_response_code(405); echo json_encode(['error' => 'POST required']); exit;
}

$importId = $_POST['import_id'] ?? '';
$action   = $_POST['action']    ?? '';
$domain   = $_POST['domain']    ?? null;

if (!preg_match('/^import_[A-Za-z0-9]+$/', $importId)) {
    http_response_code(400); echo json_encode(['error' => 'invalid import_id']); exit;
}
if (!in_array($action, ['repoint', 'dismiss'], true)) {
    http_response_code(400); echo json_encode(['error' => 'invalid action']); exit;
}

$pdo = (new mysqlmgmt())->getMySQLConnection();
$pdo->exec('USE whp');
$stmt = $pdo->prepare('SELECT username FROM cpanel_imports WHERE import_id = ?');
$stmt->execute([$importId]);
$owner = $stmt->fetchColumn();
if (!$owner || ($owner !== AUTH_USER && AUTH_USER !== 'root')) {
    http_response_code(403); echo json_encode(['error' => 'forbidden']); exit;
}

if ($action === 'dismiss') {
    $ok = CpanelImportSummary::markMxAction($importId, 'dismissed', AUTH_USER);
    echo json_encode(['success' => $ok, 'action' => 'dismissed']);
    exit;
}

// action === 'repoint'
require_once('../libs/pdns-integration.php');
$dns = new PowerDNSIntegration($pdo);
$summary = CpanelImportSummary::readSummary($importId);
if ($summary === null) {
    http_response_code(404); echo json_encode(['error' => 'summary missing']); exit;
}

// WHP's mail-server hostname: prefer a configured constant if one exists;
// otherwise fall back to "mail.<zone>." per zone (which means the zone's own
// MX A record needs to resolve -- usually true since createZoneForDomain
// publishes a `mail` A by default).
$mxTarget = (defined('WHP_MAIL_SERVER_HOST') && WHP_MAIL_SERVER_HOST) ? WHP_MAIL_SERVER_HOST : null;

$failures = [];
$repointed = [];
foreach (($summary['sites'] ?? []) as $site) {
    $zone = $site['domain'] ?? null;
    if ($zone === null) continue;
    if ($domain && $zone !== $domain) continue; // optional per-domain filter
    $target = $mxTarget ?: ('mail.' . $zone . '.');

    // PowerDNSIntegration exposes deleteRecord($domain_name, $name, $type) and
    // addRecord($domain_name, $name, $type, $content, $ttl, $priority).
    // No replaceRecords primitive, so do delete-then-add.
    try {
        // Best-effort delete of any existing apex MX records. Zone apex is
        // represented as $name === $domain_name in deleteRecord().
        @$dns->deleteRecord($zone, $zone, 'MX');
        $dns->addRecord($zone, $zone, 'MX', $target, 3600, 10);
        $repointed[] = ['zone' => $zone, 'target' => $target];
    } catch (Exception $e) {
        $failures[$zone] = $e->getMessage();
    }
}

if ($failures && !$repointed) {
    http_response_code(500);
    echo json_encode(['success' => false, 'failures' => $failures]); exit;
}
if ($failures) {
    http_response_code(207); // partial
    echo json_encode(['success' => false, 'partial' => $failures, 'repointed' => $repointed]); exit;
}

CpanelImportSummary::markMxAction($importId, 'repointed', AUTH_USER);
echo json_encode(['success' => true, 'action' => 'repointed', 'repointed' => $repointed]);
