<?php
// ECWID Order Confirmation Page with FedEx Transit Times
require_once "/var/www/html/config/production-schedule.php";
// Configuration
$ecwid_store_id = '10569756';
$ecwid_secret_token = 'secret_qv9VpA4YrCV5ytSWzMkat9FNZRweWL1W';

// FedEx API Configuration (Sandbox - change to production when ready)
$fedex_api_key = 'l7bbb5d60e0dbb419da6ea6ead6ff80ccc';
$fedex_secret_key = '7f40b6bcfc4544fcbe2807c31ff0a5bd';
$fedex_base_url = 'https://apis-sandbox.fedex.com';

// Origin address (Berkeley)
$origin_postal = '94710';
$origin_country = 'US';

// Shipping method mapping
$shipping_map = [
    'Berkeley In-store Pickup' => 'PICKUP',
    'FedEx 2 Business' => 'FEDEX_2_DAY',
    'FedEx 3 Business' => 'FEDEX_EXPRESS_SAVER',
    'FedEx Free Ground' => 'FEDEX_GROUND',
    'FedEx Next day' => 'PRIORITY_OVERNIGHT',
    'FedEx Overnight' => 'PRIORITY_OVERNIGHT',
    'FedEx International Economy' => 'INTERNATIONAL_ECONOMY',
    'FedEx International Priority' => 'INTERNATIONAL_PRIORITY',
];
$config_file = "/var/www/html/config/holidays.json";
$holidays = loadHolidays($config_file);
$conference_config_file = "/var/www/html/config/conference-skus.json";
$conference_skus = json_decode(file_get_contents($conference_config_file), true)["conference_skus"] ?? [];

$order_id = isset($_GET['order']) ? $_GET['order'] : null;
if (!$order_id) { die('Order number not provided.'); }

function getEcwidOrder($store_id, $token, $order_id) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://app.ecwid.com/api/v3/{$store_id}/orders/{$order_id}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer {$token}"]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($http_code === 200) ? json_decode($response, true) : null;
}

function getFedExToken($api_key, $secret_key, $base_url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "{$base_url}/oauth/token");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'client_credentials',
        'client_id' => $api_key,
        'client_secret' => $secret_key
    ]));
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    return $data['access_token'] ?? null;
}

function getFedExTransitTime($token, $base_url, $origin_postal, $origin_country, $dest_postal, $dest_country, $service_type, $ship_date) {
    $carrier_codes = (strpos($service_type, 'INTERNATIONAL') !== false) ? ['FDXE'] : ['FDXG', 'FDXE'];
    
    $request_body = [
        'requestedShipment' => [
            'shipper' => ['address' => ['postalCode' => $origin_postal, 'countryCode' => $origin_country]],
            'recipients' => [['address' => ['postalCode' => $dest_postal, 'countryCode' => $dest_country]]],
            'packagingType' => 'YOUR_PACKAGING',
            'pickupType' => 'DROPOFF_AT_FEDEX_LOCATION',
            'shipDateStamp' => $ship_date,
            'requestedPackageLineItems' => [['weight' => ['units' => 'LB', 'value' => 2]]]
        ],
        'carrierCodes' => $carrier_codes
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "{$base_url}/availability/v1/transittimes");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json", "Authorization: Bearer {$token}"]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_body));
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    
    if (isset($data['output']['transitTimes'][0]['transitTimeDetails'])) {
        foreach ($data['output']['transitTimes'][0]['transitTimeDetails'] as $detail) {
            if ($detail['serviceType'] === $service_type) {
                return [
                    'date' => $detail['commit']['dateDetail']['day'] ?? null,
                    'time' => $detail['commit']['dateDetail']['time'] ?? null,
                    'dayOfWeek' => $detail['commit']['dateDetail']['dayOfWeek'] ?? null
                ];
            }
        }
    }
    return null;
}

