<?php
require_once 'config.php';

/* ═══════════════════════════════════════════════════════════
   AJAX — VALIDATE COUPON
   Called via fetch: order.php?_api=validate_coupon
═══════════════════════════════════════════════════════════ */
if (($_GET['_api'] ?? '') === 'validate_coupon') {
    header('Content-Type: application/json');
    $code  = strtoupper(trim($_GET['code'] ?? ''));
    $pid   = (int)($_GET['pid']   ?? 0);
    $cycle = trim($_GET['cycle']  ?? 'monthly');

    if (!$code) {
        echo json_encode(['valid' => false, 'message' => 'Please enter a promo code.']);
        exit;
    }
    if (!defined('WHMCS_API_ID') || trim(WHMCS_API_ID) === '') {
        echo json_encode(['valid' => false, 'message' => 'WHMCS API not configured.']);
        exit;
    }

    // Fetch all promo codes from WHMCS
    $post = [
        'identifier'   => WHMCS_API_ID,
        'secret'       => WHMCS_API_SECRET,
        'action'       => 'GetPromoCodes',
        'responsetype' => 'json',
    ];
    $ch = curl_init(PORTAL_URL . '/includes/api.php');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($post),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $raw  = curl_exec($ch);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($err || !$raw) {
        echo json_encode(['valid' => false, 'message' => 'Could not reach server. Please try again.']);
        exit;
    }
    $data = json_decode($raw, true);
    if (($data['result'] ?? '') !== 'success' || empty($data['promocodes']['promocode'])) {
        echo json_encode(['valid' => false, 'message' => 'Invalid or expired promo code.']);
        exit;
    }

    $found = null;
    foreach ($data['promocodes']['promocode'] as $promo) {
        if (strtoupper($promo['code']) === $code) { $found = $promo; break; }
    }
    if (!$found) {
        echo json_encode(['valid' => false, 'message' => 'Invalid promo code.']);
        exit;
    }

    // Check expiry
    if (!empty($found['expirationdate']) && $found['expirationdate'] !== '0000-00-00') {
        if (strtotime($found['expirationdate']) < time()) {
            echo json_encode(['valid' => false, 'message' => 'This promo code has expired.']);
            exit;
        }
    }
    // Check max uses
    if ((int)$found['maxuses'] > 0 && (int)$found['uses'] >= (int)$found['maxuses']) {
        echo json_encode(['valid' => false, 'message' => 'This promo code has reached its usage limit.']);
        exit;
    }
    // Check product applicability (blank = all products)
    $appliesto = trim($found['appliesto'] ?? '');
    if ($pid > 0 && $appliesto !== '') {
        $allowed = array_map('trim', explode(',', $appliesto));
        if (!in_array((string)$pid, $allowed)) {
            echo json_encode(['valid' => false, 'message' => 'This code does not apply to the selected plan.']);
            exit;
        }
    }

    echo json_encode([
        'valid'    => true,
        'type'     => $found['type'],    // 'Percentage' or 'Fixed Amount'
        'value'    => (float)$found['value'],
        'code'     => $found['code'],
        'message'  => 'Promo code applied!',
    ]);
    exit;
}

/* ═══════════════════════════════════════════════════════════
   WHMCS API HELPER
═══════════════════════════════════════════════════════════ */
function whmcs_call(string $action, array $params = []): array {
    if (!defined('WHMCS_API_ID') || trim(WHMCS_API_ID) === '') {
        return ['result' => 'error', 'message' => 'WHMCS API credentials not configured in config.php.'];
    }
    $post = array_merge([
        'identifier'   => WHMCS_API_ID,
        'secret'       => WHMCS_API_SECRET,
        'action'       => $action,
        'responsetype' => 'json',
    ], $params);
    $ch = curl_init(PORTAL_URL . '/includes/api.php');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($post),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $raw = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) return ['result' => 'error', 'message' => 'Connection error: ' . $err];
    $data = json_decode($raw, true);
    return $data ?: ['result' => 'error', 'message' => 'Invalid response from WHMCS.'];
}

/* ═══════════════════════════════════════════════════════════
   PLAN CATALOGUE  (pricing falls back to config.php values)
═══════════════════════════════════════════════════════════ */
$catalogue = [
    'hosting' => [
        'label' => 'Web Hosting', 'icon' => 'fa-server', 'type' => 'product',
        'plans' => [
            ['pid' => PID_HOSTING_STARTER,  'name' => 'Starter',  'price' => HOSTING_STARTER_PRICE,  'orig' => HOSTING_STARTER_ORIG,  'saving' => HOSTING_STARTER_SAVING,  'cycle' => 'monthly', 'unit' => '/mo',
             'icon' => 'fa-seedling', 'tagline' => 'Launch your first website',
             'features' => ['Host <strong>1</strong> Website', '<strong>1 GB</strong> SSD Storage', '<strong>Unlimited</strong> Bandwidth', '<strong>10</strong> Email Accounts', '<strong>Free</strong> SSL Certificate', '100 Day Money-Back']],
            ['pid' => PID_HOSTING_PRO,      'name' => 'Pro',      'price' => HOSTING_PRO_PRICE,      'orig' => HOSTING_PRO_ORIG,      'saving' => HOSTING_PRO_SAVING,      'cycle' => 'monthly', 'unit' => '/mo', 'popular' => true,
             'icon' => 'fa-bolt', 'tagline' => 'Grow your online presence',
             'features' => ['Host <strong>5</strong> Websites', '<strong>5 GB</strong> SSD Storage', '<strong>Unlimited</strong> Bandwidth', '<strong>Unlimited</strong> Emails', '<strong>Free</strong> SSL Certificate', '100 Day Money-Back']],
            ['pid' => PID_HOSTING_BUSINESS, 'name' => 'Business', 'price' => HOSTING_BUSINESS_PRICE, 'orig' => HOSTING_BUSINESS_ORIG, 'saving' => HOSTING_BUSINESS_SAVING, 'cycle' => 'monthly', 'unit' => '/mo',
             'icon' => 'fa-crown', 'tagline' => 'Power multiple projects',
             'features' => ['Host <strong>25</strong> Websites', '<strong>30 GB</strong> SSD Storage', '<strong>Unlimited</strong> Bandwidth', '<strong>Unlimited</strong> Emails', '<strong>Free</strong> SSL Certificate', '100 Day Money-Back']],
        ],
    ],
    'vps' => [
        'label' => 'VPS Hosting', 'icon' => 'fa-hdd', 'type' => 'product',
        'plans' => [
            ['pid' => PID_VPS_LITE,    'name' => 'Lite',    'price' => VPS_LITE_PRICE,    'orig' => VPS_LITE_ORIG,    'saving' => VPS_LITE_SAVING,    'cycle' => 'monthly', 'unit' => '/mo',
             'features' => ['<strong>2</strong> CPU Cores', '<strong>4 GB</strong> RAM', '<strong>50 GB</strong> NVMe SSD', '<strong>2000 GB</strong> Bandwidth', '<strong>1</strong> Dedicated IP', 'Full Root Access']],
            ['pid' => PID_VPS_PLUS,    'name' => 'Plus',    'price' => VPS_PLUS_PRICE,    'orig' => VPS_PLUS_ORIG,    'saving' => VPS_PLUS_SAVING,    'cycle' => 'monthly', 'unit' => '/mo', 'popular' => true,
             'features' => ['<strong>4</strong> CPU Cores', '<strong>8 GB</strong> RAM', '<strong>100 GB</strong> NVMe SSD', '<strong>2000 GB</strong> Bandwidth', '<strong>1</strong> Dedicated IP', 'Full Root Access']],
            ['pid' => PID_VPS_PREMIUM, 'name' => 'Premium', 'price' => VPS_PREMIUM_PRICE, 'orig' => VPS_PREMIUM_ORIG, 'saving' => VPS_PREMIUM_SAVING, 'cycle' => 'monthly', 'unit' => '/mo',
             'features' => ['<strong>4</strong> CPU Cores', '<strong>16 GB</strong> RAM', '<strong>150 GB</strong> NVMe SSD', '<strong>4000 GB</strong> Bandwidth', '<strong>1</strong> Dedicated IP', 'Full Root Access']],
        ],
    ],
    'email' => [
        'label' => 'Email Hosting', 'icon' => 'fa-envelope', 'type' => 'product',
        'plans' => [
            ['pid' => PID_EMAIL_BASIC,    'name' => 'Basic',    'price' => '99',  'orig' => '199',  'saving' => '50', 'cycle' => 'monthly', 'unit' => '/mo',
             'features' => ['<strong>5</strong> Email Accounts', '<strong>5 GB</strong> Mailbox', 'Webmail Access', 'Spam &amp; Virus Protection', 'Free SSL', '24/7 Support']],
            ['pid' => PID_EMAIL_PRO,      'name' => 'Pro',      'price' => '199', 'orig' => '399',  'saving' => '50', 'cycle' => 'monthly', 'unit' => '/mo', 'popular' => true,
             'features' => ['<strong>25</strong> Email Accounts', '<strong>25 GB</strong> Mailbox', 'Webmail Access', 'Spam &amp; Virus Protection', 'Free SSL', '24/7 Support']],
            ['pid' => PID_EMAIL_BUSINESS, 'name' => 'Business', 'price' => '399', 'orig' => '799',  'saving' => '50', 'cycle' => 'monthly', 'unit' => '/mo',
             'features' => ['<strong>Unlimited</strong> Accounts', '<strong>100 GB</strong> Mailbox', 'Webmail Access', 'Spam &amp; Virus Protection', 'Free SSL', '24/7 Support']],
        ],
    ],
    'domain' => [
        'label' => 'Domain', 'icon' => 'fa-globe', 'type' => 'domain',
        'tlds'  => [
            ['ext' => '.in',     'price' => PRICE_IN,     'label' => '.IN',     'popular' => true],
            ['ext' => '.co.in',  'price' => PRICE_CO_IN,  'label' => '.CO.IN'],
            ['ext' => '.com.in', 'price' => PRICE_COM_IN, 'label' => '.COM.IN'],
            ['ext' => '.com',    'price' => PRICE_COM,    'label' => '.COM'],
            ['ext' => '.net',    'price' => PRICE_NET,    'label' => '.NET'],
        ],
    ],
];

