<?php
// view.php
// (Veritabanı bağlantısı)
require_once "db.php"; // veya kendi PDO bağlantı dosyan

$token = $_GET['token'] ?? '';

$stmt = $pdo->prepare("SELECT * FROM offers WHERE token = ?");
$stmt->execute([$token]);
$offer = $stmt->fetch();

if (!$token) {
    die("Invalid link");
}

// ✅ 15 günlük süre kontrolü
$createdAt = new DateTime($offer['created_at']);
$now = new DateTime();

$diff = $createdAt->diff($now)->days;

if ($diff > 6) {
    die("This offer has expired.");
}



$createdAt = new DateTime($offer['created_at']);
$expireAt = clone $createdAt;
$expireAt->modify('+7 days');

// Formatlı gösterim
echo '<span id="offer-expire-date" style="display:none;">' . $expireAt->format('Y-m-d H:i:s') . '</span>';


$stmt = $pdo->prepare("SELECT * FROM offers WHERE token = ?");
$stmt->execute([$token]);
$offer = $stmt->fetch();

if (!$offer) {
    die("Offer not found or expired.");
}

require_once 'v.php'; // Telegram fonksiyonları

$ip = $_SERVER['REMOTE_ADDR'];
$country = 'Bilinmiyor';

// Ülke bilgisini ip-api.com üzerinden al
$geoResponse = @file_get_contents("http://ip-api.com/json/{$ip}?fields=country");
if ($geoResponse !== false) {
    $geoData = json_decode($geoResponse, true);
    if (isset($geoData['country'])) {
        $country = $geoData['country'];
    }
}

$link = "https://offer.hosfinder.com/view.php?token=$token";
$zaman = date('Y-m-d H:i:s');
$created_by = $offer['created_by'] ?? 'bilinmiyor';
$operations = json_decode($offer['operation_titles'] ?? '[]', true);
$operationList = is_array($operations) ? implode(", ", $operations) : 'Yok';
$assigned_to = $offer['assigned_to'] ?? '';
$created_by = $offer['created_by'] ?? 'bilinmiyor';
$yetkili = $assigned_to ?: $created_by; // Boşsa created_by kullan