function mapShippingToFedEx($shipping_name, $shipping_map) {
    foreach ($shipping_map as $pattern => $service) {
        if (stripos($shipping_name, $pattern) !== false) return $service;
    }
    return 'FEDEX_GROUND';
}

function formatFileSize($bytes) {
    if ($bytes >= 1048576) return number_format($bytes / 1048576, 1) . ' MB';
    if ($bytes >= 1024) return number_format($bytes / 1024, 1) . ' KB';
    return $bytes . ' bytes';
}

function getFileType($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if (in_array($ext, ['pdf'])) return 'pdf';
    if (in_array($ext, ['jpg','jpeg','png','gif','bmp','tiff','tif'])) return 'img';
    if (in_array($ext, ['ppt','pptx'])) return 'ppt';
    return 'unknown';
}

$order = getEcwidOrder($ecwid_store_id, $ecwid_secret_token, $order_id);
if (!$order) { die('Order not found or API error.'); }

$customer_name = $order['billingPerson']['name'] ?? 'Customer';
$customer_email = $order['email'] ?? '';
$order_number = $order['orderNumber'] ?? $order_id;
$order_date_raw = $order["createDate"] ?? "now";
$order_date = date("M j, Y \\a\\t g:i A", strtotime($order_date_raw));
$order_total = number_format($order['total'] ?? 0, 2);
$shipping_method_name = $order['shippingOption']['shippingMethodName'] ?? 'Standard Shipping';
$fedex_service_type = mapShippingToFedEx($shipping_method_name, $shipping_map);
$is_pickup = ($fedex_service_type === 'PICKUP');

$ship_to = $order['shippingPerson'] ?? [];
$ship_to_name = $ship_to['name'] ?? $customer_name;
$ship_to_street = $ship_to['street'] ?? '';
$ship_to_city = $ship_to['city'] ?? '';
$ship_to_state = $ship_to['stateOrProvinceCode'] ?? '';
$ship_to_postal = $ship_to['postalCode'] ?? '';
$ship_to_country = $ship_to['countryCode'] ?? 'US';
$ship_to_phone = $ship_to['phone'] ?? '';

$bill_to = $order['billingPerson'] ?? [];
$bill_to_name = $bill_to['name'] ?? $customer_name;
$bill_to_street = $bill_to['street'] ?? '';
$bill_to_city = $bill_to['city'] ?? '';
$bill_to_state = $bill_to['stateOrProvinceCode'] ?? '';
$bill_to_postal = $bill_to['postalCode'] ?? '';
$bill_to_country = $bill_to['countryCode'] ?? 'US';
$bill_to_phone = $bill_to['phone'] ?? '';
$payment_method = $order['paymentMethod'] ?? 'Credit or debit card';
// Calculate ship date based on production schedule
$ship_date_str = date("Y-m-d", strtotime("+1 day"));
$is_conditional = false;

$pickup_display = "Next Business Day";
if ($is_pickup) {
    $pickup_date = calculatePickupDate($order_date_raw, $holidays);
    $pickup_display = formatPickupDisplay($pickup_date);
}
$delivery_date = '';
$delivery_time = '';
if (!$is_pickup && !empty($ship_to_postal)) {
    $fedex_token = getFedExToken($fedex_api_key, $fedex_secret_key, $fedex_base_url);
    if ($fedex_token) {
        $transit_info = getFedExTransitTime($fedex_token, $fedex_base_url, $origin_postal, $origin_country, $ship_to_postal, $ship_to_country, $fedex_service_type, $ship_date_str);
        if ($transit_info) {
            $delivery_date = $transit_info['date'];
            $delivery_time = $transit_info['time'];
        }
    }
}

$delivery_display = '';
$delivery_time_display = '';
if ($delivery_date) {
    $date_obj = DateTime::createFromFormat('M-d-Y', $delivery_date);
    $delivery_display = $date_obj ? $date_obj->format('F j, Y') : $delivery_date;
    if ($delivery_time === '12:00') $delivery_time_display = 'by 12:00 PM (noon)';
    elseif ($delivery_time === '17:00' || $delivery_time === '23:59') $delivery_time_display = 'by end of day';
    elseif ($delivery_time) $delivery_time_display = 'by ' . date('g:i A', strtotime($delivery_time));
}

