<?php
require_once __DIR__.'/../config/config.php';
require_user();
$U = current_user();
$sid = (int)($_GET['id'] ?? $_POST['id'] ?? 0);

$s = $pdo->prepare("SELECT * FROM services WHERE id=? AND kind='custom'");
$s->execute([$sid]);
$svc = $s->fetch();
if (!$svc) { redirect('services.php'); }
if ($svc['status'] !== 'open') { flash_set('err','এই সার্ভিস এখন বন্ধ।'); redirect('services.php'); }

$f = $pdo->prepare("SELECT * FROM service_fields WHERE service_id=? ORDER BY position, id");
$f->execute([$sid]); $fields = $f->fetchAll();

$err = null;

if ($_SERVER['REQUEST_METHOD']==='POST') {
    csrf_check();
    $data = [];
    $override_price = null; // if any selected option has a non-zero price → it overrides
    foreach ($fields as $fi) {
        $key = 'f_'.$fi['id'];
        $v = trim($_POST[$key] ?? '');
        if ($fi['required'] && $v === '') { $err = $fi['label'].' পূরণ করুন'; break; }
        $data[$fi['label']] = $v;
        if ($fi['field_type']==='select' && $v !== '' && !empty($fi['options_json'])) {
            $opts = json_decode($fi['options_json'], true) ?: [];
            foreach ($opts as $op) {
                if (($op['name']??'') === $v) {
                    $p = (float)($op['price'] ?? 0);
                    // Option price > 0 → becomes the service price (override, not addition).
                    // Option price == 0 → use service base price.
                    if ($p > 0) $override_price = $p;
                    break;
                }
            }
        }
    }

    if (!$err) {
        $final_price = $override_price !== null ? $override_price : (float)$svc['price'];
        if ((float)$U['balance'] < $final_price) {
            $err = 'ব্যালেন্স যথেষ্ট নয় ('.money($final_price).')। রিচার্জ করুন।';
        } else {
            // Deduct on placement
            $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$final_price, $U['id']]);
            log_txn($pdo, $U['id'], 'debit', $final_price, '', 'Service: '.$svc['name']);

            // Auto-access?
            $auto = trim($svc['auto_access_link'] ?? '');
            if ($auto !== '') {
                $pdo->prepare("INSERT INTO orders(user_id, service_id, price, status, custom_data, delivery_type, delivery_content, completed_at, user_notified)
                               VALUES(?,?,?, 'completed', ?, 'text', ?, NOW(), 0)")
                    ->execute([$U['id'], $sid, $final_price, json_encode($data, JSON_UNESCAPED_UNICODE), $auto]);
            } else {
                $pdo->prepare("INSERT INTO orders(user_id, service_id, price, status, custom_data)
                               VALUES(?,?,?, 'pending', ?)")
                    ->execute([$U['id'], $sid, $final_price, json_encode($data, JSON_UNESCAPED_UNICODE)]);
            }
            $oid = (int)$pdo->lastInsertId();

            // Telegram notification (skips Auto Server Copy / API services internally)
            try { tg_notify_new_order($pdo, $oid); } catch (Throwable $e) { /* ignore */ }

            redirect('order_view.php?id='.$oid);
        }
    }
}

$PAGE_TITLE = 'অর্ডার: '.$svc['name'];
require __DIR__.'/_layout.php';
?>
<h2 style="margin-bottom:14px">🛒 <?=e($svc['name'])?></h2>
<div class="card">
  <?php if($err): ?><div class="alert err"><?=e($err)?></div><?php endif; ?>
  <p style="color:#64748b"><?=e($svc['description'])?></p>
  <p><b>মূল্য:</b> <span style="color:#6366f1;font-weight:700"><?=money($svc['price'])?></span> <small style="color:#64748b">(সিলেক্ট অপশনে আলাদা মূল্য থাকলে সেটিই প্রযোজ্য হবে)</small></p>

  <form method="post"><?=csrf_field()?>
    <input type="hidden" name="id" value="<?=$sid?>">
    <?php foreach($fields as $fi):
      $opts = $fi['field_type']==='select' && $fi['options_json'] ? (json_decode($fi['options_json'],true)?:[]) : [];
    ?>
      <div class="field">
        <label><?=e($fi['label'])?> <?=$fi['required']?'<span style="color:#dc2626">*</span>':''?></label>
        <?php if($fi['field_type']==='select'): ?>
          <select class="input" name="f_<?=$fi['id']?>" <?=$fi['required']?'required':''?>>
            <option value="">-- সিলেক্ট --</option>
            <?php foreach($opts as $op): ?>
              <option value="<?=e($op['name'])?>"><?=e($op['name'])?><?=!empty($op['price'])?' ('.money($op['price']).')':''?></option>
            <?php endforeach; ?>
          </select>
        <?php else: ?>
          <input class="input" name="f_<?=$fi['id']?>" placeholder="<?=e($fi['placeholder'])?>" <?=$fi['required']?'required':''?>>
        <?php endif; ?>
      </div>
    <?php endforeach; ?>

    <button class="btn">✅ অর্ডার প্লেস করুন</button>
    <a class="btn ghost" href="services.php">বাতিল</a>
  </form>
</div>
<?php require __DIR__.'/_footer.php';