// View sayısı + son görüntüleme zamanını güncelle
$update = $pdo->prepare("UPDATE offers SET 
    view_count = view_count + 1,
    last_viewed_at = NOW()
    WHERE token = ?");
$update->execute([$token]);

// JSON verileri parse ediliyor
$operationTitles = json_decode($offer['operation_titles'] ?? '[]', true);
$operationPrices = json_decode($offer['operation_prices'] ?? '[]', true);
$operationDiscounts = json_decode($offer['operation_discounts'] ?? '[]', true);

// 1. Subtotal'ı hesapla (sadece operasyon fiyatları, indirimsiz)
$subtotal = 0;
foreach ($operationPrices as $price) {
    $price = (float) str_replace(['€', '.', ','], ['', '', '.'], $price);
    $subtotal += $price;
}

// 2. Avrupa formatında yazdırılacak subtotal
$formattedSubtotal = '€' . number_format($subtotal, 2, ',', '.');
$manualDiscount = (float) $offer['manual_discount'] ?? 0;
// total_text temizleniyor: € işareti, nokta ve virgül kaldırılıyor
$totalText = str_replace(['€', '.', ','], ['', '', '.'], $offer['total_text'] ?? '0');

// float’a dönüştür
$totalFloat = (float) $totalText;

// KDV %10 dahilse ayıklama: net fiyat = toplam / 1.1, vergi = fark
$tax = $totalFloat / 1.1 * 0.1;
$grandTotal = (float) $offer['total_text'];
$specialtotal = $grandTotal - $manualDiscount;


// Eğer JSON'dan gelen işlemler üzerinden indirim hesaplanıyorsa:
$operationPrices = json_decode($offer['operation_prices'] ?? '[]', true);
$operationDiscounts = json_decode($offer['operation_discounts'] ?? '[]', true);
$discountTotal = 0;
for ($i = 0; $i < count($operationPrices); $i++) {
    $price = (float) str_replace(['.', ','], ['', '.'], $operationPrices[$i]);
    $discountPercent = (float) rtrim($operationDiscounts[$i], '%');
    if ($discountPercent > 0) {
        $discountTotal += $price * ($discountPercent / 100);
    }
}

// Ek hizmetler
$implantPrice = (float) $offer['implant_price'];
$transferPrice = (float) $offer['transfer_price'];
$accommodationPrice = (float) $offer['accommodation_price'];
$bloodPrice = (float) $offer['blood_price'];

$additional = $implantPrice + $transferPrice + $accommodationPrice + $bloodPrice;

// 1. Normal ve indirimli toplamı hesapla
$originalTotal = 0;
$discountedTotal = 0;

for ($i = 0; $i < count($operationPrices); $i++) {
    $price = (float) str_replace(['.', ','], ['', '.'], $operationPrices[$i]);
    $discountPercent = (float) rtrim($operationDiscounts[$i], '%');

    $originalTotal += $price;
    $discountedTotal += $price * (1 - $discountPercent / 100);
}

$rawStatus = $offer['health_status'] ?? 'Normal Patient';

// Veritabanındaki değerleri switch uyumlu hale getir
switch (trim($rawStatus)) {
    case 'HBV/HCV Positive':
        $multiplier = 1.5;
        $healthStatus = 'HBV/HCV Positive';
        break;
    case 'HIV Positive':
        $multiplier = 2.0;
        $healthStatus = 'HIV Positive';
        break;
    default:
        $multiplier = 1.0;
        $healthStatus = 'Normal';
        break;
}

// 3. Farklar
$adjustedTotal = $originalTotal * $multiplier;
$diff = $adjustedTotal - $originalTotal; // İndirimsiz fark
$discountRatio = $originalTotal > 0 ? ($discountedTotal / $originalTotal) : 0;
$adjustedDiff = $diff * $discountRatio; // İndirimli fark

function parseFloatSmart($val) {
    $val = trim(str_replace(['€', ' ', "\xc2\xa0"], '', $val));

    // Sayının hem ',' hem '.' içerip içermediğini kontrol et
    $commaCount = substr_count($val, ',');
    $dotCount = substr_count($val, '.');

    if ($commaCount > 0 && $dotCount > 0) {
        // Avrupa formatı: 3.300,50
        $val = str_replace('.', '', $val);     // binlik nokta sil
        $val = str_replace(',', '.', $val);    // ondalık virgül → nokta
    } elseif ($commaCount > 0 && $dotCount === 0) {
        // 3,300 → 3300 (Avrupa binlik sanılıyorsa düzelt)
        // ama aslında 3.3 olabilir — yani , ondalık olabilir
        // karar: 3,30 → ondalık; 3,300 → binlik
        $commaPos = strrpos($val, ',');
        $decimals = strlen(substr($val, $commaPos + 1));
        if ($decimals === 3) {
            // büyük ihtimal binlik ayırıcı olarak kullanılmış
            $val = str_replace(',', '', $val);
        } else {
            // 3,30 → 3.30
            $val = str_replace(',', '.', $val);
        }
    } elseif ($dotCount > 0 && $commaCount === 0) {
        // Amerikan formatı → doğrudan kullanılabilir
        // Ama yine de € karakterleri silindiği için float'a hazır
    }

    return (float) $val;
}
// Telegram'a detaylı log gönder
sendTelegramMessage("
👁️ <b>Teklif Görüntülendi</b>
🔗 <b>Link:</b> <a href='$link'>$link</a>
👤 <b>Yetkili:</b> $yetkili
🕒 <b>Zaman:</b> $zaman
🌐 <b>IP:</b> $ip
🏳️ <b>Ülke:</b> $country
💉 <b>Operasyonlar:</b> $operationList
💶 <b>Toplam Fiyat:</b> $totalText
");

?>

<!DOCTYPE html>
<html class="no-js" lang="en">

<head>
    <!-- Meta Tags -->
    <?php $base = "pages/"; ?>
    <?php $bases = "assets/"; ?>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="author" content="Hosfinder" />
    <!-- WhatsApp / Facebook / LinkedIn için -->
<meta property="og:title" content="<?= htmlspecialchars($patient_name) ?> - Your Personalized Offer from Hosfinder">
<meta property="og:description" content="Get your custom medical treatment plan with transparent pricing.">
<meta property="og:image" content="https://offer.hosfinder.com/assets/preview.jpg">
<meta property="og:url" content="https://offer.hosfinder.com/view.php?token=<?= htmlspecialchars($token) ?>">
<meta property="og:type" content="website">

    <link rel="shortcut icon" href="<?= $bases ?>fav.svg"
        type="image/x-icon" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />

    <!-- Site Title -->
    <title>
        <?= strtoupper(htmlspecialchars($offer['patient_name'] . ' Invoice - ' . $offer['created_at'])) ?>
    </title>

    <link rel="stylesheet"
        href="<?= $base ?>/assets/css/style.css" />
    <style>
             #tm_download_sections {
              width: 100%;
  max-width: 794px;
            /* A4 genişliği */
            height: auto;
            /* yüksekliği kısıtlama */
            max-height: fit-content;
            /* A4 yüksekliği */
            overflow: hidden;
            box-sizing: border-box;
            font-size: 12px;
        }

        @media print {
            body {
                zoom: 0.75;
                /* PDF'e daha iyi sığması için */
            }
        }
        .tm_grid_row.tm_col_3 {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: flex-start;
  gap: 10px;
}

/* Her kutunun eşit genişlikte olmasını sağla */
.tm_grid_row.tm_col_3 .tm_text_center {
  flex: 1;
  text-align: center;
}

/* Küçük ekranlar için sığmazsa fontu küçült */
@media (max-width: 480px) {
  .tm_grid_row.tm_col_3 .tm_text_center {
    font-size: 12px;
    padding: 5px;
  }
  .tm_grid_row.tm_col_3 svg {
    width: 18px;
    height: 18px;
  }
}

        .countdown-wrapper {
            text-align: center;

            border-radius: 16px;


            font-family: 'Segoe UI', sans-serif;
        }

        .countdown-label {
            font-size: 1.1rem;
            font-weight: 600;
            color: #0077b6;
            margin-bottom: 10px;
        }

        .countdown-box {
            font-size: 1.8rem;
            font-weight: bold;
            background-color: #ffffff;
            color: #1d3557;
            border-radius: 12px;
            display: inline-block;
            padding: 10px 20px;
            box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.1);
            letter-spacing: 1px;
            transition: all 0.3s ease;
        }

        .countdown-cta {
            font-size: 0.95rem;
            margin-top: 10px;
            color: #ff4d4d;
            font-weight: 500;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 12px;
        }

        .tm_table th,
        .tm_table td,
        .tm_invoice_footer,
        .tm_invoice_info,
        .tm_invoice_head,
        .tm_invoice_in {
            font-size: 12px;
        }
    </style>
