<?php
/**
 * static_pay.php
 * Public page for a merchant's reusable Static Paylink (created from
 * auth/static_paylink.php). Reached via the clean URL /s/{link_id}
 * (see root .htaccess). Every visitor who pays here gets a brand new
 * order created through the same /api/create-order endpoint every other
 * payment flow already uses - so QR/verification all just works.
 */
define('ROOT_DIR', realpath(dirname(__FILE__)) . '/');
include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'auth/config.php';
include ROOT_DIR . 'pages/dbInfo.php';
include ROOT_DIR . 'includes/white_label_lib.php';

$linkId = mysqli_real_escape_string($conn, $_GET['id'] ?? '');
$link = null;
if ($linkId !== '') {
    $res = mysqli_query($conn, "SELECT * FROM static_paylinks WHERE link_id = '$linkId' LIMIT 1");
    if ($res && mysqli_num_rows($res) > 0) {
        $link = mysqli_fetch_assoc($res);
    }
}

$brand = htmlspecialchars($site_settings['brand_name'] ?? 'Payment');
$isExpired = $link && !empty($link['expires_at']) && strtotime($link['expires_at']) < time();
$isInvalid = !$link || $link['status'] !== 'Active' || $isExpired;

// ---------- Handle payment submission ----------
$formError = '';
if (!$isInvalid && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pay_now'])) {
    $custName = trim($_POST['cust_name'] ?? '');
    $custMobile = trim($_POST['cust_mobile'] ?? '');
    $custEmail = trim($_POST['cust_email'] ?? '');

    if ($link['collect_name'] && $custName === '') $formError = 'Please enter your name.';
    elseif ($link['collect_mobile'] && !preg_match('/^[0-9]{10}$/', $custMobile)) $formError = 'Please enter a valid 10-digit mobile number.';
    elseif ($link['collect_email'] && !filter_var($custEmail, FILTER_VALIDATE_EMAIL)) $formError = 'Please enter a valid email address.';

    if ($formError === '') {
        $orderid = mt_rand(10000000000, 9999999999999);
        $redirectTo = ($link['paylink_type'] === 'redirect' && !empty($link['redirect_url']))
            ? $link['redirect_url']
            : 'https://' . current_host() . '/success';

        $data = [
            'customer_mobile' => $custMobile !== '' ? $custMobile : '0000000000',
            'user_token'      => $link['user_token'],
            'amount'          => $link['amount'],
            'order_id'        => $orderid,
            'redirect_url'    => $redirectTo,
            'remark1'         => $link['title'],
            'origin_domain'   => current_host(),
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://' . current_host() . '/api/create-order',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => http_build_query($data),
        ]);
        $response = curl_exec($curl);
        $curlErr = curl_error($curl);
        curl_close($curl);
        $jsondatares = json_decode($response, true);

        if (!empty($jsondatares['status']) && !empty($jsondatares['result']['payment_url'])) {
            mysqli_query($conn, "UPDATE static_paylinks SET orders_count = orders_count + 1 WHERE id = " . (int)$link['id']);
            header('Location: ' . $jsondatares['result']['payment_url']);
            exit;
        } else {
            $formError = $jsondatares['message'] ?? ($curlErr ?: 'Payment link could not be created. Please try again.');
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $isInvalid ? 'Link Unavailable' : htmlspecialchars($link['title']) . ' - ' . $brand; ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root{ --p:#6c63ff; --p2:#e040fb; --g: linear-gradient(135deg,#6c63ff,#e040fb); }
    *{box-sizing:border-box}
    body{margin:0;background:#0a0a12;color:#fff;font-family:-apple-system,'Segoe UI',Roboto,sans-serif;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px}
    .card{width:100%;max-width:420px;background:rgba(255,255,255,.04);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.08);border-radius:22px;padding:28px 26px;text-align:center}
    .icn{width:56px;height:56px;border-radius:16px;background:var(--g);display:inline-flex;align-items:center;justify-content:center;font-size:24px;margin-bottom:16px}
    h2{margin:0 0 6px;font-size:1.25rem}
    .desc{color:rgba(255,255,255,.5);font-size:.85rem;margin-bottom:20px}
    .amt{font-size:2.1rem;font-weight:800;margin:10px 0 22px;background:var(--g);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
    .form-control{width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;padding:11px 13px;color:#fff;font-size:.9rem;margin-bottom:12px;text-align:left}
    .form-control::placeholder{color:rgba(255,255,255,.3)}
    .btn{width:100%;background:var(--g);border:none;color:#fff;padding:13px;border-radius:10px;font-size:.95rem;font-weight:700;cursor:pointer;margin-top:6px}
    .err{background:rgba(255,101,132,.12);color:#ff6584;border-radius:8px;padding:10px 12px;font-size:.8rem;margin-bottom:14px;text-align:left}
    .badge{display:inline-block;background:rgba(255,255,255,.06);border-radius:20px;padding:4px 12px;font-size:.72rem;color:rgba(255,255,255,.5);margin-top:16px}
</style>
</head>
<body>
<div class="card">
<?php if ($isInvalid): ?>
    <div class="icn"><i class="fas fa-link-slash"></i></div>
    <h2>Link Unavailable</h2>
    <p class="desc"><?php echo $isExpired ? 'Yeh payment link expire ho chuki hai.' : 'Yeh payment link ab active nahi hai ya exist nahi karti.'; ?></p>
<?php else: ?>
    <div class="icn"><i class="fas fa-store"></i></div>
    <h2><?php echo htmlspecialchars($link['title']); ?></h2>
    <?php if (!empty($link['description'])): ?><p class="desc"><?php echo htmlspecialchars($link['description']); ?></p><?php endif; ?>
    <div class="amt">₹<?php echo number_format((float)$link['amount'], 2); ?></div>

    <?php if ($formError): ?><div class="err"><i class="fas fa-circle-exclamation"></i> <?php echo htmlspecialchars($formError); ?></div><?php endif; ?>

    <form method="POST" action="">
        <?php if ($link['collect_name']): ?>
            <input type="text" name="cust_name" class="form-control" placeholder="Your Name" value="<?php echo htmlspecialchars($_POST['cust_name'] ?? ''); ?>" required>
        <?php endif; ?>
        <?php if ($link['collect_mobile']): ?>
            <input type="tel" name="cust_mobile" class="form-control" placeholder="Mobile Number" maxlength="10" value="<?php echo htmlspecialchars($_POST['cust_mobile'] ?? ''); ?>" required>
        <?php endif; ?>
        <?php if ($link['collect_email']): ?>
            <input type="email" name="cust_email" class="form-control" placeholder="Email Address" value="<?php echo htmlspecialchars($_POST['cust_email'] ?? ''); ?>" required>
        <?php endif; ?>
        <button type="submit" name="pay_now" class="btn"><i class="fas fa-lock"></i> Pay Now</button>
    </form>
    <div class="badge"><i class="fas fa-shield-halved"></i> Secured by <?php echo $brand; ?></div>
<?php endif; ?>
</div>
</body>
</html>
