<?php
declare(strict_types=1);

ob_start();
session_start();

/* -----------------------
   Load Escrow config7.php reliably
------------------------ */
$configCandidates = [
    '/home/fvme60ccdm8r/config/config7.php',
    __DIR__ . '/../../config/config7.php',
    __DIR__ . '/../config/config7.php'
];

$configPath = null;
foreach ($configCandidates as $p) {
    if (is_readable($p)) {
        $configPath = $p;
        break;
    }
}

if (!$configPath) {
    http_response_code(500);
    echo "Server configuration error: config7.php missing or not readable. Tried: ";
    echo htmlspecialchars(implode(' | ', $configCandidates));
    exit;
}

require_once $configPath;

if (!defined('ESCROW_EMAIL') || trim((string)ESCROW_EMAIL) === '') {
    http_response_code(500);
    echo "Server configuration error: ESCROW_EMAIL is not set in config7.php.";
    exit;
}
if (!defined('ESCROW_API_KEY') || trim((string)ESCROW_API_KEY) === '') {
    http_response_code(500);
    echo "Server configuration error: ESCROW_API_KEY is not set in config7.php.";
    exit;
}

$escrow_email   = (string)ESCROW_EMAIL;
$escrow_api_key = (string)ESCROW_API_KEY;

/* -----------------------
   Marketplace settings
------------------------ */
$seller_email = 'info@metaverde.com';
$thankyou_base = 'https://vsatdomains.com/portfolio/thankyou.php';

/* -----------------------
   Helpers
------------------------ */
function normalizeDomain($domain): string {
    $domain = strtolower(trim((string)$domain));
    $domain = preg_replace('/\s+/', '', $domain);

    $pattern = '/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*\.[a-z]{2,}$/i';
    if ($domain === '' || !preg_match($pattern, $domain)) return '';
    return $domain;
}

function normalizePrice($priceRaw): float {
    if ($priceRaw === null || $priceRaw === '') return 0.0;
    if (!is_numeric($priceRaw)) return 0.0;
    $p = (float)$priceRaw;
    if ($p <= 0) return 0.0;
    return round($p, 2);
}

function createEscrowTransaction(
    string $domain,
    float $priceFloat,
    string $seller_email,
    string $buyer_email,
    string $escrow_email,
    string $escrow_api_key
): array {
    $url = "https://api.escrow.com/2017-09-01/transaction";

    $data = [
        "parties" => [
            [
                "role" => "buyer",
                "customer" => $buyer_email
            ],
            [
                "role" => "seller",
                "customer" => $seller_email,
                "initiator" => true
            ]
        ],
        "currency" => "usd",
        "description" => "Sale of domain: {$domain}",
        "items" => [
            [
                "type" => "domain_name",
                "title" => $domain,
                "description" => $domain,
                "extra_attributes" => [
                    "concierge" => false,
                    "with_content" => false
                ],
                "schedule" => [
                    [
                        "amount" => $priceFloat,
                        "payer_customer" => $buyer_email,
                        "beneficiary_customer" => $seller_email
                    ]
                ],
                "quantity" => 1,
                "inspection_period" => 259200
            ]
        ]
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Accept: application/json"
    ]);
    curl_setopt($ch, CURLOPT_USERPWD, "{$escrow_email}:{$escrow_api_key}");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $response = curl_exec($ch);
    $http_code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($http_code === 201) {
        $result = json_decode((string)$response, true);
        return [
            'success' => true,
            'transaction_id' => $result['id'] ?? null,
            'payment_url' => $result['landing_page'] ?? null,
            'raw' => $result
        ];
    }

    $error = "Failed to create transaction: HTTP {$http_code}";
    if ($curl_error) $error .= " | cURL Error: {$curl_error}";
    if ($response) $error .= " | Response: {$response}";

    return [
        'success' => false,
        'error' => $error
    ];
}

/* -----------------------
   Input
------------------------ */
$domain = normalizeDomain($_GET['domain'] ?? '');
$price  = normalizePrice($_GET['price'] ?? null);

$error_msg = '';

