<?php
/**
 * Admin: preview selected configuration description (values only, / separated).
 * GET: ?id=123&folder_id=1  — saved configuration
 * POST: same fields as configuration_detail save form — current form values (opens in new tab)
 */
require __DIR__ . '/config.php';
require_once __DIR__ . '/admin_config_helpers.php';

$id = (int) ($_POST['id'] ?? $_GET['id'] ?? 0);
$folder_id = (int) ($_POST['folder_id'] ?? $_GET['folder_id'] ?? 0);

if ($id <= 0) {
    header('Location: configurations.php?error=' . urlencode('Missing configuration ID'));
    exit;
}

$stmt = $pdo->prepare('SELECT * FROM door_configurations WHERE id = ?');
$stmt->execute([$id]);
$config = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$config) {
    header('Location: configurations.php?error=' . urlencode('Configuration not found'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $options = json_decode((string) ($config['options_json'] ?? ''), true);
    if (!is_array($options)) {
        $options = [];
    }

    if (($_POST['action'] ?? '') === 'save_quote_preview') {
        $saveResult = admin_save_configuration_quote_preview($pdo, $config, $_POST);
        if (!$saveResult['success']) {
            header('Location: configuration_detail.php?id=' . $id
                . ($folder_id ? '&folder_id=' . $folder_id : '')
                . '&quote_preview_error=' . rawurlencode((string) ($saveResult['error'] ?? 'Save failed.')));
            exit;
        }
        header('Location: configuration_detail.php?id=' . $id
            . ($folder_id ? '&folder_id=' . $folder_id : '')
            . '&quote_preview_saved=1');
        exit;
    }

    $built = admin_configuration_options_from_form_post($options, $config, $_POST);
    $config['options_json'] = json_encode($built['options']);
    $config['base_price'] = $built['base_price'];
    $config['computed_price'] = $built['computed_price'];
}

admin_render_configuration_quote_preview($pdo, $config, $folder_id);