// Process ALL items in the order
$items = $order['items'] ?? [];
$product_names = [];
$product_skus = [];
$poster_sizes = [];
$poster_materials = [];
$quantities = [];
$files = [];
$is_conference = false;
$conference_message = "";
$assurance_proof = 'No';
$assurance_proof_provided = false;
$assurance_proof_requested = false;

foreach ($items as $item) {
    $product_names[] = $item['name'] ?? 'Poster';
    $product_skus[] = $item['sku'] ?? '';
    $quantities[] = $item['quantity'] ?? 1;
    
    // Check for conference SKU
    $item_sku = $item['sku'] ?? '';
    foreach ($conference_skus as $conf) {
        if ($conf["active"] && stripos($item_sku, $conf["prefix"]) === 0) {
            $is_conference = true;
            $conference_message = $conf["message"];
            break;
        }
    }
    
    $item_size = '';
    $item_material = '';
    
    if (isset($item['selectedOptions'])) {
        foreach ($item['selectedOptions'] as $option) {
            $opt_name = $option['name'] ?? '';
            $opt_value = $option['value'] ?? '';
            if (stripos($opt_name, 'Size') !== false) $item_size = $opt_value;
            if (stripos($opt_name, 'Material') !== false) $item_material = $opt_value;
            if (stripos($opt_name, 'Assurance Proof') !== false) {
                $assurance_proof = $opt_value;
                $assurance_proof_provided = true;
                if (stripos($opt_value, 'Yes') !== false) $assurance_proof_requested = true;
            }
            if ($option['type'] === 'FILES' && isset($option['files'])) {
                foreach ($option['files'] as $file) {
                    $files[] = ['name' => $file['name'] ?? 'file', 'url' => $file['url'] ?? '', 'size' => $file['size'] ?? 0];
                }
            }
        }
    }
    
    // Auto-detect material from product name if not set
    if (empty($item_material)) {
        $item_name = $item['name'] ?? '';
        if (stripos($item_name, 'Fabric') !== false) $item_material = 'Fabric';
        elseif (stripos($item_name, 'Vinyl') !== false) $item_material = 'Vinyl';
        elseif (stripos($item_name, 'Trifold') !== false) $item_material = 'Trifold Board';
        else $item_material = 'Paper';
    }
    
    $poster_sizes[] = $item_size;
    $poster_materials[] = $item_material;
}

// For display: join multiple values with line breaks
$product_name = implode('<br>', $product_names);
$poster_size = implode('<br>', $poster_sizes);
$poster_material = implode('<br>', $poster_materials);
$quantity = implode('<br>', $quantities);
$product_sku = $product_skus[0] ?? '';