</head>

<body>



    <div class="tm_container">
        <div class="tm_invoice_wrap">
            <div class="tm_invoice tm_style2 tm_type1 tm_accent_border tm_radius_0 tm_small_border"
                id="tm_download_sections">
                <div class="tm_invoice_in">
                    <div class="tm_invoice_head tm_mb20 tm_m0_md">
                        <div class="tm_invoice_left">
                            <div class="tm_logo">
                                <img src="<?= $base ?>/assets/img/hosfinder.png"
                                    alt="Logo" style="
    margin-left: -10%;opacity: 80%; height: auto;
" />
                            </div>
                        </div>
                        <div class="tm_invoice_right">
                            <div class="tm_grid_row tm_col_3">
                                <div class="tm_text_center">
                                    <p class="tm_accent_color tm_mb0">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                            viewBox="0 0 512 512" fill="currentColor">
                                            <path
                                                d="M424 80H88a56.06 56.06 0 00-56 56v240a56.06 56.06 0 0056 56h336a56.06 56.06 0 0056-56V136a56.06 56.06 0 00-56-56zm-14.18 92.63l-144 112a16 16 0 01-19.64 0l-144-112a16 16 0 1119.64-25.26L256 251.73l134.18-104.36a16 16 0 0119.64 25.26z" />
                                        </svg>
                                    </p>
                                    <?= htmlspecialchars($offer['user_email']) ?>


                                </div>
                                <div class="tm_text_center">
                                    <p class="tm_accent_color tm_mb0">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                            viewBox="0 0 512 512" fill="currentColor">
                                            <path
                                                d="M391 480c-19.52 0-46.94-7.06-88-30-49.93-28-88.55-53.85-138.21-103.38C116.91 298.77 93.61 267.79 61 208.45c-36.84-67-30.56-102.12-23.54-117.13C45.82 73.38 58.16 62.65 74.11 52a176.3 176.3 0 0128.64-15.2c1-.43 1.93-.84 2.76-1.21 4.95-2.23 12.45-5.6 21.95-2 6.34 2.38 12 7.25 20.86 16 18.17 17.92 43 57.83 52.16 77.43 6.15 13.21 10.22 21.93 10.23 31.71 0 11.45-5.76 20.28-12.75 29.81-1.31 1.79-2.61 3.5-3.87 5.16-7.61 10-9.28 12.89-8.18 18.05 2.23 10.37 18.86 41.24 46.19 68.51s57.31 42.85 67.72 45.07c5.38 1.15 8.33-.59 18.65-8.47 1.48-1.13 3-2.3 4.59-3.47 10.66-7.93 19.08-13.54 30.26-13.54h.06c9.73 0 18.06 4.22 31.86 11.18 18 9.08 59.11 33.59 77.14 51.78 8.77 8.84 13.66 14.48 16.05 20.81 3.6 9.53.21 17-2 22-.37.83-.78 1.74-1.21 2.75a176.49 176.49 0 01-15.29 28.58c-10.63 15.9-21.4 28.21-39.38 36.58A67.42 67.42 0 01391 480z" />
                                        </svg>
                                    </p>
                                    <?= htmlspecialchars($offer['user_phone']) ?>

                                </div>
                                <div class="tm_text_center">
                                    <p class="tm_accent_color tm_mb0">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                            viewBox="0 0 512 512" fill="currentColor">
                                            <circle cx="256" cy="192" r="32" />
                                            <path
                                                d="M256 32c-88.22 0-160 68.65-160 153 0 40.17 18.31 93.59 54.42 158.78 29 52.34 62.55 99.67 80 123.22a31.75 31.75 0 0051.22 0c17.42-23.55 51-70.88 80-123.22C397.69 278.61 416 225.19 416 185c0-84.35-71.78-153-160-153zm0 224a64 64 0 1164-64 64.07 64.07 0 01-64 64z" />
                                        </svg>
                                    </p>
                                    <?= htmlspecialchars($offer['user_adres']) ?>

                                </div>
                            </div>
                        </div>
                        <div class="tm_shape_bg tm_accent_bg_10 tm_border tm_accent_border_20"></div>
                    </div>
                    <div class="tm_invoice_info tm_mb30 tm_align_center">
                        <div class="tm_invoice_info_left tm_mb20_md">
                            <p class="tm_mb0">
                                <b class="tm_primary_color">Offer No:
                                    #<?= htmlspecialchars($offer['invoice_number']) ?>
                                </b>

                                <br />
                                <b class="tm_primary_color">Offer Date:
                                </b><?= htmlspecialchars($offer['created_at']) ?>
                            </p>
                        </div>
                        <div class="tm_invoice_info_right">
                            <div
                                class="tm_border tm_accent_border_20 tm_radius_0 tm_accent_bg_10 tm_curve_35 tm_text_center">
                                <div>
                                    <b class="tm_accent_color tm_f26 tm_medium tm_body_lineheight">Total:
                                        <?php