/* ═══════════════════════════════════════════════════════════
   HANDLE ORDER SUBMISSION
═══════════════════════════════════════════════════════════ */
$order_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['_action'] ?? '') === 'place_order') {

    // Sanitise inputs
    $in = array_map('trim', [
        'firstname'      => $_POST['firstname']      ?? '',
        'lastname'       => $_POST['lastname']       ?? '',
        'email'          => $_POST['email']          ?? '',
        'phone'          => $_POST['phone']          ?? '',
        'address'        => $_POST['address']        ?? '',
        'city'           => $_POST['city']           ?? '',
        'state'          => $_POST['state']          ?? '',
        'postcode'       => $_POST['postcode']       ?? '',
        'country'        => $_POST['country']        ?? 'IN',
        'order_type'     => $_POST['order_type']     ?? 'product',
        'pid'            => $_POST['pid']            ?? '0',
        'billing_cycle'  => $_POST['billing_cycle']  ?? 'monthly',
        'hosting_domain' => $_POST['hosting_domain'] ?? '',
        'domain_name'    => $_POST['domain_name']    ?? '',
        'domain_tld'     => $_POST['domain_tld']     ?? '.in',
        'promocode'      => $_POST['promocode']      ?? '',
    ]);
    $password = $_POST['password'] ?? '';

    // Basic validation
    if (!$in['firstname'] || !$in['lastname'] || !$in['email'] || !$password) {
        $order_error = 'Please fill in all required fields.';
    } elseif (!filter_var($in['email'], FILTER_VALIDATE_EMAIL)) {
        $order_error = 'Please enter a valid email address.';
    } elseif (strlen($password) < 8) {
        $order_error = 'Password must be at least 8 characters.';
    } else {
        // Step 1 — Create or retrieve client
        $cr = whmcs_call('AddClient', [
            'firstname'   => $in['firstname'],
            'lastname'    => $in['lastname'],
            'email'       => $in['email'],
            'password2'   => $password,
            'phonenumber' => $in['phone'],
            'address1'    => $in['address'] ?: 'N/A',
            'city'        => $in['city']    ?: 'N/A',
            'state'       => $in['state']   ?: 'N/A',
            'postcode'    => $in['postcode']?: '000000',
            'country'     => $in['country'],
        ]);

        $client_id = null;
        if ($cr['result'] === 'success') {
            $client_id = (int)$cr['clientid'];
        } elseif (stripos($cr['message'] ?? '', 'exist') !== false) {
            $find = whmcs_call('GetClients', ['search' => $in['email']]);
            $client_id = isset($find['clients']['client'][0]['id'])
                ? (int)$find['clients']['client'][0]['id'] : null;
        }

        if (!$client_id) {
            $order_error = $cr['message'] ?? 'Could not create your account. Please try again.';
        } else {
            // Step 2 — Place order
            if ($in['order_type'] === 'domain') {
                $domainParams = [
                    'clientid'        => $client_id,
                    'paymentmethod'   => WHMCS_PAY_METHOD,
                    'domain[0]'       => $in['domain_name'] . $in['domain_tld'],
                    'domaintype[0]'   => 'register',
                    'regperiod[0]'    => 1,
                    'dnsmanagement[0]'=> true,
                ];
                if ($in['promocode']) $domainParams['promocode'] = $in['promocode'];
                $or = whmcs_call('AddOrder', $domainParams);
            } else {
                $productParams = [
                    'clientid'        => $client_id,
                    'paymentmethod'   => WHMCS_PAY_METHOD,
                    'pid[0]'          => (int)$in['pid'],
                    'domain[0]'       => $in['hosting_domain'],
                    'billingcycle[0]' => $in['billing_cycle'],
                ];
                if ($in['promocode']) $productParams['promocode'] = $in['promocode'];
                $or = whmcs_call('AddOrder', $productParams);
            }

            if (($or['result'] ?? '') === 'success') {
                $inv = (int)($or['invoiceid'] ?? 0);
                header('Location: ' . PORTAL_URL . '/viewinvoice.php?id=' . $inv . '&paynow=true');
                exit;
            } else {
                $order_error = $or['message'] ?? 'Order could not be placed. Please try again or contact support.';
            }
        }
    }
}

/* ═══════════════════════════════════════════════════════════
   PAGE HEADER
═══════════════════════════════════════════════════════════ */
$page_title = "Order Now | " . SITE_NAME;
$page_desc  = "Order domains, web hosting, VPS or email hosting from " . SITE_NAME . " — India's lowest prices.";
include 'includes/header.php';
?>