/* -----------------------
   Handle POST
------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $buyer_email = trim((string)($_POST['buyer_email'] ?? ''));

    if ($domain === '' || $price <= 0) {
        $error_msg = "Error: Missing or invalid domain or price.";
    } elseif (!filter_var($buyer_email, FILTER_VALIDATE_EMAIL)) {
        $error_msg = "Invalid buyer email address.";
    } else {
        $result = createEscrowTransaction($domain, $price, $seller_email, $buyer_email, $escrow_email, $escrow_api_key);

        if (!empty($result['success']) && !empty($result['transaction_id'])) {
            $tid = urlencode((string)$result['transaction_id']);
            $brand = urlencode('VSATDomains');
            header("Location: {$thankyou_base}?tid={$tid}&brand={$brand}");
            exit;
        } else {
            $error_msg = "Error creating Escrow.com transaction. " . htmlspecialchars($result['error'] ?? 'Unknown error');
        }
    }
}

$price_display = $price > 0 ? number_format($price, 2) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VSATDomains - Domain Purchase</title>
    <style>
        body{
            font-family: Arial, sans-serif;
            margin:0;
            padding:0;
            line-height:1.6;
            color:#111;
            background:#fff;
            text-align:center;
        }
        header{
            background:#000;
            color:#fff;
            padding:20px 0;
            text-align:center;
        }
        header h1{margin:0;font-size:2.2rem}
        header p{margin:6px 0 0;color:#ddd}
        nav{margin-top:10px}
        nav a{
            color:#fff;
            text-decoration:none;
            margin:0 12px;
            font-size:15px;
        }
        nav a:hover{text-decoration:underline}

        .container{
            max-width:600px;
            margin:30px auto;
            padding:22px;
            border:1px solid #eee;
            border-radius:8px;
            background:#fff;
            box-shadow:0 0 8px rgba(0,0,0,0.08);
            text-align:left;
        }
        .container h2{
            margin:0 0 10px;
            text-align:center;
        }
        .row{
            margin:10px 0;
        }
        .price{
            font-size:1.4rem;
            font-weight:700;
            color:#111;
            text-align:center;
            margin:10px 0 12px;
        }
        .buyer-email-form{
            display:flex;
            gap:10px;
            margin-top:12px;
            flex-wrap:wrap;
            justify-content:center;
        }
        input[type="email"]{
            padding:10px;
            border:1px solid #ddd;
            border-radius:6px;
            font-size:16px;
            flex:1;
            min-width:240px;
        }
        .purchase-btn{
            padding:10px 14px;
            background:#1a73e8;
            color:#fff;
            border:none;
            border-radius:6px;
            cursor:pointer;
            font-size:16px;
            font-weight:700;
        }
        .purchase-btn:hover{background:#1557b0}

        .error{
            color:#b00020;
            background:#fde7ea;
            border:1px solid #f5c2c7;
            padding:10px;
            border-radius:6px;
            margin:12px 0;
            text-align:center;
        }
        .note{
            color:#444;
            font-size:14px;
            text-align:center;
            margin-top:10px;
        }

        footer{
            background:#000;
            color:#fff;
            text-align:center;
            padding:18px 0;
            margin-top:30px;
            font-size:14px;
        }
        footer a{color:#1a73e8;text-decoration:none}
        footer a:hover{text-decoration:underline}
    </style>
</head>
<body>

<header>
    <h1>VSATDomains</h1>
    <p>Your destination for premium domain names</p>

    <nav>
        <a href="/portfolio/index.php?page=1">Home</a>
        <a href="/portfolio/about.php">About</a>
        <a href="/portfolio/contact.php">Contact</a>
        <a href="/portfolio/terms.php">Terms</a>
        <a href="/portfolio/privacy.php">Privacy</a>
    </nav>
</header>

<div class="container">
    <h2>Purchase Domain</h2>

    <?php if ($error_msg): ?>
        <div class="error"><?php echo $error_msg; ?></div>
    <?php endif; ?>

    <?php if ($domain === '' || $price <= 0): ?>
        <div class="error">Error: No valid domain or price specified.</div>
    <?php else: ?>
        <div class="row"><strong>Domain:</strong> <?php echo htmlspecialchars($domain); ?></div>
        <div class="price">Price: $<?php echo htmlspecialchars($price_display); ?></div>

        <form method="POST" action="" class="buyer-email-form">
            <input type="email" name="buyer_email" placeholder="Your Email Address" required>
            <button type="submit" class="purchase-btn">Continue to Escrow.com</button>
        </form>

        <div class="note">
            Enter your email to initiate a secure transaction through Escrow.com.
        </div>
    <?php endif; ?>
</div>

<footer>
    <div>
        Contact: <a href="mailto:info@metaverde.com">info@metaverde.com</a>
    </div>
    <div>© 2025 VSATDomains</div>
</footer>

<?php ob_end_flush(); ?>
</body>
</html>