$totalText = parseFloatSmart($offer['total_text'] ?? '0');
$manualDiscount = parseFloatSmart($offer['manual_discount'] ?? '0');
$specialTotal = max(0, $totalText - $manualDiscount);


echo "Total: €" . number_format($specialTotal, 2, ',', '.');

?>

                                    </b>
                                </div>
                            </div>
                        </div>
                    </div>
                    <p>Dear
                        <strong><?= htmlspecialchars($offer['patient_name']) ?></strong>,
                        <br>
                        After a comprehensive evaluation of your consultation details and the images you provided, our
                        experienced surgeon and medical team have thoroughly assessed the current shape and projection
                        of your case.
                        <br><br>
                        We are confident in moving forward with a customized combination of procedures specifically
                        designed to deliver the most refined and natural results — aligned precisely with your goals and
                        expectations.
                        <br><br>
                        Your satisfaction and comfort remain our top priority, and we are fully committed to supporting
                        you at every stage of your journey with us.
                        <br><br>
                        Warm regards
                    </p>
                    <h2 class="tm_f16 tm_section_heading tm_accent_border_20 tm_mb0">
                        <span
                            class="tm_accent_bg_10 tm_radius_0 tm_curve_35 tm_border tm_accent_border_20 tm_border_bottom_0 tm_accent_color"><span>Offer
                                to:</span></span>
                    </h2>
                    <div class="tm_table tm_style1 tm_mb30">
                        <div class="tm_border tm_accent_border_20 tm_border_top_0">
                            <div class="tm_table_responsive">
                                <table>
                                    <tbody>
                                        <tr>
                                            <td class="tm_width_6 tm_border_top_0">
                                                <b class="tm_primary_color tm_medium">Name:
                                                </b>
                                                <?= htmlspecialchars($offer['patient_name']) ?>
                                            </td>
                                            <td class="tm_width_6 tm_border_top_0 tm_border_left tm_accent_border_20">
                                                <b class="tm_primary_color tm_medium">Phone: </b>
                                                <?= htmlspecialchars($offer['patient_phone']) ?>
                                            </td>
                                        </tr>

                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="tm_table tm_style1">
                        <div class="tm_border tm_accent_border_20">
                            <div class="tm_table_responsive">
                                <table>
                                    <thead>
                                        <tr>
                                            <th class="tm_width_3 tm_semi_bold tm_accent_color tm_accent_bg_10">
                                                Operation</th>
                                            <th class="tm_width_4 tm_semi_bold tm_accent_color tm_accent_bg_10">
                                                Description</th>
                                            <th class="tm_width_2 tm_semi_bold tm_accent_color tm_accent_bg_10">Price
                                            </th>
                                            <th
                                                class="tm_width_2 tm_semi_bold tm_accent_color tm_accent_bg_10 tm_text_right">
                                                Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php for ($i = 0; $i < count($operationTitles); $i++):
                                            $title = ucwords(strtolower($operationTitles[$i]));
                                            $priceRaw = $operationPrices[$i];
                                            $discountRaw = $operationDiscounts[$i];

                                            $price = (float) str_replace(['.', ','], ['', '.'], $priceRaw);
                                            $discountPercent = (float) rtrim($discountRaw, '%');
                                            $discountedPrice = $price * (1 - $discountPercent / 100);
                                            ?>
                                        <tr>
                                            <td><?= htmlspecialchars($title) ?>
                                            </td>
                                            <td><?= htmlspecialchars($discountRaw) ?>
                                                discount</td>
                                            <td>€<?= number_format($price, 2, ',', '.') ?>
                                            </td>
                                            <td style="text-align: right;">
                                                €<?= number_format($discountedPrice, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endfor; ?>

                                        <?php if ($implantPrice > 0): ?>
                                        <tr>
                                            <td>Implant</td>
                                            <td>Included ✅</td>
                                            <td>€<?= number_format($implantPrice, 2, ',', '.') ?>
                                            </td>
                                            <td style="text-align: right;">
                                                €<?= number_format($implantPrice, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endif; ?>

                                        <?php if ($accommodationPrice > 0): ?>
                                        <tr>
                                            <td>Accommodation</td>
                                            <td><?= htmlspecialchars($offer['accommodation_text']) ?>
                                            </td>
                                            <td>€<?= number_format($accommodationPrice, 2, ',', '.') ?>
                                            </td>
                                            <td style="text-align: right;">
                                                €<?= number_format($accommodationPrice, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endif; ?>

                                        <?php if ($transferPrice > 0): ?>
                                        <tr>
                                            <td>Transfer</td>
                                            <td>City/Airport Transfers</td>
                                            <td>€<?= number_format($transferPrice, 2, ',', '.') ?>
                                            </td>
                                            <td style="text-align: right;">
                                                €<?= number_format($transferPrice, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endif; ?>

                                        <?php if ($bloodPrice > 0): ?>
                                        <tr>
                                            <td>Extra Blood</td>
                                            <td>Blood Units</td>
                                            <td>€<?= number_format($bloodPrice, 2, ',', '.') ?>
                                            </td>
                                            <td style="text-align: right;">
                                                €<?= number_format($bloodPrice, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endif; ?>

                                        <!-- 4. Tabloya yazdır -->
                                        <?php if ($multiplier > 1): ?>
                                        <tr style="background-color:#fff3cd;">
                                            <td><strong>Health Status</strong></td>
                                            <td><?= htmlspecialchars($healthStatus) ?>
                                            </td>

                                            <td class="text-end text-warning" style="text-decoration: line-through;">
                                                €<?= number_format($diff, 2, ',', '.') ?>
                                            </td>
                                            <td style="text-align: right;">
                                                €<?= number_format($adjustedDiff, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="tm_invoice_footer tm_mb15 tm_m0_md">
                            <div class="tm_left_footer" style="justify-items: center;    background-color: #e5f1ff;
    padding: 25px;
    margin-bottom: 2%;
    background-image: url('<?= $bases ?>bg.png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;">
                                <p class="tm_mb2">
                                    <b class="tm_primary_color" style="
    font-size: 18px;
    font-family: serif;
    opacity: 75%;
">Your Journey to Confidence Starts Here</b>
                                </p>
                                <p class="tm_m0" style="margin-top: 3%;">
                                    <img src="<?= $bases ?>cert.png"
                                        style="width: 95%;">
                                </p>


                                <style>
                                    .grid-top {
                                        font-size: 18px;
                                        font-weight: bold;
                                        margin-bottom: 20px;
                                        color: #333;
                                        justify-self: center;
                                    }

                                    .grid-bottom {
                                        display: flex;
                                        justify-content: center;
                                        flex-wrap: wrap;
                                        gap: 20px;
                                    }

                                    .box {
                                        background: white;
                                        border-radius: 12px;
                                        padding: 10px 9px;
                                        min-width: 90px;
                                        text-align: center;
                                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
                                        transition: 0.3s ease;
                                    }

                                    .box:hover {
                                        transform: translateY(-5px);
                                        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
                                    }

                                    .box a {
                                        text-decoration: none;
                                        color: #333;
                                        font-weight: 500;
                                        display: flex;
                                        align-items: center;
                                        justify-content: center;
                                        gap: 10px;
                                    }

                                    .box i {
                                        font-size: 20px;
                                        color: #007bff;
                                    }
                                </style>
                            </div>


                            <div class="tm_right_footer">
                                <table class="tm_mb15 tm_m0_md">
                                    <tbody>
                                        <tr>
                                            <td class="tm_width_3 tm_primary_color tm_border_none tm_medium">
                                                Subtotal
                                            </td>
                                            <td
                                                class="tm_width_3 tm_primary_color tm_text_right tm_border_none tm_medium">
                                                €<?= number_format($subtotal + $additional + $diff, 2, ',', '.') ?>
                                            </td>
                                        </tr>

                                        <?php if ($discountTotal > 0): ?>
                                        <tr>
                                            <td class="tm_width_3 tm_danger_color tm_border_none tm_pt0">
                                                Discount
                                            </td>
                                            <td class="tm_width_3 tm_danger_color tm_text_right tm_border_none tm_pt0">
                                                -€<?= number_format($discountTotal + $adjustedDiff, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endif; ?>

                                        <?php if ($manualDiscount > 0): ?>
                                        <tr>
                                            <td class="tm_width_3 tm_danger_color tm_border_none tm_pt0"
                                                style="font-weight: bold; color: #b70505;">
                                                Special Discount
                                            </td>
                                            <td class="tm_width_3 tm_danger_color tm_text_right tm_border_none tm_pt0"
                                                style="font-weight: bold; color: #b70505;">
                                                -€<?= number_format($manualDiscount, 2, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endif; ?>

                                        <tr>
                                            <td class="tm_width_3 tm_primary_color tm_border_none tm_pt0">
                                                Tax 10% <br><small class="text-muted fst-italic">Included in
                                                    price</small>
                                            </td>
                                            <td class="tm_width_3 tm_primary_color tm_text_right tm_border_none tm_pt0">
                                        <?php
                                        $totalText = parseFloatSmart($offer['total_text'] ?? '0');
                                        $manualDiscount = parseFloatSmart($offer['manual_discount'] ?? '0');
                                        
                                        $specialTotal = max(0, $totalText - $manualDiscount);
                                        $tax = $specialTotal * 0.10;
                                        
                                        echo  "€". number_format($tax, 2, ',', '.') ;
                                        ?>

                                            </td>
                                        </tr>

                                        <tr class="tm_accent_border_20 tm_border">
                                            <td class="tm_width_3 tm_bold tm_f16 tm_border_top_0 tm_accent_color tm_accent_bg_10"
                                                style="font-size: 15px;">
                                                Total Amount
                                            </td>
                                            <td class="tm_width_3 tm_bold tm_f16 tm_border_top_0 tm_accent_color tm_text_right tm_accent_bg_10"
                                                style="font-size: 20px;">
                                        <?php
$totalText = parseFloatSmart($offer['total_text'] ?? '0');
$manualDiscount = parseFloatSmart($offer['manual_discount'] ?? '0');
$specialTotal = max(0, $totalText - $manualDiscount);


echo "€" . number_format($specialTotal, 2, ',', '.');

?>

                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>

                        </div>
                        <?php
$invoiceDate = $_POST['invoiceDate'] ?? date('d.m.Y');
$endDate = date('d.m.Y', strtotime($invoiceDate . ' +15 days'));
?>

                        <style>
                            .tm_invoice_footer_grid {
                                display: grid;
                                grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                                gap: 30px;
                                align-items: start;


                            }

                            .tm_info_box {
                                font-size: 13px;
                                color: #333;
                                line-height: 1.6;
                            }

                            .tm_info_box strong {
                                color: #007bff;
                            }

                            .tm_sign {
                                text-align: center;
                            }

                            .tm_sign img {
                                max-width: 120px;
                                margin-bottom: 5px;
                            }
                        </style>

<div style="border: 1px solid #dee2e6; border-radius: 12px; padding: 24px; background-color: #f8f9fa; margin-top: 30px; font-family: Arial, sans-serif;">

  <!-- Üst kısım: sol bilgi + sağ imza -->
  <div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 20px;">
    
    <!-- Sol bilgi -->
    <div style="flex: 1; min-width: 260px;">
      <p style="font-size: 14px; margin: 0 0 6px; color: #212529;margin-top: 2%;">
        <strong style="color: #0d6efd;">Thank you for choosing us!</strong><br>
        Your discount has started on <strong><?= $invoiceDate ?></strong><br>
        and will expire on <strong><?= $endDate ?></strong>.
      </p>
    </div>

    <!-- Sağ imza -->
    <div style="text-align: center; flex-shrink: 0;">
      <img src="<?= $base ?>/assets/img/sign.png" alt="Sign" style="max-width: 100px; opacity: 0.85;" />
      <p style="margin: 6px 0 0; font-size: 13px; color: #6c757d;">
         <?= htmlspecialchars(!empty($offer['assigned_to']) ? $offer['assigned_to'] : $offer['created_by']) ?>
      </p>
      <p style="margin: 0; font-size: 14px; font-weight: bold; color: #303030;">
        Medical Consultant
      </p>
    </div>
  </div>

  <!-- Alt tam genişlik bilgi -->
  <div style="margin-top: 20px; font-size: 13px; line-height: 1.7; color: #212529;">
    <p style="margin-bottom: 8px; font-weight: bold;">
      To secure your spot and confirm your booking, please choose one of the following options:
    </p>

    <ul style="padding-left: 20px; margin: 0 0 10px;">
      <li>
        Send your <strong><a href="#" style="color: #0d6efd; text-decoration: underline;">flight ticket</a></strong> to confirm your travel plans.
      </li>
      <li>
        OR make a <strong><a href="#" style="color: #0d6efd; text-decoration: underline;">10% deposit</a></strong> based on your total package price.
      </li>
    </ul>

    <p style="color: #dc3545; font-weight: bold; margin: 0;font-size:11px;">
      ⚠ This step is required to officially reserve your place, lock the current offer, and begin preparation on our side.
    </p>
  </div>

</div>

                    </div>
                    <div class="tm_bottom_invoice tm_accent_border_20"
                        style="padding: 0px !important;margin: 0px !important;">
                        <div class="tm_bottom_invoice_left">
                            <div class="confidence-grid">
                                <div class="grid-top" style="    font-family: serif;">
                                    Let's Stay in Touch
                                </div>
                                <div class="grid-bottom">
                                    <div class="box">
                                        <a href="https://hosfinder.com" target="_blank">
                                            <i class="fas fa-globe"></i> Website
                                        </a>
                                    </div>
                                    <div class="box">
                                        <a href="https://instagram.com/hosfinder" target="_blank">
                                            <i class="fab fa-instagram"></i> Instagram
                                        </a>
                                    </div>
                                    <div class="box">
                                        <?php
$rawPhone = $phone ?? ($_SESSION['telefon'] ?? '');
$cleanPhone = ltrim($rawPhone, '+'); // Başındaki + işaretini kaldırır
?>

                                        <a href="https://wa.me/<?= htmlspecialchars($cleanPhone) ?>"
                                            target="_blank">
                                            <i class="fab fa-whatsapp"></i> WhatsApp
                                        </a>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="tm_bottom_invoice_right tm_mobile_hide">
                            <div class="tm_logo">
                                <img src="<?= $base ?>/assets/img/hosfinder.png"
                                    alt="Logo" style="
    margin-left: 10%;opacity: 80%; height: auto;
" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div id="google_translate_element" style="position: fixed; top: 10px; right: 10px; z-index: 9999;"></div>

            <div class="tm_invoice_btns tm_hide_print">

                    <button id="tm_download_btns" class="tm_invoice_btn tm_color2">
                        <span class="tm_btn_icon">
                            <svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512">
                                <path
                                    d="M320 336h76c55 0 100-21.21 100-75.6s-53-73.47-96-75.6C391.11 99.74 329 48 256 48c-69 0-113.44 45.79-128 91.2-60 5.7-112 35.88-112 98.4S70 336 136 336h56M192 400.1l64 63.9 64-63.9M256 224v224.03"
                                    fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                    stroke-width="32" />
                            </svg>
                        </span>
                        <span class="tm_btn_text">Download</span>
                    </button>
            </div>
        </div>
    </div>
    <div class="countdown-wrapper">
        <p class="countdown-label">⏳ Offer Expires In</p>
        <div class="countdown-box" id="countdown"></div>
        <p class="countdown-cta">Secure your spot before it's gone!</p>
    </div>


    <script src="<?= $base ?>/assets/js/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="<?= $base ?>/assets/js/main.js"></script>
<script>
    document.getElementById("tm_download_btns").addEventListener("click", function () {
        const element = document.getElementById("tm_download_sections");

        // Orijinal stil bilgilerini sakla
        const originalWidth = element.style.width;
        const originalZoom = document.body.style.zoom;

        // Mobilde bile masaüstü gibi görünmesi için genişliği sabitle
        element.style.width = "794px"; // A4 genişliği
        document.body.style.zoom = "1.0";

        html2canvas(element, {
            scale: 2,
            useCORS: true,
            scrollY: -window.scrollY,
            windowWidth: 794, // A4 genişliği zorlaması
            windowHeight: element.scrollHeight
        }).then((canvas) => {
            const imgData = canvas.toDataURL("image/png");
            const { jsPDF } = window.jspdf;

            const pdfWidth = 210; // A4 mm
            const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

            const pdf = new jsPDF("p", "mm", [pdfWidth, pdfHeight]);
            pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight);
            pdf.save("invoice.pdf");

            // Stil bilgilerini geri yükle
            element.style.width = originalWidth;
            document.body.style.zoom = originalZoom;
        });
    });
</script>




    <script>
        (function() {
            function c() {
                var b = a.contentDocument || a.contentWindow.document;
                if (b) {
                    var d = b.createElement("script");
                    d.innerHTML =
                        "window.__CF$cv$params={r:'944cb1ebe9a0e32d',t:'MTc0ODA4ODY4MC4wMDAwMDA='};var a=document.createElement('script');a.nonce='';a.src='../cdn-cgi/challenge-platform/h/g/scripts/jsd/6fab0cec561d/maind41d.js';document.getElementsByTagName('head')[0].appendChild(a);";
                    b.getElementsByTagName("head")[0].appendChild(d);
                }
            }
            if (document.body) {
                var a = document.createElement("iframe");
                a.height = 1;
                a.width = 1;
                a.style.position = "absolute";
                a.style.top = 0;
                a.style.left = 0;
                a.style.border = "none";
                a.style.visibility = "hidden";
                document.body.appendChild(a);
                if ("loading" !== document.readyState) c();
                else if (window.addEventListener)
                    document.addEventListener("DOMContentLoaded", c);
                else {
                    var e = document.onreadystatechange || function() {};
                    document.onreadystatechange = function(b) {
                        e(b);
                        "loading" !== document.readyState &&
                            ((document.onreadystatechange = e), c());
                    };
                }
            }
        })();
    </script>
    <script defer
        src="https://static.cloudflareinsights.com/beacon.min.js/vcd15cbe7772f49c399c6a5babf22c1241717689176015"
        integrity="sha512-ZpsOmlRQV6y907TI0dKBHq9Md29nnaEIPlkf84rnaERnq6zvWvPUqr2ft8M1aS28oN72PdrCzSjY4U6VaAw1EQ=="
        data-cf-beacon='{"rayId":"944cb1ebe9a0e32d","version":"2025.4.0-1-g37f21b1","r":1,"serverTiming":{"name":{"cfExtPri":true,"cfL4":true,"cfSpeedBrain":true,"cfCacheStatus":true}},"token":"6f756f02820545e3be40ddc6eb6154c3","b":1}'
        crossorigin="anonymous"></script>
    <script type="text/javascript">
        function googleTranslateElementInit() {
            new google.translate.TranslateElement({
                pageLanguage: 'en', // Sayfanın orijinal dili
                includedLanguages: 'en,tr,de,fr,es,it,ar,ru,pt,', // Dilediğin dilleri virgülle yaz
                layout: google.translate.TranslateElement.InlineLayout.SIMPLE
            }, 'google_translate_element');
        }
    </script>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const expireText = document.getElementById("offer-expire-date").textContent;
            const expireTime = new Date(expireText).getTime();
            const countdownEl = document.getElementById("countdown");

            function updateCountdown() {
                const now = new Date().getTime();
                const diff = expireTime - now;

                if (diff <= 0) {
                    countdownEl.innerText = "Expired";
                    countdownEl.style.color = "red";
                    return;
                }

                const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((diff % (1000 * 60)) / 1000);

                countdownEl.innerText = `${days}d ${hours}h ${minutes}m ${seconds}s`;
            }

            updateCountdown();
            setInterval(updateCountdown, 1000);
        });
    </script>

</body>

</html>