<?php
/**
 * Email Archival API for Web Hosting Panel
 * Handles AJAX requests for Bichon email archival operations.
 *
 * SECURITY: The plaintext IMAP password submitted to ?action=enable is
 * forwarded directly to emailmgmt::enableArchival() and MUST NEVER be logged.
 */

// Set content type to JSON
header('Content-Type: application/json');

// Check authentication (auto-prepend handles login redirect for HTML pages,
// but for API endpoints we want a JSON 401 if AUTH_USER is missing)
if (!defined('AUTH_USER')) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Authentication required']);
    exit();
}

// Auto-prepend has already finished its session writes (nonce rotation, CSRF
// validation, csrf_token init). Release the lock now so concurrent AJAX from
// the same page doesn't queue behind a slow page render.
if (session_status() === PHP_SESSION_ACTIVE) {
    session_write_close();
}

require_once('/docker/whp/web/libs/emailmgmt.php');

$EmailMgmt = new emailmgmt();

// Get request method and action
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// For POST requests, also check for action in JSON body
if ($method === 'POST' && empty($action)) {
    $input = json_decode(file_get_contents('php://input'), true);
    if ($input && !empty($input['action'])) {
        $action = $input['action'];

        // If CSRF token is in JSON body, make it available for validation
        if (isset($input['csrf_token']) && !isset($_POST['csrf_token'])) {
            $_POST['csrf_token'] = $input['csrf_token'];
        }
    }
}

// Note: CSRF validation is performed globally in auto-prepend.php for any
// authenticated POST request, so per-action validation is intentionally
// omitted here (matches web-files/api/email-management.php convention).

switch ($action) {
    case 'enable':
        if ($method !== 'POST') {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
            break;
        }

        try {
            // For 'enable' we do NOT json_decode the body — the password must
            // come through $_POST so it stays out of any var_dump/log of $input.
            $email_id = filter_var($_POST['email_id'] ?? null, FILTER_VALIDATE_INT);
            if ($email_id === false || $email_id === null) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid email_id']);
                break;
            }

            if (!isset($_POST['password']) || $_POST['password'] === '') {
                echo json_encode(['status' => 'error', 'message' => 'Password is required']);
                break;
            }

            // Optional separate Bichon-WebUI password. If absent or empty,
            // emailmgmt::enableArchival() falls back to the mailbox password.
            $bichon_pw = $_POST['bichon_password'] ?? null;
            if (is_string($bichon_pw) && $bichon_pw === '') {
                $bichon_pw = null;
            }

            // Pass plaintext passwords straight through; do not assign to
            // named locals that might end up in a backtrace dump.
            $result = $EmailMgmt->enableArchival(
                $email_id,
                AUTH_USER,
                $_POST['password'],
                $bichon_pw
            );

            echo json_encode($result);
        } catch (Throwable $e) {
            // Never include request body (especially passwords) in logs
            error_log("email-archival.php: " . $e->getMessage());
            echo json_encode(['status' => 'error', 'message' => 'Internal error']);
        }
        break;

    case 'reset_password':
        if ($method !== 'POST') {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
            break;
        }

        try {
            // Like ?action=enable, deliberately read from $_POST so the
            // plaintext password never ends up in a $input dump.
            $email_id = filter_var($_POST['email_id'] ?? null, FILTER_VALIDATE_INT);
            if ($email_id === false || $email_id === null) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid email_id']);
                break;
            }

            if (!isset($_POST['new_password']) || $_POST['new_password'] === '') {
                echo json_encode(['status' => 'error', 'message' => 'New password is required']);
                break;
            }

            $result = $EmailMgmt->resetBichonPassword(
                $email_id,
                AUTH_USER,
                $_POST['new_password']
            );

            echo json_encode($result);
        } catch (Throwable $e) {
            // Never include request body (especially $_POST['new_password']) in logs
            error_log("email-archival.php: " . $e->getMessage());
            echo json_encode(['status' => 'error', 'message' => 'Internal error']);
        }
        break;

    case 'disable':
        if ($method !== 'POST') {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
            break;
        }

        try {
            $input = json_decode(file_get_contents('php://input'), true);
            if (!$input) {
                $input = $_POST;
            }

            $email_id = filter_var($input['email_id'] ?? null, FILTER_VALIDATE_INT);
            if ($email_id === false || $email_id === null) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid email_id']);
                break;
            }

            // Default purge_remote = true. Only the literal string "false",
            // "0", or boolean false flips it off (strict cast).
            $purge_remote = true;
            if (array_key_exists('purge_remote', $input)) {
                $raw = $input['purge_remote'];
                if ($raw === false || $raw === 'false' || $raw === '0' || $raw === 0) {
                    $purge_remote = false;
                }
            }

            $result = $EmailMgmt->disableArchival($email_id, AUTH_USER, $purge_remote);
            echo json_encode($result);
        } catch (Throwable $e) {
            error_log("email-archival.php: " . $e->getMessage());
            echo json_encode(['status' => 'error', 'message' => 'Internal error']);
        }
        break;

    case 'status':
        if ($method !== 'GET') {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
            break;
        }

        try {
            $email_id = filter_var($_GET['email_id'] ?? null, FILTER_VALIDATE_INT);
            if ($email_id === false || $email_id === null) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid email_id']);
                break;
            }

            $result = $EmailMgmt->getArchivalStatus($email_id);
            echo json_encode($result);
        } catch (Throwable $e) {
            error_log("email-archival.php: " . $e->getMessage());
            echo json_encode(['status' => 'error', 'message' => 'Internal error']);
        }
        break;

    default:
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
        break;
}
?>