<style>
/* ── Checkout layout ─────────────────────────────────────── */
.checkout-hero{background:linear-gradient(135deg,var(--primary) 0%,var(--primary-light) 100%);padding:40px 0 0;}
.checkout-steps{display:flex;align-items:center;justify-content:center;gap:0;margin-bottom:0;padding-bottom:28px;}
.cs-step{display:flex;flex-direction:column;align-items:center;position:relative;flex:1;max-width:160px;}
.cs-step:not(:last-child)::after{content:'';position:absolute;top:18px;left:calc(50% + 22px);right:calc(-50% + 22px);height:2px;background:rgba(255,255,255,.3);}
.cs-step.done::after,.cs-step.active::after{background:rgba(255,255,255,.7);}
.cs-num{width:36px;height:36px;border-radius:50%;background:rgba(255,255,255,.25);color:#fff;font-family:'Nunito',sans-serif;font-weight:800;font-size:15px;display:flex;align-items:center;justify-content:center;border:2px solid rgba(255,255,255,.4);transition:all .3s;flex-shrink:0;}
.cs-step.active .cs-num{background:#fff;color:var(--primary);border-color:#fff;box-shadow:0 3px 12px rgba(0,0,0,.2);}
.cs-step.done .cs-num{background:rgba(255,255,255,.5);border-color:rgba(255,255,255,.6);}
.cs-label{color:rgba(255,255,255,.75);font-size:11px;font-weight:700;margin-top:6px;text-transform:uppercase;letter-spacing:.5px;white-space:nowrap;}
.cs-step.active .cs-label{color:#fff;}

/* ── Checkout body card ──────────────────────────────────── */
.checkout-body{background:#f0f7ff;padding:32px 0 60px;}
.checkout-card{background:#fff;border-radius:16px;box-shadow:0 4px 24px rgba(26,86,219,.1);border:1px solid var(--border);overflow:hidden;}
.checkout-step-panel{display:none;padding:32px;}
.checkout-step-panel.active{display:block;}

/* ── Plan tabs ───────────────────────────────────────────── */
.plan-tabs{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:24px;}
.plan-tab-btn{background:#f0f7ff;border:2px solid var(--border);color:var(--text-dark);padding:9px 20px;border-radius:30px;font-weight:700;font-size:13px;cursor:pointer;transition:all .2s;display:flex;align-items:center;gap:6px;}
.plan-tab-btn:hover,.plan-tab-btn.active{background:var(--primary);color:#fff;border-color:var(--primary);}
.plan-tab-content{display:none;}
.plan-tab-content.active{display:block;}

/* ── Plan cards (base — used by VPS / Email) ─────────────── */
.plan-card{border:2px solid var(--border);border-radius:12px;padding:20px;cursor:pointer;transition:all .22s;position:relative;height:100%;}
.plan-card:hover{border-color:var(--primary);box-shadow:0 6px 20px rgba(26,86,219,.14);}
.plan-card.selected{border-color:var(--primary);box-shadow:0 0 0 3px rgba(26,86,219,.18);background:#f0f7ff;}
.plan-card .popular-badge{position:absolute;top:-1px;right:16px;background:var(--accent);color:#fff;font-size:10px;font-weight:800;padding:3px 10px;border-radius:0 0 8px 8px;text-transform:uppercase;}
.plan-card .plan-name{font-family:'Nunito',sans-serif;font-weight:800;font-size:18px;color:var(--text-dark);margin-bottom:4px;}
.plan-card .plan-price{font-family:'Nunito',sans-serif;font-weight:800;font-size:28px;color:var(--primary);line-height:1;}
.plan-card .plan-price small{font-size:13px;font-weight:500;color:var(--text-muted);}
.plan-card .plan-orig{font-size:13px;color:var(--text-muted);text-decoration:line-through;}
.plan-card .plan-saving{display:inline-block;background:#d1fae5;color:#065f46;font-size:11px;font-weight:700;padding:2px 8px;border-radius:10px;margin:4px 0 10px;}
.plan-card .plan-features{list-style:none;padding:0;margin:12px 0 0;font-size:13px;}
.plan-card .plan-features li{padding:5px 0;border-bottom:1px solid var(--border);color:var(--text-muted);display:flex;align-items:center;gap:7px;}
.plan-card .plan-features li:last-child{border-bottom:none;}
.plan-card .plan-features li i{color:var(--primary);width:14px;flex-shrink:0;}
.plan-card .select-btn{width:100%;margin-top:14px;padding:9px;border-radius:6px;border:2px solid var(--primary);background:#fff;color:var(--primary);font-weight:700;font-size:13px;cursor:pointer;transition:all .2s;}
.plan-card.selected .select-btn,.plan-card:hover .select-btn{background:var(--primary);color:#fff;}
.plan-card .selected-check{position:absolute;top:12px;left:12px;width:22px;height:22px;background:var(--primary);border-radius:50%;display:none;align-items:center;justify-content:center;}
.plan-card.selected .selected-check{display:flex;}
.plan-card.selected .selected-check i{font-size:11px;color:#fff;}

/* ── Hosting plan cards v2 ───────────────────────────────── */
.hplan-card{border-radius:16px;overflow:hidden;cursor:pointer;transition:transform .22s,box-shadow .22s;position:relative;height:100%;display:flex;flex-direction:column;border:2px solid transparent;background:#fff;box-shadow:0 2px 12px rgba(26,86,219,.08);}
.hplan-card:hover{transform:translateY(-5px);box-shadow:0 14px 36px rgba(26,86,219,.18);}
.hplan-card.selected{border-color:var(--primary);box-shadow:0 0 0 4px rgba(26,86,219,.18),0 12px 32px rgba(26,86,219,.2);transform:translateY(-4px);}
.hplan-card.popular-card{border-color:var(--primary);}

/* card header band */
.hplan-header{padding:24px 22px 20px;position:relative;overflow:hidden;}
.hplan-header::after{content:'';position:absolute;bottom:-20px;right:-20px;width:80px;height:80px;border-radius:50%;background:rgba(255,255,255,.12);}
.hplan-card.plan-starter .hplan-header{background:linear-gradient(135deg,#0ea5e9 0%,#38bdf8 100%);}
.hplan-card.plan-pro .hplan-header{background:linear-gradient(135deg,#1a56db 0%,#7c3aed 100%);}
.hplan-card.plan-biz .hplan-header{background:linear-gradient(135deg,#0f172a 0%,#1e3a5f 100%);}

.hplan-tier-icon{width:44px;height:44px;border-radius:12px;background:rgba(255,255,255,.22);display:flex;align-items:center;justify-content:center;margin-bottom:12px;font-size:20px;color:#fff;}
.hplan-name{font-family:'Nunito',sans-serif;font-weight:800;font-size:22px;color:#fff;margin:0 0 2px;}
.hplan-tagline{font-size:12px;color:rgba(255,255,255,.8);margin:0;}
.hplan-popular-pill{position:absolute;top:14px;right:14px;background:#ff6b35;color:#fff;font-size:10px;font-weight:800;padding:3px 10px;border-radius:20px;text-transform:uppercase;letter-spacing:.5px;}
.hplan-selected-ring{position:absolute;top:14px;left:14px;width:24px;height:24px;border-radius:50%;background:#fff;display:none;align-items:center;justify-content:center;}
.hplan-card.selected .hplan-selected-ring{display:flex;}
.hplan-selected-ring i{font-size:12px;color:var(--primary);}

/* card body */
.hplan-body{padding:20px 22px;flex:1;display:flex;flex-direction:column;}
.hplan-price-row{display:flex;align-items:flex-end;gap:10px;margin-bottom:4px;}
.hplan-price{font-family:'Nunito',sans-serif;font-weight:800;font-size:36px;color:var(--text-dark);line-height:1;}
.hplan-price small{font-size:14px;font-weight:500;color:var(--text-muted);}
.hplan-orig{font-size:13px;color:var(--text-muted);text-decoration:line-through;}
.hplan-saving{display:inline-flex;align-items:center;gap:4px;background:#d1fae5;color:#065f46;font-size:11px;font-weight:800;padding:3px 10px;border-radius:20px;margin-top:6px;width:fit-content;}
.hplan-divider{height:1px;background:var(--border);margin:16px 0;}
.hplan-features{list-style:none;padding:0;margin:0;flex:1;}
.hplan-features li{display:flex;align-items:center;gap:10px;font-size:13.5px;color:var(--text-dark);padding:7px 0;border-bottom:1px dashed #e2e8f0;}
.hplan-features li:last-child{border-bottom:none;}
.hplan-feat-icon{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;}
.hplan-card.plan-starter .hplan-feat-icon{background:#e0f2fe;color:#0284c7;}
.hplan-card.plan-pro    .hplan-feat-icon{background:#ede9fe;color:#7c3aed;}
.hplan-card.plan-biz    .hplan-feat-icon{background:#dbeafe;color:#1a56db;}
.hplan-feat-icon i{font-size:10px;}

/* CTA button */
.hplan-btn{width:100%;margin-top:18px;padding:11px;border-radius:10px;font-weight:800;font-size:14px;cursor:pointer;transition:all .2s;border:none;letter-spacing:.3px;}
.hplan-card.plan-starter .hplan-btn{background:#e0f2fe;color:#0284c7;}
.hplan-card.plan-starter:hover .hplan-btn,.hplan-card.plan-starter.selected .hplan-btn{background:linear-gradient(135deg,#0ea5e9,#38bdf8);color:#fff;}
.hplan-card.plan-pro .hplan-btn{background:linear-gradient(135deg,#1a56db,#7c3aed);color:#fff;}
.hplan-card.plan-pro:hover .hplan-btn,.hplan-card.plan-pro.selected .hplan-btn{opacity:.9;}
.hplan-card.plan-biz .hplan-btn{background:#0f172a;color:#fff;}
.hplan-card.plan-biz:hover .hplan-btn,.hplan-card.plan-biz.selected .hplan-btn{background:#1e3a5f;}

/* ── Domain TLD grid ─────────────────────────────────────── */
.tld-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:12px;margin:16px 0;}
.tld-card{border:2px solid var(--border);border-radius:10px;padding:14px 10px;text-align:center;cursor:pointer;transition:all .2s;}
.tld-card:hover,.tld-card.selected{border-color:var(--primary);background:#f0f7ff;}
.tld-card.selected{box-shadow:0 0 0 3px rgba(26,86,219,.15);}
.tld-card .tld-ext{font-family:'Nunito',sans-serif;font-weight:800;font-size:18px;color:var(--primary);}
.tld-card .tld-price{font-size:13px;color:var(--text-muted);margin-top:3px;}
.tld-card .tld-popular{font-size:10px;background:var(--accent);color:#fff;padding:1px 7px;border-radius:10px;font-weight:700;}

/* ── Form styles ─────────────────────────────────────────── */
.form-label{font-size:13px;font-weight:700;color:var(--text-dark);margin-bottom:5px;}
.form-label .req{color:var(--accent);}
.form-control{border:1.5px solid var(--border);border-radius:8px;padding:10px 14px;font-size:14px;transition:border-color .2s;}
.form-control:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(26,86,219,.1);outline:none;}
.form-section-title{font-family:'Nunito',sans-serif;font-weight:800;font-size:14px;color:var(--primary);text-transform:uppercase;letter-spacing:.5px;border-bottom:2px solid #dbeafe;padding-bottom:6px;margin:20px 0 14px;}

/* ── Order summary sidebar ───────────────────────────────── */
.order-summary{background:#f0f7ff;border:1.5px solid var(--border);border-radius:12px;padding:20px;position:sticky;top:90px;}
.order-summary h5{font-family:'Nunito',sans-serif;font-weight:800;font-size:15px;margin-bottom:14px;color:var(--text-dark);}
.summary-row{display:flex;justify-content:space-between;align-items:center;font-size:13.5px;padding:7px 0;border-bottom:1px solid var(--border);}
.summary-row:last-child{border-bottom:none;font-weight:700;font-size:15px;color:var(--primary);margin-top:4px;}
.summary-placeholder{color:var(--text-muted);font-size:13px;font-style:italic;}
.cycle-select{display:flex;gap:8px;flex-wrap:wrap;margin-top:6px;}
.cycle-btn{flex:1;padding:8px 6px;border:2px solid var(--border);border-radius:8px;background:#fff;font-size:12px;font-weight:700;text-align:center;cursor:pointer;transition:all .2s;min-width:80px;}
.cycle-btn.active{border-color:var(--primary);background:var(--primary);color:#fff;}

/* ── Review panel ────────────────────────────────────────── */
.review-box{border:1.5px solid var(--border);border-radius:12px;padding:20px;margin-bottom:16px;}
.review-box h6{font-family:'Nunito',sans-serif;font-weight:800;font-size:13px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;}
.review-item{display:flex;justify-content:space-between;font-size:14px;padding:5px 0;border-bottom:1px solid #f0f7ff;}
.review-item:last-child{border-bottom:none;}
.review-total{background:linear-gradient(135deg,var(--primary),var(--primary-light));color:#fff;border-radius:12px;padding:16px 20px;display:flex;justify-content:space-between;align-items:center;margin-top:16px;}
.review-total .label{font-size:14px;opacity:.85;}
.review-total .amount{font-family:'Nunito',sans-serif;font-weight:800;font-size:24px;}

/* ── Action buttons ──────────────────────────────────────── */
.btn-next{background:var(--primary);color:#fff;border:none;padding:12px 32px;border-radius:8px;font-weight:700;font-size:15px;cursor:pointer;transition:background .2s;display:inline-flex;align-items:center;gap:8px;}
.btn-next:hover{background:var(--primary-dark);}
.btn-next:disabled{opacity:.6;cursor:not-allowed;}
.btn-back{background:#fff;color:var(--text-dark);border:2px solid var(--border);padding:11px 24px;border-radius:8px;font-weight:700;font-size:14px;cursor:pointer;transition:all .2s;}
.btn-back:hover{border-color:var(--primary);color:var(--primary);}
.btn-place-order{background:linear-gradient(135deg,#16a34a,#15803d);color:#fff;border:none;padding:14px 40px;border-radius:8px;font-weight:800;font-size:16px;cursor:pointer;transition:all .2s;display:inline-flex;align-items:center;gap:10px;width:100%;justify-content:center;}
.btn-place-order:hover{opacity:.92;transform:translateY(-1px);}

/* ── Error alert ──────────────────────────────────────────── */
.order-alert{background:#fef2f2;border:1.5px solid #fca5a5;border-radius:10px;padding:14px 18px;color:#991b1b;font-size:14px;display:flex;align-items:center;gap:10px;margin-bottom:20px;}

/* ── Coupon input ─────────────────────────────────────────── */
.coupon-wrap{margin-top:14px;padding-top:14px;border-top:1.5px solid var(--border);}
.coupon-wrap label{font-size:12px;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.4px;display:block;margin-bottom:7px;}
.coupon-row{display:flex;gap:6px;}
.coupon-row input{flex:1;border:1.5px solid var(--border);border-radius:8px;padding:8px 12px;font-size:13px;font-weight:700;text-transform:uppercase;letter-spacing:1px;background:#fff;transition:border-color .2s;outline:none;}
.coupon-row input:focus{border-color:var(--primary);}
.coupon-row input.coupon-valid{border-color:#16a34a;background:#f0fdf4;}
.coupon-row input.coupon-invalid{border-color:#dc2626;background:#fef2f2;}
.coupon-apply-btn{background:var(--primary);color:#fff;border:none;border-radius:8px;padding:8px 14px;font-size:12px;font-weight:700;cursor:pointer;white-space:nowrap;transition:background .2s;}
.coupon-apply-btn:hover{background:var(--primary-dark);}
.coupon-apply-btn:disabled{opacity:.5;cursor:not-allowed;}
.coupon-msg{font-size:12px;margin-top:6px;font-weight:600;display:none;}
.coupon-msg.ok{color:#16a34a;display:block;}
.coupon-msg.err{color:#dc2626;display:block;}
.coupon-remove{background:none;border:none;color:#dc2626;font-size:11px;font-weight:700;cursor:pointer;padding:0;margin-left:6px;display:none;}

/* ── Responsive ───────────────────────────────────────────── */
@media(max-width:767px){
  .checkout-step-panel{padding:20px 16px;}
  .cs-step::after{display:none;}
  .plan-card .plan-price{font-size:22px;}
}
</style>

<!-- ═══════════════════════════════════════════════════════ -->
<!--  CHECKOUT HERO + STEP INDICATORS                        -->
<!-- ═══════════════════════════════════════════════════════ -->
<div class="checkout-hero">
  <div class="container">
    <div class="text-center mb-3">
      <h1 style="color:#fff;font-size:28px;margin-bottom:4px;">Order Now</h1>
      <p style="color:rgba(255,255,255,.75);font-size:14px;margin:0;">Secure checkout powered by <?= SITE_NAME ?></p>
    </div>
    <div class="checkout-steps">
      <div class="cs-step active" id="indicator-1">
        <div class="cs-num"><span class="step-num">1</span><i class="fas fa-check" style="display:none;font-size:13px;"></i></div>
        <div class="cs-label">Choose Plan</div>
      </div>
      <div class="cs-step" id="indicator-2">
        <div class="cs-num"><span class="step-num">2</span><i class="fas fa-check" style="display:none;font-size:13px;"></i></div>
        <div class="cs-label">Your Details</div>
      </div>
      <div class="cs-step" id="indicator-3">
        <div class="cs-num">3</div>
        <div class="cs-label">Review &amp; Pay</div>
      </div>
    </div>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════════ -->
<!--  CHECKOUT BODY                                          -->
<!-- ═══════════════════════════════════════════════════════ -->
<div class="checkout-body">
<div class="container">
<div class="row justify-content-center">
<div class="col-xl-11">

<form method="POST" action="order.php" id="checkoutForm" novalidate>
  <input type="hidden" name="_action"       value="place_order">
  <input type="hidden" name="order_type"    id="h_order_type"   value="product">
  <input type="hidden" name="pid"           id="h_pid"          value="0">
  <input type="hidden" name="billing_cycle" id="h_billing_cycle" value="monthly">
  <input type="hidden" name="hosting_domain" id="h_hosting_domain" value="">
  <input type="hidden" name="domain_name"   id="h_domain_name"  value="">
  <input type="hidden" name="domain_tld"    id="h_domain_tld"   value=".in">
  <input type="hidden" name="promocode"     id="h_promocode"    value="">

  <div class="checkout-card mt-4">

    <!-- ─────────────────────────────────────────
         STEP 1 — CHOOSE PLAN
    ───────────────────────────────────────── -->
    <div class="checkout-step-panel active" id="step-1">
      <h4 style="font-family:'Nunito',sans-serif;font-weight:800;margin-bottom:6px;">Choose Your Plan</h4>
      <p style="color:var(--text-muted);font-size:14px;margin-bottom:20px;">Select the product and plan that's right for you.</p>

      <!-- Category tabs -->
      <div class="plan-tabs">
        <?php foreach($catalogue as $key => $cat): ?>
        <button type="button" class="plan-tab-btn <?= $key==='hosting'?'active':'' ?>" onclick="switchTab('<?= $key ?>')">
          <i class="fas <?= $cat['icon'] ?>"></i> <?= $cat['label'] ?>
        </button>
        <?php endforeach; ?>
      </div>

      <!-- ── Web Hosting ── -->
      <div class="plan-tab-content active" id="tab-hosting">
        <div class="row g-4 align-items-stretch">
        <?php
          $h_variants = ['plan-starter','plan-pro','plan-biz'];
          $h_ctaLabels = ['Get Started','Most Popular →','Go Business'];
          foreach($catalogue['hosting']['plans'] as $i => $plan):
            $variant = $h_variants[$i] ?? 'plan-starter';
            $cta     = $h_ctaLabels[$i] ?? 'Select Plan';
        ?>
        <div class="col-lg-4 col-md-6">
          <div class="hplan-card <?= $variant ?> <?= !empty($plan['popular']) ? 'popular-card' : '' ?>"
               id="card-<?= $plan['pid'] ?>"
               onclick="selectPlan(<?= $plan['pid'] ?>,'<?= $plan['name'] ?>','<?= $plan['price'] ?>','product','hosting')">

            <!-- Coloured header band -->
            <div class="hplan-header">
              <div class="hplan-selected-ring"><i class="fas fa-check"></i></div>
              <?php if(!empty($plan['popular'])): ?>
              <div class="hplan-popular-pill"><i class="fas fa-fire me-1"></i>Most Popular</div>
              <?php endif; ?>
              <div class="hplan-tier-icon"><i class="fas <?= $plan['icon'] ?>"></i></div>
              <div class="hplan-name"><?= $plan['name'] ?></div>
              <div class="hplan-tagline"><?= $plan['tagline'] ?></div>
            </div>

            <!-- Body -->
            <div class="hplan-body">
              <div class="hplan-price-row">
                <div class="hplan-price">₹<?= $plan['price'] ?><small><?= $plan['unit'] ?></small></div>
                <div class="hplan-orig">₹<?= $plan['orig'] ?><?= $plan['unit'] ?></div>
              </div>
              <div class="hplan-saving"><i class="fas fa-tag" style="font-size:9px;"></i> Save <?= $plan['saving'] ?>%</div>

              <div class="hplan-divider"></div>

              <ul class="hplan-features">
                <?php foreach($plan['features'] as $f): ?>
                <li>
                  <span class="hplan-feat-icon"><i class="fas fa-check"></i></span>
                  <span><?= $f ?></span>
                </li>
                <?php endforeach; ?>
              </ul>

              <button type="button" class="hplan-btn"><?= $cta ?></button>
            </div>

          </div>
        </div>
        <?php endforeach; ?>
        </div>
      </div>

      <!-- ── VPS Hosting ── -->
      <div class="plan-tab-content" id="tab-vps">
        <div class="row g-3">
        <?php foreach($catalogue['vps']['plans'] as $plan): ?>
        <div class="col-lg-4 col-md-6">
          <div class="plan-card" id="card-vps-<?= $plan['name'] ?>" onclick="selectPlan(<?= $plan['pid'] ?>,'VPS <?= $plan['name'] ?>','<?= $plan['price'] ?>','product','vps')">
            <?php if(!empty($plan['popular'])): ?><span class="popular-badge">Most Popular</span><?php endif; ?>
            <div class="selected-check"><i class="fas fa-check"></i></div>
            <div class="plan-name">VPS <?= $plan['name'] ?></div>
            <div class="plan-orig">₹<?= $plan['orig'] ?><?= $plan['unit'] ?></div>
            <div class="plan-saving"><?= $plan['saving'] ?>% savings</div>
            <div class="plan-price">₹<?= $plan['price'] ?><small><?= $plan['unit'] ?></small></div>
            <ul class="plan-features">
              <?php foreach($plan['features'] as $f): ?>
              <li><i class="fas fa-check-circle"></i> <?= $f ?></li>
              <?php endforeach; ?>
            </ul>
            <button type="button" class="select-btn">Select Plan</button>
          </div>
        </div>
        <?php endforeach; ?>
        </div>
      </div>

      <!-- ── Email Hosting ── -->
      <div class="plan-tab-content" id="tab-email">
        <div class="row g-3">
        <?php foreach($catalogue['email']['plans'] as $plan): ?>
        <div class="col-lg-4 col-md-6">
          <div class="plan-card" id="card-email-<?= $plan['name'] ?>" onclick="selectPlan(<?= $plan['pid'] ?>,'Email <?= $plan['name'] ?>','<?= $plan['price'] ?>','product','email')">
            <?php if(!empty($plan['popular'])): ?><span class="popular-badge">Most Popular</span><?php endif; ?>
            <div class="selected-check"><i class="fas fa-check"></i></div>
            <div class="plan-name">Email <?= $plan['name'] ?></div>
            <div class="plan-orig">₹<?= $plan['orig'] ?><?= $plan['unit'] ?></div>
            <div class="plan-saving"><?= $plan['saving'] ?>% savings</div>
            <div class="plan-price">₹<?= $plan['price'] ?><small><?= $plan['unit'] ?></small></div>
            <ul class="plan-features">
              <?php foreach($plan['features'] as $f): ?>
              <li><i class="fas fa-check-circle"></i> <?= $f ?></li>
              <?php endforeach; ?>
            </ul>
            <button type="button" class="select-btn">Select Plan</button>
          </div>
        </div>
        <?php endforeach; ?>
        </div>
      </div>

      <!-- ── Domain Registration ── -->
      <div class="plan-tab-content" id="tab-domain">
        <div style="background:#f0f7ff;border-radius:12px;padding:20px;border:1.5px solid var(--border);">
          <label class="form-label">Domain Name <span class="req">*</span></label>
          <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-start;">
            <input type="text" id="domain_input" class="form-control" placeholder="yourbusiness" style="flex:1;min-width:180px;"
              oninput="updateDomainPreview()" pattern="[a-zA-Z0-9\-]+">
            <select id="tld_select" class="form-control" style="max-width:140px;" onchange="updateDomainSelection()">
              <?php foreach($catalogue['domain']['tlds'] as $tld): ?>
              <option value="<?= $tld['ext'] ?>" data-price="<?= $tld['price'] ?>"><?= $tld['label'] ?> — ₹<?= $tld['price'] ?>/yr</option>
              <?php endforeach; ?>
            </select>
          </div>
          <div id="domain-preview" style="margin-top:10px;display:none;">
            <span style="font-family:'Nunito',sans-serif;font-weight:800;font-size:18px;color:var(--primary);" id="domain-preview-text"></span>
            <span class="discount-badge ms-2" id="domain-preview-price"></span>
          </div>
          <div class="tld-grid mt-3">
            <?php foreach($catalogue['domain']['tlds'] as $i => $tld): ?>
            <div class="tld-card <?= $i===0?'selected':'' ?>" id="tld-<?= str_replace('.','',ltrim($tld['ext'],'.')) ?>" onclick="selectTLD('<?= $tld['ext'] ?>',<?= $tld['price'] ?>)">
              <div class="tld-ext"><?= $tld['label'] ?></div>
              <div class="tld-price">₹<?= $tld['price'] ?>/yr</div>
              <?php if(!empty($tld['popular'])): ?><div class="tld-popular mt-1">Popular</div><?php endif; ?>
            </div>
            <?php endforeach; ?>
          </div>
          <button type="button" class="btn-next mt-3" id="domainNextBtn" onclick="selectDomainAndNext()" disabled>
            Continue <i class="fas fa-arrow-right"></i>
          </button>
        </div>
      </div>

      <!-- Step 1 bottom nav -->
      <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top" id="step1-nav" style="display:none!important;">
        <div style="font-size:13px;color:var(--text-muted);"><i class="fas fa-lock me-1"></i> Secure &amp; Encrypted Checkout</div>
        <button type="button" class="btn-next" id="step1NextBtn" onclick="goToStep(2)" disabled>
          Continue to Your Details <i class="fas fa-arrow-right"></i>
        </button>
      </div>
    </div>

    <!-- ─────────────────────────────────────────
         STEP 2 — YOUR DETAILS
    ───────────────────────────────────────── -->
    <div class="checkout-step-panel" id="step-2">
      <div class="row g-4">

        <!-- Left: Form -->
        <div class="col-lg-7">
          <h4 style="font-family:'Nunito',sans-serif;font-weight:800;margin-bottom:4px;">Your Details</h4>
          <p style="color:var(--text-muted);font-size:14px;margin-bottom:20px;">Your information will be used to create your <?= SITE_NAME ?> account.</p>

          <?php if($order_error): ?>
          <div class="order-alert"><i class="fas fa-exclamation-circle fa-lg"></i><?= htmlspecialchars($order_error) ?></div>
          <?php endif; ?>

          <!-- Account info -->
          <div class="form-section-title"><i class="fas fa-user me-2"></i>Account Information</div>
          <div class="row g-3">
            <div class="col-sm-6">
              <label class="form-label">First Name <span class="req">*</span></label>
              <input type="text" name="firstname" class="form-control" required value="<?= htmlspecialchars($_POST['firstname']??'') ?>">
            </div>
            <div class="col-sm-6">
              <label class="form-label">Last Name <span class="req">*</span></label>
              <input type="text" name="lastname" class="form-control" required value="<?= htmlspecialchars($_POST['lastname']??'') ?>">
            </div>
            <div class="col-sm-6">
              <label class="form-label">Email Address <span class="req">*</span></label>
              <input type="email" name="email" class="form-control" required value="<?= htmlspecialchars($_POST['email']??'') ?>">
            </div>
            <div class="col-sm-6">
              <label class="form-label">Phone Number <span class="req">*</span></label>
              <input type="tel" name="phone" class="form-control" required placeholder="+91 XXXXX XXXXX" value="<?= htmlspecialchars($_POST['phone']??'') ?>">
            </div>
            <div class="col-sm-6">
              <label class="form-label">Password <span class="req">*</span></label>
              <div style="position:relative;">
                <input type="password" name="password" id="pwdInput" class="form-control" required minlength="8" placeholder="Min. 8 characters">
                <button type="button" onclick="togglePwd()" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--text-muted);cursor:pointer;"><i class="fas fa-eye" id="eyeIcon"></i></button>
              </div>
            </div>
            <div class="col-sm-6" id="hosting-domain-wrap">
              <label class="form-label">Domain for Hosting</label>
              <input type="text" id="hosting_domain_input" class="form-control" placeholder="e.g. yourbusiness.in" oninput="document.getElementById('h_hosting_domain').value=this.value">
            </div>
          </div>

          <!-- Billing cycle (for product plans) -->
          <div id="cycle-wrap">
            <div class="form-section-title mt-3"><i class="fas fa-calendar me-2"></i>Billing Cycle</div>
            <div class="cycle-select">
              <div class="cycle-btn active" id="cycle-monthly" onclick="setCycle('monthly')"><div style="font-size:13px;">Monthly</div><div style="font-size:11px;color:inherit;opacity:.8;" id="cycle-mo-price"></div></div>
              <div class="cycle-btn" id="cycle-annually" onclick="setCycle('annually')"><div style="font-size:13px;">Annually</div><div style="font-size:11px;opacity:.8;">Best Value</div></div>
            </div>
          </div>

          <!-- Address -->
          <div class="form-section-title mt-3"><i class="fas fa-map-marker-alt me-2"></i>Address</div>
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Street Address</label>
              <input type="text" name="address" class="form-control" value="<?= htmlspecialchars($_POST['address']??'') ?>">
            </div>
            <div class="col-sm-6">
              <label class="form-label">City</label>
              <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($_POST['city']??'') ?>">
            </div>
            <div class="col-sm-6">
              <label class="form-label">State</label>
              <input type="text" name="state" class="form-control" value="<?= htmlspecialchars($_POST['state']??'') ?>">
            </div>
            <div class="col-sm-4">
              <label class="form-label">Postcode</label>
              <input type="text" name="postcode" class="form-control" value="<?= htmlspecialchars($_POST['postcode']??'') ?>">
            </div>
            <div class="col-sm-8">
              <label class="form-label">Country</label>
              <select name="country" class="form-control">
                <option value="IN" selected>India</option>
                <option value="US">United States</option>
                <option value="GB">United Kingdom</option>
                <option value="AU">Australia</option>
                <option value="CA">Canada</option>
                <option value="SG">Singapore</option>
                <option value="AE">UAE</option>
              </select>
            </div>
          </div>
        </div>

        <!-- Right: Order Summary -->
        <div class="col-lg-5">
          <div class="order-summary">
            <h5><i class="fas fa-receipt me-2" style="color:var(--primary);"></i>Order Summary</h5>
            <div id="summary-content">
              <div class="summary-placeholder">No plan selected yet.</div>
            </div>
            <!-- Coupon Code -->
            <div class="coupon-wrap">
              <label><i class="fas fa-tag me-1"></i> Promo Code</label>
              <div class="coupon-row">
                <input type="text" id="coupon-input" placeholder="ENTER CODE" maxlength="30" autocomplete="off">
                <button type="button" class="coupon-apply-btn" id="coupon-apply-btn" onclick="applyCoupon()">Apply</button>
              </div>
              <div class="coupon-msg" id="coupon-msg"></div>
            </div>

            <div class="mt-3 pt-2" style="border-top:1.5px solid var(--border);">
              <div style="font-size:12px;color:var(--text-muted);"><i class="fas fa-lock me-1" style="color:var(--primary);"></i> Secure SSL-encrypted checkout</div>
              <div style="font-size:12px;color:var(--text-muted);margin-top:5px;"><i class="fas fa-headset me-1" style="color:var(--primary);"></i> 24/7 Support available</div>
              <div style="font-size:12px;color:var(--text-muted);margin-top:5px;"><i class="fas fa-shield-alt me-1" style="color:var(--primary);"></i> 100-Day Money-Back Guarantee</div>
            </div>
          </div>
        </div>
      </div>

      <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top flex-wrap gap-2">
        <button type="button" class="btn-back" onclick="goToStep(1)"><i class="fas fa-arrow-left me-1"></i> Back</button>
        <button type="button" class="btn-next" onclick="goToStep(3)">
          Review Order <i class="fas fa-arrow-right"></i>
        </button>
      </div>
    </div>

    <!-- ─────────────────────────────────────────
         STEP 3 — REVIEW & PAY
    ───────────────────────────────────────── -->
    <div class="checkout-step-panel" id="step-3">
      <h4 style="font-family:'Nunito',sans-serif;font-weight:800;margin-bottom:4px;">Review Your Order</h4>
      <p style="color:var(--text-muted);font-size:14px;margin-bottom:20px;">Please review everything before placing your order.</p>

      <div class="row g-4">
        <div class="col-lg-7">

          <div class="review-box">
            <h6><i class="fas fa-box me-1"></i> Your Plan</h6>
            <div class="review-item"><span>Plan</span><strong id="rv-plan">—</strong></div>
            <div class="review-item"><span>Billing</span><strong id="rv-cycle">—</strong></div>
            <div class="review-item" id="rv-domain-row" style="display:none;"><span>Domain</span><strong id="rv-domain">—</strong></div>
          </div>

          <div class="review-box">
            <h6><i class="fas fa-user me-1"></i> Account Details</h6>
            <div class="review-item"><span>Name</span><strong id="rv-name">—</strong></div>
            <div class="review-item"><span>Email</span><strong id="rv-email">—</strong></div>
            <div class="review-item"><span>Phone</span><strong id="rv-phone">—</strong></div>
          </div>

          <div id="rv-coupon-row" class="review-item" style="display:none;color:#16a34a;">
            <span><i class="fas fa-tag me-1"></i>Promo (<span id="rv-coupon-code"></span>)</span>
            <strong id="rv-coupon-saving" style="color:#16a34a;"></strong>
          </div>

          <div class="review-total">
            <div><div class="label">Total Due Today</div><div style="font-size:12px;opacity:.75;">Redirecting to secure payment</div></div>
            <div class="amount" id="rv-total">₹—</div>
          </div>

          <div style="font-size:12px;color:var(--text-muted);margin-top:12px;">
            By placing this order you agree to our <a href="tos.php">Terms of Service</a> and <a href="privacy-policy.php">Privacy Policy</a>.
          </div>
        </div>

        <div class="col-lg-5">
          <div style="background:#f0f7ff;border:1.5px solid var(--border);border-radius:12px;padding:20px;text-align:center;">
            <i class="fas fa-shield-alt" style="font-size:40px;color:var(--primary);margin-bottom:12px;display:block;"></i>
            <div style="font-weight:700;margin-bottom:6px;">100% Secure Payment</div>
            <div style="font-size:13px;color:var(--text-muted);">You'll be redirected to our secure payment gateway after placing your order.</div>
            <div style="margin-top:14px;display:flex;flex-wrap:wrap;gap:6px;justify-content:center;">
              <span style="background:#fff;border:1px solid var(--border);border-radius:6px;padding:4px 10px;font-size:12px;font-weight:700;color:var(--text-muted);">UPI</span>
              <span style="background:#fff;border:1px solid var(--border);border-radius:6px;padding:4px 10px;font-size:12px;font-weight:700;color:var(--text-muted);">Net Banking</span>
              <span style="background:#fff;border:1px solid var(--border);border-radius:6px;padding:4px 10px;font-size:12px;font-weight:700;color:var(--text-muted);">Cards</span>
              <span style="background:#fff;border:1px solid var(--border);border-radius:6px;padding:4px 10px;font-size:12px;font-weight:700;color:var(--text-muted);">Wallets</span>
            </div>
          </div>
        </div>
      </div>

      <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top flex-wrap gap-2">
        <button type="button" class="btn-back" onclick="goToStep(2)"><i class="fas fa-arrow-left me-1"></i> Back</button>
        <button type="submit" class="btn-place-order" style="width:auto;">
          <i class="fas fa-lock"></i> Place Order &amp; Pay Securely
        </button>
      </div>
    </div>

  </div><!-- /.checkout-card -->
</form>

</div></div></div>
</div>

<script>
/* ═══════════════════════════════════════════════════════════
   STATE
═══════════════════════════════════════════════════════════ */
var CS = {
  step: 1,
  plan: { pid: 0, name: '', price: '', type: '', category: '' },
  cycle: 'monthly',
  domainTld: '.in',
  domainTldPrice: <?= PRICE_IN ?>,
  coupon: { valid: false, code: '', type: '', value: 0 }
};

/* ═══════════════════════════════════════════════════════════
   STEP NAVIGATION
═══════════════════════════════════════════════════════════ */
function goToStep(n) {
  if (n === 2 && CS.plan.pid === 0 && CS.plan.type !== 'domain') {
    showToast('Please select a plan first.'); return;
  }
  if (n === 3) {
    if (!validateStep2()) return;
    fillReview();
  }
  document.querySelectorAll('.checkout-step-panel').forEach(function(p){ p.classList.remove('active'); });
  document.getElementById('step-' + n).classList.add('active');

  // Update indicators
  for (var i = 1; i <= 3; i++) {
    var ind = document.getElementById('indicator-' + i);
    ind.classList.remove('active','done');
    var num = ind.querySelector('.step-num');
    var chk = ind.querySelector('.fa-check');
    if (i < n) {
      ind.classList.add('done');
      if(num) num.style.display = 'none';
      if(chk) chk.style.display = 'inline';
    } else if (i === n) {
      ind.classList.add('active');
      if(num) num.style.display = 'inline';
      if(chk) chk.style.display = 'none';
    } else {
      if(num) num.style.display = 'inline';
      if(chk) chk.style.display = 'none';
    }
  }
  CS.step = n;
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

/* ═══════════════════════════════════════════════════════════
   TAB SWITCHING
═══════════════════════════════════════════════════════════ */
function switchTab(key) {
  document.querySelectorAll('.plan-tab-btn').forEach(function(b){ b.classList.remove('active'); });
  document.querySelectorAll('.plan-tab-content').forEach(function(c){ c.classList.remove('active'); });
  event.currentTarget.classList.add('active');
  document.getElementById('tab-' + key).classList.add('active');

  // Show/hide domain-specific next btn vs product next btn
  var step1Nav = document.getElementById('step1-nav');
  var domainNext = document.getElementById('domainNextBtn').closest('button') ||
                   document.getElementById('domainNextBtn');
  if (key === 'domain') {
    step1Nav.style.setProperty('display','none','important');
  } else {
    step1Nav.style.removeProperty('display');
    checkStep1();
  }
}

/* ═══════════════════════════════════════════════════════════
   PLAN SELECTION
═══════════════════════════════════════════════════════════ */
function selectPlan(pid, name, price, type, category) {
  // Deselect all cards (both styles)
  document.querySelectorAll('.plan-card, .hplan-card').forEach(function(c){ c.classList.remove('selected'); });
  // Select clicked card
  var card = document.querySelector('[onclick*="' + pid + ',' + "'" + name + "'"]');
  if (card) card.classList.add('selected');

  CS.plan = { pid: pid, name: name, price: price, type: type, category: category };

  // Update hidden fields
  document.getElementById('h_pid').value          = pid;
  document.getElementById('h_order_type').value   = 'product';
  document.getElementById('h_billing_cycle').value = CS.cycle;

  // Show hosting domain field only for hosting/email
  var hdWrap = document.getElementById('hosting-domain-wrap');
  hdWrap.style.display = (category === 'vps') ? 'none' : 'block';

  updateSummary();
  checkStep1();
  document.getElementById('step1-nav').style.removeProperty('display');
  setTimeout(function(){ goToStep(2); }, 320);
}

function checkStep1() {
  var btn = document.getElementById('step1NextBtn');
  if (btn) btn.disabled = (CS.plan.pid === 0);
}

/* ═══════════════════════════════════════════════════════════
   DOMAIN SELECTION
═══════════════════════════════════════════════════════════ */
function selectTLD(ext, price) {
  CS.domainTld      = ext;
  CS.domainTldPrice = price;
  document.getElementById('h_domain_tld').value = ext;
  // Deselect all tld cards
  document.querySelectorAll('.tld-card').forEach(function(c){ c.classList.remove('selected'); });
  var key = ext.replace(/\./g,'').replace(/^in/,'in');
  // Find by data or iterate
  document.querySelectorAll('.tld-card').forEach(function(c){
    if (c.getAttribute('onclick') && c.getAttribute('onclick').indexOf("'" + ext + "'") !== -1) {
      c.classList.add('selected');
    }
  });
  updateDomainPreview();
}

function updateDomainPreview() {
  var name = document.getElementById('domain_input').value.trim();
  var prev = document.getElementById('domain-preview');
  var txt  = document.getElementById('domain-preview-text');
  var price= document.getElementById('domain-preview-price');
  var btn  = document.getElementById('domainNextBtn');
  if (name.length > 1) {
    txt.textContent  = name + CS.domainTld;
    price.textContent = '₹' + CS.domainTldPrice + '/yr';
    prev.style.display = 'block';
    btn.disabled = false;
  } else {
    prev.style.display = 'none';
    btn.disabled = true;
  }
}

function updateDomainSelection() {
  var sel = document.getElementById('tld_select');
  var opt = sel.options[sel.selectedIndex];
  selectTLD(opt.value, opt.getAttribute('data-price'));
}

function selectDomainAndNext() {
  var name = document.getElementById('domain_input').value.trim();
  if (!name) { showToast('Enter a domain name first.'); return; }
  CS.plan = { pid: 0, name: name + CS.domainTld, price: CS.domainTldPrice, type: 'domain', category: 'domain' };
  document.getElementById('h_order_type').value  = 'domain';
  document.getElementById('h_domain_name').value = name;
  document.getElementById('h_domain_tld').value  = CS.domainTld;
  document.getElementById('hosting-domain-wrap').style.display = 'none';
  document.getElementById('cycle-wrap').style.display = 'none';
  updateSummary();
  goToStep(2);
}

/* ═══════════════════════════════════════════════════════════
   BILLING CYCLE
═══════════════════════════════════════════════════════════ */
function setCycle(cycle) {
  CS.cycle = cycle;
  document.getElementById('h_billing_cycle').value = cycle;
  document.querySelectorAll('.cycle-btn').forEach(function(b){ b.classList.remove('active'); });
  document.getElementById('cycle-' + cycle).classList.add('active');
  updateSummary();
}

/* ═══════════════════════════════════════════════════════════
   COUPON
═══════════════════════════════════════════════════════════ */
function applyCoupon() {
  var input = document.getElementById('coupon-input');
  var btn   = document.getElementById('coupon-apply-btn');
  var msg   = document.getElementById('coupon-msg');
  var code  = input.value.trim().toUpperCase();

  if (!code) { showCouponMsg('err', 'Please enter a promo code.'); return; }

  // If already applied and clicking again — treat as remove
  if (CS.coupon.valid && CS.coupon.code === code) {
    removeCoupon(); return;
  }

  btn.disabled = true;
  btn.textContent = '...';
  msg.className = 'coupon-msg';
  input.className = '';

  var url = 'order.php?_api=validate_coupon&code=' + encodeURIComponent(code) +
            '&pid=' + CS.plan.pid + '&cycle=' + CS.cycle;

  fetch(url)
    .then(function(r){ return r.json(); })
    .then(function(d) {
      btn.disabled = false;
      if (d.valid) {
        CS.coupon = { valid: true, code: d.code, type: d.type, value: d.value };
        document.getElementById('h_promocode').value = d.code;
        input.className = 'coupon-valid';
        input.readOnly  = true;
        btn.textContent = 'Remove';
        btn.style.background = '#dc2626';
        btn.onclick = removeCoupon;
        showCouponMsg('ok', '<i class="fas fa-check-circle me-1"></i>' + d.message);
        updateSummary();
      } else {
        CS.coupon = { valid: false, code: '', type: '', value: 0 };
        document.getElementById('h_promocode').value = '';
        input.className = 'coupon-invalid';
        btn.textContent = 'Apply';
        showCouponMsg('err', d.message);
        updateSummary();
      }
    })
    .catch(function() {
      btn.disabled = false;
      btn.textContent = 'Apply';
      showCouponMsg('err', 'Could not validate code. Please try again.');
    });
}

function removeCoupon() {
  CS.coupon = { valid: false, code: '', type: '', value: 0 };
  document.getElementById('h_promocode').value = '';
  var input = document.getElementById('coupon-input');
  var btn   = document.getElementById('coupon-apply-btn');
  input.value    = '';
  input.readOnly = false;
  input.className = '';
  btn.textContent = 'Apply';
  btn.style.background = '';
  btn.disabled = false;
  btn.onclick = applyCoupon;
  document.getElementById('coupon-msg').className = 'coupon-msg';
  updateSummary();
}

function showCouponMsg(type, html) {
  var el = document.getElementById('coupon-msg');
  el.className = 'coupon-msg ' + type;
  el.innerHTML = html;
}

function calcDiscount(basePrice) {
  if (!CS.coupon.valid) return 0;
  if (CS.coupon.type === 'Percentage') {
    return Math.round((parseFloat(basePrice) * CS.coupon.value / 100) * 100) / 100;
  }
  return Math.min(parseFloat(CS.coupon.value), parseFloat(basePrice));
}

/* ═══════════════════════════════════════════════════════════
   ORDER SUMMARY
═══════════════════════════════════════════════════════════ */
function updateSummary() {
  var box = document.getElementById('summary-content');
  if (!CS.plan.pid && CS.plan.type !== 'domain') {
    box.innerHTML = '<div class="summary-placeholder">No plan selected yet.</div>'; return;
  }
  var cycleLabel  = CS.cycle === 'monthly' ? 'Monthly' : 'Annually';
  var unit        = CS.plan.category === 'domain' ? '/yr' : (CS.cycle === 'monthly' ? '/mo' : '/yr');
  var basePrice   = parseFloat(CS.plan.price);
  var discount    = calcDiscount(basePrice);
  var finalPrice  = Math.max(0, basePrice - discount);

  var html = '<div class="summary-row"><span>Plan</span><strong>' + CS.plan.name + '</strong></div>' +
    (CS.plan.type !== 'domain' ? '<div class="summary-row"><span>Billing</span><strong>' + cycleLabel + '</strong></div>' : '');

  if (CS.coupon.valid && discount > 0) {
    html += '<div class="summary-row" style="color:#16a34a;"><span><i class="fas fa-tag me-1"></i>Promo</span><strong style="color:#16a34a;">−₹' + discount.toFixed(0) + '</strong></div>';
  }

  html += '<div class="summary-row"><span>&nbsp;</span></div>' +
    '<div class="summary-row"><span>Total</span><strong style="color:var(--primary);font-size:16px;">₹' + finalPrice.toFixed(0) + unit + '</strong></div>';

  box.innerHTML = html;
}

/* ═══════════════════════════════════════════════════════════
   STEP 2 VALIDATION
═══════════════════════════════════════════════════════════ */
function validateStep2() {
  var fields = ['firstname','lastname','email','phone'];
  var form   = document.getElementById('checkoutForm');
  for (var i = 0; i < fields.length; i++) {
    var el = form.elements[fields[i]];
    if (!el || !el.value.trim()) {
      showToast('Please fill in all required fields.');
      el && el.focus();
      return false;
    }
  }
  var pwd = document.getElementById('pwdInput');
  if (!pwd.value || pwd.value.length < 8) {
    showToast('Password must be at least 8 characters.');
    pwd.focus();
    return false;
  }
  var email = form.elements['email'];
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
    showToast('Please enter a valid email address.');
    email.focus();
    return false;
  }
  return true;
}

/* ═══════════════════════════════════════════════════════════
   REVIEW FILL
═══════════════════════════════════════════════════════════ */
function fillReview() {
  var f = document.getElementById('checkoutForm').elements;
  var cycleLabel  = CS.cycle === 'monthly' ? 'Monthly' : 'Annually';
  var unit        = CS.plan.type === 'domain' ? '/yr' : (CS.cycle==='monthly' ? '/mo' : '/yr');
  var basePrice   = parseFloat(CS.plan.price);
  var discount    = calcDiscount(basePrice);
  var finalPrice  = Math.max(0, basePrice - discount);

  document.getElementById('rv-plan').textContent  = CS.plan.name;
  document.getElementById('rv-cycle').textContent = CS.plan.type === 'domain' ? '1 Year Registration' : cycleLabel;
  document.getElementById('rv-total').textContent = '₹' + finalPrice.toFixed(0) + unit;
  document.getElementById('rv-name').textContent  = (f['firstname'].value + ' ' + f['lastname'].value).trim();
  document.getElementById('rv-email').textContent = f['email'].value;
  document.getElementById('rv-phone').textContent = f['phone'].value || '—';

  var domRow = document.getElementById('rv-domain-row');
  var hdInput = document.getElementById('hosting_domain_input');
  if (hdInput && hdInput.value.trim()) {
    domRow.style.display = 'flex';
    document.getElementById('rv-domain').textContent = hdInput.value.trim();
  } else if (CS.plan.type === 'domain') {
    domRow.style.display = 'flex';
    document.getElementById('rv-domain').textContent = CS.plan.name;
  } else {
    domRow.style.display = 'none';
  }

  var couponRow = document.getElementById('rv-coupon-row');
  if (CS.coupon.valid && discount > 0) {
    couponRow.style.display = 'flex';
    document.getElementById('rv-coupon-code').textContent  = CS.coupon.code;
    document.getElementById('rv-coupon-saving').textContent = '−₹' + discount.toFixed(0);
  } else {
    couponRow.style.display = 'none';
  }
}

/* ═══════════════════════════════════════════════════════════
   HELPERS
═══════════════════════════════════════════════════════════ */
function togglePwd() {
  var i = document.getElementById('pwdInput');
  var eye = document.getElementById('eyeIcon');
  i.type = (i.type === 'password') ? 'text' : 'password';
  eye.className = (i.type === 'password') ? 'fas fa-eye' : 'fas fa-eye-slash';
}

function showToast(msg) {
  var t = document.getElementById('co-toast');
  if (!t) {
    t = document.createElement('div');
    t.id = 'co-toast';
    t.style.cssText = 'position:fixed;bottom:80px;left:50%;transform:translateX(-50%);background:#1a56db;color:#fff;padding:11px 24px;border-radius:30px;font-size:14px;font-weight:700;z-index:9999;box-shadow:0 4px 20px rgba(0,0,0,.2);transition:opacity .3s;';
    document.body.appendChild(t);
  }
  t.textContent = msg;
  t.style.opacity = '1';
  clearTimeout(t._timer);
  t._timer = setTimeout(function(){ t.style.opacity = '0'; }, 3000);
}

// On load — if POST returned an error, go to step 2
<?php if($order_error): ?>
window.addEventListener('DOMContentLoaded', function(){
  // Restore plan state from hidden fields if available
  goToStep(2);
});
<?php endif; ?>

// Init
checkStep1();
</script>

<?php include 'includes/footer.php'; ?>
