<?php
/**
 * Admin: email selected folder configurations to the customer via HubSpot.
 * POST: folder_id, config_ids[]
 * Optional: debug=1 — show quote payload including custom_image_url / preview (no redirect).
 *
 * Quote images: uses _custom_image_url per config, else _product_image_url.
 * Quote PDF: generated server-side, uploaded to Shopify Files, URL sent as admin_quote_pdf_url.
 */
require __DIR__ . '/config.php';
if (is_file(__DIR__ . '/hubspot-config.php')) {
    require_once __DIR__ . '/hubspot-config.php';
}
require_once __DIR__ . '/admin_config_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: folders.php');
    exit;
}

$folder_id = isset($_POST['folder_id']) ? (int) $_POST['folder_id'] : 0;
$config_ids = [];
if (!empty($_POST['config_ids']) && is_array($_POST['config_ids'])) {
    $config_ids = array_values(array_unique(array_filter(array_map('intval', $_POST['config_ids']))));
}
$debug = !empty($_POST['debug']);

if ($folder_id <= 0) {
    header('Location: folders.php');
    exit;
}

if (empty($config_ids)) {
    header('Location: folder_detail.php?id=' . $folder_id . '&quote_error=' . rawurlencode('Select at least one project to email.'));
    exit;
}

$stmt = $pdo->prepare('SELECT * FROM door_folders WHERE id = ?');
$stmt->execute([$folder_id]);
$folder = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$folder) {
    header('Location: folders.php');
    exit;
}

$result = admin_send_folder_quote_via_hubspot($pdo, $folder, $config_ids);
if (!$result['success']) {
    $errUrl = 'folder_detail.php?id=' . $folder_id . '&quote_error=' . rawurlencode($result['error']);
    if ($debug) {
        $errUrl .= '&quote_debug=1';
    }
    header('Location: ' . $errUrl);
    exit;
}

$quote = is_array($result['quote'] ?? null) ? $result['quote'] : [];
$count = (int) ($quote['item_count'] ?? count($config_ids));
$imageUrls = is_array($quote['image_urls'] ?? null) ? $quote['image_urls'] : [];
$imageCount = count($imageUrls);
$pdfUrl = trim((string) ($result['pdf_url'] ?? ($quote['pdf_url'] ?? '')));

if ($debug) {
    header('Content-Type: text/html; charset=utf-8');
    $previewUrl = admin_quote_preview_url($folder_id, admin_normalize_web_path(dirname($_SERVER['SCRIPT_NAME'] ?? '')));
    $hubspotProps = admin_hubspot_quote_property_payload($folder, $quote);
    echo '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Quote email debug</title>';
    echo '<style>body{font-family:Arial,sans-serif;margin:1.5rem;color:#0f172a;} pre{background:#f8fafc;border:1px solid #e2e8f0;padding:1rem;border-radius:8px;overflow:auto;} .imgs{display:flex;flex-wrap:wrap;gap:1rem;margin:1rem 0;} .imgs img{max-width:200px;border-radius:8px;border:1px solid #e2e8f0;}</style>';
    echo '</head><body><h1>Quote email — debug</h1>';
    echo '<p><strong>Success.</strong> Send mode: ' . htmlspecialchars((string) ($result['send_mode'] ?? 'workflow'), ENT_QUOTES, 'UTF-8') . '</p>';
    echo '<p><strong>Items:</strong> ' . (int) $count . ' &nbsp; <strong>Images:</strong> ' . (int) $imageCount;
    if ($pdfUrl !== '') {
        echo ' &nbsp; <strong>PDF:</strong> <a href="' . htmlspecialchars($pdfUrl, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener">Shopify CDN</a>';
    }
    echo '</p>';
    if ($imageCount > 0) {
        echo '<div class="imgs">';
        foreach ($imageUrls as $url) {
            $u = htmlspecialchars((string) $url, ENT_QUOTES, 'UTF-8');
            echo '<div><img src="' . $u . '" alt=""><br><small>' . $u . '</small></div>';
        }
        echo '</div>';
    } else {
        echo '<p><em>No custom_image_url or product_image_url on selected configs.</em></p>';
    }
    echo '<h2>HubSpot contact properties</h2><pre>' . htmlspecialchars(json_encode($hubspotProps, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') . '</pre>';
    echo '<h2>Quote HTML (admin_quote_html)</h2><div style="border:1px solid #e2e8f0;padding:1rem;border-radius:8px;background:#fff;">';
    echo (string) ($quote['html'] ?? '');
    echo '</div>';
    echo '<p style="margin-top:1.25rem;"><a href="' . htmlspecialchars($previewUrl, ENT_QUOTES, 'UTF-8') . '">Open logged preview</a>';
    echo ' &nbsp; <a href="folder_detail.php?id=' . (int) $folder_id . '">Back to project</a></p>';
    echo '</body></html>';
    exit;
}

$query = [
    'quote_sent'   => '1',
    'quote_count'  => (string) $count,
    'quote_images' => (string) $imageCount,
];
if ($imageCount === 0) {
    $query['quote_no_images'] = '1';
}
if (!empty($result['extra_properties_skipped'])) {
    $query['quote_extra_skipped'] = '1';
}
if ($pdfUrl !== '') {
    $query['quote_pdf_url'] = $pdfUrl;
}
header('Location: folder_detail.php?id=' . $folder_id . '&' . http_build_query($query));
exit;