$files_json = json_encode(array_map(function($file) {
    return ['name' => $file['name'], 'url' => $file['url'], 'size' => formatFileSize($file['size']), 'type' => getFileType($file['name'])];
}, $files));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order #<?php echo htmlspecialchars($order_number); ?> - PosterPresentations.com</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        html, body { height: 100%; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f2f2f2; color: #333; font-size: 14px; }
        .dashboard { min-height: 100vh; display: flex; flex-direction: column; }
        .top-nav { background: #003366; color: white; padding: 12px 30px; }
        .logo { font-size: 18px; font-weight: 700; color: white; }
        .status-bar { background: #184163; color: white; padding: 20px 30px; display: flex; align-items: center; justify-content: space-between; }
        .status-left { display: flex; align-items: center; gap: 15px; }
        .status-icon { width: 50px; height: 50px; background: #27ae60; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 24px; }
        .status-text .thank-you { font-size: 14px; opacity: 0.9; margin-bottom: 2px; }
        .status-text h1 { font-size: 20px; font-weight: 600; }
        .status-text p { font-size: 13px; opacity: 0.85; }
        .order-id { background: rgba(255,255,255,0.1); padding: 10px 20px; border-radius: 6px; text-align: right; }
        .order-id .number { font-size: 20px; font-weight: 700; color: white; }
        .order-id .date { font-size: 12px; opacity: 0.8; }
        .main-grid { flex: 1; display: grid; grid-template-columns: 2fr 1fr; gap: 20px; padding: 20px 30px; max-width: 1800px; margin: 0 auto; width: 100%; }
        .card { background: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); overflow: hidden; }
        .card-header { background: #003366; color: white; padding: 12px 18px; font-weight: 600; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; }
        .card-body { padding: 18px; }
        .preview-card { grid-row: span 3; }
        .preview-area { background: #fafafa; display: flex; align-items: center; justify-content: center; min-height: 500px; }
        .preview-area canvas, .preview-area img { max-width: 100%; max-height: 600px; box-shadow: 0 2px 15px rgba(0,0,0,0.1); }
        .file-toolbar { padding: 12px 18px; background: #f8f8f8; border-top: 1px solid #eee; display: flex; align-items: center; gap: 12px; }
        .file-type-badge { background: #e74c3c; color: white; padding: 4px 10px; border-radius: 4px; font-size: 11px; font-weight: 700; }
        .file-type-badge.ppt { background: #d35400; }
        .file-type-badge.img { background: #27ae60; }
        .file-details .name { font-weight: 600; color: #184163; }
        .file-details .meta { font-size: 12px; color: #888; }
        .additional-files { padding: 12px 18px; background: #fff8e7; border-top: 1px solid #f0e0c0; }
        .additional-files-header { font-size: 12px; color: #b37f29; font-weight: 600; margin-bottom: 8px; }
        .mini-files { display: flex; gap: 8px; flex-wrap: wrap; }
        .mini-file { background: white; border: 1px solid #e0d5c0; border-radius: 4px; padding: 5px 10px; font-size: 12px; display: flex; align-items: center; gap: 6px; cursor: pointer; }
        .mini-file:hover { background: #335b70; color: white; border-color: #335b70; }
        .mini-file.active { background: #b37f29; color: white; border-color: #b37f29; }
        .mini-file .dot { width: 8px; height: 8px; border-radius: 50%; }
        .mini-file .dot.pdf { background: #e74c3c; }
        .mini-file .dot.ppt { background: #d35400; }
        .mini-file .dot.img { background: #27ae60; }
        .mini-file:hover .dot, .mini-file.active .dot { background: white; }
        .details-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0f0f0; }
        .details-row:last-child { border-bottom: none; }
        .details-row .label { color: #888; font-size: 13px; }
        .details-row .value { font-weight: 600; color: #184163; text-align: right; }
        .details-row.highlight { background: #f2f2f2; margin: 8px -18px 0; padding: 12px 18px; }
        .details-row.highlight .value { color: #b37f29; font-size: 18px; }
        .shipping-method { background: #f8f8f8; padding: 12px; border-radius: 6px; margin-bottom: 15px; display: flex; align-items: center; gap: 12px; }
        .shipping-icon { width: 40px; height: 40px; background: #335b70; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; }
        .shipping-method-info .method { font-weight: 600; color: #184163; }
        .shipping-method-info .carrier { font-size: 12px; color: #888; }
        .delivery-estimate { background: linear-gradient(135deg, #003366 0%, #184163 100%); color: white; padding: 20px; border-radius: 8px; text-align: center; }
        .delivery-estimate .label { font-size: 12px; opacity: 0.8; margin-bottom: 5px; }
        .delivery-estimate .date { font-size: 22px; font-weight: 700; color: white; }
        .delivery-estimate .time { font-size: 13px; opacity: 0.9; margin-top: 5px; }
        .pickup-notice { background: #e8f4fd; border: 1px solid #335b70; border-radius: 6px; padding: 12px; margin-top: 12px; font-size: 12px; color: #184163; }
        .pickup-notice strong { display: block; margin-bottom: 4px; }
        .info-columns { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .info-column h4 { color: #003366; font-size: 14px; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 2px solid #b37f29; }
        .info-column .name { font-weight: 600; color: #184163; margin-bottom: 5px; }
        .info-column .address { font-size: 13px; color: #666; line-height: 1.5; margin-bottom: 10px; }
        .info-column .contact { font-size: 12px; color: #888; }
        .payment-shipping-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee; }
        .payment-shipping-item .label { font-size: 11px; color: #888; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 3px; }
        .payment-shipping-item .value { font-weight: 600; color: #184163; font-size: 13px; }
        .support-card { grid-column: span 2; }
        .support-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; }
        .support-item { background: #f8f8f8; padding: 15px; border-radius: 6px; text-align: center; text-decoration: none; color: inherit; }
        .support-item:hover { background: #003366; color: white; }
        .support-item:hover .support-icon { background: #b37f29; }
        .support-icon { width: 40px; height: 40px; background: #335b70; color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-size: 18px; }
        .support-item .title { font-weight: 600; font-size: 14px; margin-bottom: 3px; }
        .support-item .desc { font-size: 12px; opacity: 0.7; }
        .footer { background: #003366; color: rgba(255,255,255,0.8); padding: 15px 30px; font-size: 12px; display: flex; justify-content: space-between; }
        .footer .brand { color: white; font-weight: 600; }
        .no-files { text-align: center; padding: 50px; color: #888; }
        .no-files .icon { font-size: 48px; margin-bottom: 15px; }
        @media (max-width: 1200px) { .main-grid { grid-template-columns: 1fr; } .preview-card, .support-card { grid-column: 1; grid-row: auto; } }
        @media (max-width: 768px) { .status-bar { flex-direction: column; gap: 15px; text-align: center; } .info-columns, .payment-shipping-row { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
<div class="dashboard">
    <nav class="top-nav"><div class="logo">PosterPresentations.com</div></nav>
    <div class="status-bar">
        <div class="status-left">
            <div class="status-icon">✓</div>
            <div class="status-text">
                <h1>Order Confirmed</h1>
                <div class="thank-you" style="font-size: 18px;">Thank you for your order, <?php echo htmlspecialchars($customer_name); ?>!</div>
                <p><?php echo $assurance_proof_requested ? "Awaiting your proof approval" : "Your poster is being prepared for production"; ?></p>
            </div>
        </div>
        <a href="javascript:void(0);" onclick="if(window.sidebar && window.sidebar.addPanel){window.sidebar.addPanel(document.title,window.location.href,'');}else if(window.external && ('AddFavorite' in window.external)){window.external.AddFavorite(location.href,document.title);}else{alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Cmd' : 'Ctrl') + '+D to bookmark this page.');}" style="background: rgba(255,255,255,0.1); padding: 10px 15px; border-radius: 6px; color: white; text-decoration: none; display: flex; align-items: center; gap: 8px; margin-right: 10px;" title="Bookmark this page"><span style="font-size: 20px;">🔖</span><span style="font-size: 12px;">Bookmark</span></a>
        <div class="order-id">
            <div class="number">#<?php echo htmlspecialchars($order_number); ?></div>
            <div class="date"><?php echo htmlspecialchars($order_date); ?></div>
        </div>
    </div>
    <div class="main-grid">
        <div class="card preview-card">
            <div class="card-header">Uploaded File Preview</div>
            <div class="preview-area" id="preview-area">
                <?php if (empty($files)): ?>
                <div class="no-files"><div class="icon">📄</div><div>No files uploaded</div></div>
                <?php else: ?>
                <canvas id="pdf-canvas"></canvas>
                <?php endif; ?>
            </div>
            <?php if (!empty($files)): ?>
            <div class="file-toolbar">
                <span class="file-type-badge" id="file-type-badge"><?php echo strtoupper(pathinfo($files[0]['name'], PATHINFO_EXTENSION)); ?></span>
                <div class="file-details">
                    <div class="name" id="file-name"><?php echo htmlspecialchars($files[0]['name']); ?></div>
                    <div class="meta" id="file-meta"><?php echo formatFileSize($files[0]['size']); ?></div>
                </div>
            </div>
            <?php if (count($files) > 1): ?>
            <div class="additional-files">
                <div class="additional-files-header">+ <?php echo count($files); ?> Files (click to preview)</div>
                <div class="mini-files">
                    <?php foreach ($files as $i => $f): ?>
                    <div class="mini-file <?php echo $i===0?'active':''; ?>" onclick="switchFile(<?php echo $i; ?>, this)">
                        <span class="dot <?php echo getFileType($f['name']); ?>"></span><?php echo htmlspecialchars($f['name']); ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; endif; ?>
        </div>
        <div class="card">
            <div class="card-header">Order Details</div>
            <div class="card-body">
                <div class="details-row"><span class="label">Product</span><span class="value"><?php echo $product_name; ?></span></div>
                <div class="details-row"><span class="label">Poster Material</span><span class="value"><?php echo $poster_material; ?></span></div>
                <div class="details-row"><span class="label">Ordered Size</span><span class="value"><?php echo $poster_size; ?></span></div>
                <?php if ($assurance_proof_provided): ?><div class="details-row"><span class="label">Assurance Proof</span><span class="value"><?php echo htmlspecialchars($assurance_proof); ?></span></div><?php endif; ?>
                <div class="details-row"><span class="label">Quantity</span><span class="value"><?php echo $quantity; ?></span></div>
                <div class="details-row highlight"><span class="label">Total</span><span class="value">$<?php echo htmlspecialchars($order_total); ?></span></div>
            </div>
        </div>
        <div class="card">
            <div class="card-header">Shipping Schedule</div>
            <div class="card-body">
                <?php if (!$is_conference): ?>
                <div class="shipping-method">
                    <div class="shipping-icon"><?php echo $is_pickup ? '📍' : '🚚'; ?></div>
                    <div class="shipping-method-info">
                        <div class="method"><?php echo htmlspecialchars($shipping_method_name); ?></div>
                        <div class="carrier"><?php echo $is_pickup ? 'Berkeley Location' : 'FedEx'; ?></div>
                    </div>
                </div>
                <?php endif; ?>
                <?php if ($is_conference): ?>
                <div class="delivery-estimate" style="background: linear-gradient(135deg, #b37f29 0%, #8b5a1e 100%);">
                    <div class="label" style="font-size: 18px; font-weight: 600;">Conference Pickup</div>
                    
                    <div class="time" style="font-size: 14px; line-height: 1.4;"><?php echo htmlspecialchars($conference_message); ?></div>
                </div>
                <?php elseif ($is_pickup): ?>
                <div class="delivery-estimate">
                    <div class="label">Scheduled Pickup Availability</div>
                    <div class="date"><?php echo $pickup_display; ?><?php echo $assurance_proof_requested ? "*" : ""; ?></div>
                    <div class="time">by 4:30 PM</div>
                </div>
                <div class="pickup-notice"><strong>📍 Berkeley Pickup Location</strong>2117 Fourth Street, STE C, Berkeley, CA 94710<br>Please pick up by 4:30 PM, Monday–Friday</div>
                <?php if ($assurance_proof_requested): ?>
                <div style="background:#d65846;border:1px solid #b84a3c;border-radius:6px;padding:12px;margin-top:12px;font-size:12px;color:white;"><strong style="display:block;margin-bottom:4px;">⚠️ Proof Approval Required</strong>*Your order requires that we send you a proof. Please review and approve it to begin production. The estimated completion date above is valid only if the proof is approved before noon (Pacific Time).</div>
                <?php endif; ?>
                <?php else: ?>
                <div class="delivery-estimate">
                    <div class="label">Expected Delivery</div>
                    <div class="date"><?php echo $delivery_display ?: "Calculating..."; ?><?php echo $assurance_proof_requested ? "*" : ""; ?></div>
                    <div class="time"><?php echo $delivery_time_display; ?></div>
                </div>
                <?php if ($assurance_proof_requested): ?>
                <div style="background:#d65846;border:1px solid #b84a3c;border-radius:6px;padding:12px;margin-top:12px;font-size:12px;color:white;"><strong style="display:block;margin-bottom:4px;">⚠️ Proof Approval Required</strong>*Your order requires that we send you a proof. Please review and approve it to begin production. The estimated delivery date above is valid only if the proof is approved before noon (Pacific Time).</div>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <div class="card">
            <div class="card-header">Customer Information</div>
            <div class="card-body">
                <div class="info-columns">
                    <div class="info-column">
                        <?php if ($is_conference): ?>
                        <h4>Ship To Conference</h4>
                        <div class="name"><?php echo htmlspecialchars($ship_to_name); ?></div>
                        <?php elseif ($is_pickup): ?>
                        <h4>Pickup</h4>
                        <div class="name"><?php echo htmlspecialchars($ship_to_name); ?></div>
                        <?php else: ?>
                        <h4>Ship To</h4>
                        <div class="name"><?php echo htmlspecialchars($ship_to_name); ?></div>
                        <div class="address"><?php echo htmlspecialchars($ship_to_street); ?><br><?php echo htmlspecialchars($ship_to_city); ?>, <?php echo htmlspecialchars($ship_to_state); ?> <?php echo htmlspecialchars($ship_to_postal); ?><br><?php echo htmlspecialchars($ship_to_country); ?></div>
                        <?php if ($ship_to_phone): ?><div class="contact">Phone: <?php echo htmlspecialchars($ship_to_phone); ?></div><?php endif; ?>
                        <?php endif; ?>
                    </div>
                    <div class="info-column">
                        <h4>Billing Info</h4>
                        <div class="name"><?php echo htmlspecialchars($bill_to_name); ?></div>
                        <div class="address"><?php echo htmlspecialchars($bill_to_street); ?><br><?php echo htmlspecialchars($bill_to_city); ?>, <?php echo htmlspecialchars($bill_to_state); ?> <?php echo htmlspecialchars($bill_to_postal); ?><br><?php echo htmlspecialchars($bill_to_country); ?></div>
                        <?php if ($bill_to_phone): ?><div class="contact">Phone: <?php echo htmlspecialchars($bill_to_phone); ?></div><?php endif; ?>
                    </div>
                </div>
                <div class="payment-shipping-row">
                    <?php if (!$is_conference && !$is_pickup): ?><div class="payment-shipping-item"><div class="label">Shipping Method</div><div class="value"><?php echo htmlspecialchars($shipping_method_name); ?></div></div><?php endif; ?>
                    <div class="payment-shipping-item"><div class="label">Payment Method</div><div class="value"><?php echo htmlspecialchars($payment_method); ?></div></div>
                </div>
                <div style="margin-top:12px;font-size:12px;"><span style="color:#888;">Email:</span> <a href="mailto:<?php echo htmlspecialchars($customer_email); ?>" style="color:#003366;"><?php echo htmlspecialchars($customer_email); ?></a></div>
            </div>
        </div>
        <div class="card support-card">
            <div class="card-header">Resources</div>
            <div class="card-body">
                <div class="support-grid">
                    <a href="https://virtual.posterpresentations.com" target="_blank" class="support-item" style="background: linear-gradient(135deg, #003366 0%, #184163 100%); color: white;"><div class="support-icon" style="background: transparent;"><img src="http://Posterpresentations.com/qrcodeemoji.png" style="width:40px;height:40px;"></div><div class="title" style="color: white;">FREE Virtual Poster with this order</div><div class="desc" style="color: rgba(255,255,255,0.85);">Add video, audio & QR code to your poster</div></a>
                    <a href="mailto:production@posterpresentations.com" class="support-item"><div class="support-icon">✉</div><div class="title">Need Something Changed?</div><div class="desc">production@posterpresentations.com</div></a>
                    <a href="tel:+15106493001" class="support-item"><div class="support-icon">☎</div><div class="title">Call Us</div><div class="desc">510-649-3001</div></a>
                </div>
            </div>
        </div>
    </div>
    <footer class="footer"><div>© <?php echo date('Y'); ?> <span class="brand">PosterPresentations.com</span> • Canterbury Media Services, Inc.</div><div>2117 Fourth Street, STE C, Berkeley, CA 94710</div></footer>
</div>
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
const files = <?php echo $files_json; ?>;
async function renderPDF(url) {
    const area = document.getElementById('preview-area');
    try {
        const pdf = await pdfjsLib.getDocument(url).promise;
        const page = await pdf.getPage(1);
        const canvas = document.createElement('canvas');
        canvas.id = 'pdf-canvas';
        area.innerHTML = '';
        area.appendChild(canvas);
        const ctx = canvas.getContext('2d');
        const vp = page.getViewport({scale: 1});
        const scale = Math.min(600/vp.width, 600/vp.height);
        const svp = page.getViewport({scale});
        canvas.width = svp.width;
        canvas.height = svp.height;
        await page.render({canvasContext: ctx, viewport: svp}).promise;
    } catch(e) { area.innerHTML = '<div class="no-files"><div class="icon">📄</div><div>Preview unavailable</div></div>'; }
}
function renderImage(url) {
    const area = document.getElementById('preview-area');
    const img = new Image();
    img.onload = () => { area.innerHTML = ''; area.appendChild(img); };
    img.onerror = () => { area.innerHTML = '<div class="no-files"><div class="icon">🖼️</div><div>Preview unavailable</div></div>'; };
    img.src = url;
    img.style.maxWidth = '100%';
    img.style.maxHeight = '600px';
    img.style.boxShadow = '0 2px 15px rgba(0,0,0,0.1)';
}
function showPlaceholder(type, name) {
    const area = document.getElementById('preview-area');
    const colors = {ppt: '#d35400', unknown: '#7f8c8d'};
    const ext = name.split('.').pop().toUpperCase();
    area.innerHTML = '<div style="text-align:center;padding:50px;"><div style="width:120px;height:150px;background:'+(colors[type]||colors.unknown)+';border-radius:12px;display:flex;align-items:center;justify-content:center;margin:0 auto 20px;color:white;font-weight:bold;font-size:24px;">'+ext+'</div><div style="color:#184163;font-weight:600;">File Uploaded</div><div style="color:#888;font-size:13px;margin-top:5px;">Preview not available</div></div>';
}
function switchFile(i, el) {
    const f = files[i];
    document.querySelectorAll('.mini-file').forEach(e => e.classList.remove('active'));
    el.classList.add('active');
    document.getElementById('file-name').textContent = f.name;
    document.getElementById('file-meta').textContent = f.size;
    const badge = document.getElementById('file-type-badge');
    badge.textContent = f.name.split('.').pop().toUpperCase();
    badge.className = 'file-type-badge ' + f.type;
    if (f.type === 'pdf') renderPDF(f.url);
    else if (f.type === 'img') renderImage(f.url);
    else showPlaceholder(f.type, f.name);
}
document.addEventListener('DOMContentLoaded', () => {
    if (files.length > 0) {
        const f = files[0];
        if (f.type === 'pdf') renderPDF(f.url);
        else if (f.type === 'img') renderImage(f.url);
        else showPlaceholder(f.type, f.name);
    }
});
</script>
</body>
</html>
