<?php
// ⚠️ POST handle করতে হবে layout require এর আগে (redirect header issue)
require_once __DIR__.'/../config/config.php';
require_admin();

// ---- POST: create / update service (with custom fields) ----
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='save_service') {
    csrf_check();
    $id       = (int)($_POST['id']??0);
    $name     = trim($_POST['name']??'');
    $desc     = trim($_POST['description']??'');
    $kind     = ($_POST['kind']??'custom')==='api' ? 'api' : 'custom';
    $api_id   = $kind==='api' ? (int)($_POST['api_id']??0) : null;
    $price    = (float)($_POST['price']??0);
    $pinned   = isset($_POST['pinned']) ? 1 : 0;
    $status   = in_array($_POST['status']??'open',['open','closed','hidden'],true) ? $_POST['status'] : 'open';
    $active   = $status==='hidden' ? 0 : 1; // keep legacy `active` in sync
    $auto     = trim($_POST['auto_access_link']??'');
    $position = (int)($_POST['position']??0);

    // ---- Handle service image upload (optional) ----
    $existing = null;
    if ($id) {
        $qx = $pdo->prepare("SELECT image FROM services WHERE id=?");
        $qx->execute([$id]); $rx = $qx->fetch();
        $existing = $rx ? ($rx['image'] ?? null) : null;
    }
    $image = $existing;
    $img_dir = __DIR__.'/../uploads/services';
    if (!empty($_POST['remove_image']) && $existing) {
        $fp = $img_dir.'/'.$existing;
        if (is_file($fp)) @unlink($fp);
        $image = null;
    }
    if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','gif','webp'];
        if (in_array($ext, $allowed, true)) {
            @mkdir($img_dir, 0775, true);
            $safe = 'svc_'.time().'_'.bin2hex(random_bytes(4)).'.'.$ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $img_dir.'/'.$safe)) {
                // delete previous image
                if ($existing) {
                    $fp = $img_dir.'/'.$existing;
                    if (is_file($fp)) @unlink($fp);
                }
                $image = $safe;
            }
        }
    }

    if ($id) {
        $pdo->prepare("UPDATE services SET name=?,description=?,api_id=?,kind=?,price=?,active=?,pinned=?,status=?,auto_access_link=?,position=?,image=? WHERE id=?")
            ->execute([$name,$desc,$api_id,$kind,$price,$active,$pinned,$status,$auto,$position,$image,$id]);
        $sid = $id;
    } else {
        $pdo->prepare("INSERT INTO services(name,description,api_id,kind,price,active,pinned,status,auto_access_link,position,image) VALUES(?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$name,$desc,$api_id,$kind,$price,$active,$pinned,$status,$auto,$position,$image]);
        $sid = (int)$pdo->lastInsertId();
    }

    // Save custom form fields (only for kind=custom)
    $pdo->prepare("DELETE FROM service_fields WHERE service_id=?")->execute([$sid]);
    if ($kind==='custom' && !empty($_POST['fields']) && is_array($_POST['fields'])) {
        $pos = 0;
        $ins = $pdo->prepare("INSERT INTO service_fields(service_id,position,label,field_type,placeholder,required,options_json) VALUES(?,?,?,?,?,?,?)");
        foreach ($_POST['fields'] as $f) {
            $lbl = trim($f['label']??'');
            if ($lbl==='') continue;
            $ft  = ($f['type']??'text')==='select' ? 'select' : 'text';
            $ph  = trim($f['placeholder']??'');
            $req = !empty($f['required']) ? 1 : 0;
            $opts = null;
            if ($ft==='select' && !empty($f['options']) && is_array($f['options'])) {
                $O = [];
                foreach ($f['options'] as $op) {
                    $on = trim($op['name']??'');
                    if ($on==='') continue;
                    $O[] = ['name'=>$on, 'price'=>(float)($op['price']??0)];
                }
                $opts = json_encode($O, JSON_UNESCAPED_UNICODE);
            }
            $ins->execute([$sid,$pos++,$lbl,$ft,$ph,$req,$opts]);
        }
    }
    redirect('services.php');
}

if (isset($_GET['del'])) {
    $__did = (int)$_GET['del'];
    $qi = $pdo->prepare("SELECT image FROM services WHERE id=?");
    $qi->execute([$__did]); $ri = $qi->fetch();
    if ($ri && !empty($ri['image'])) {
        $fp = __DIR__.'/../uploads/services/'.$ri['image'];
        if (is_file($fp)) @unlink($fp);
    }
    $pdo->prepare("DELETE FROM service_fields WHERE service_id=?")->execute([$__did]);
    $pdo->prepare("DELETE FROM services WHERE id=?")->execute([$__did]);
    redirect('services.php');
}

$PAGE_TITLE='Services'; require __DIR__.'/_layout.php';

$edit=null; $edit_fields=[];
if (isset($_GET['edit'])) {
    $s = $pdo->prepare("SELECT * FROM services WHERE id=?"); $s->execute([(int)$_GET['edit']]); $edit = $s->fetch();
    if ($edit) {
        $f = $pdo->prepare("SELECT * FROM service_fields WHERE service_id=? ORDER BY position, id");
        $f->execute([(int)$edit['id']]);
        $edit_fields = $f->fetchAll();
    }
}

$apis = $pdo->query("SELECT * FROM apis WHERE active=1")->fetchAll();
$rows = $pdo->query("SELECT s.*, a.name AS api_name FROM services s LEFT JOIN apis a ON a.id=s.api_id ORDER BY s.pinned DESC, s.position, s.id DESC")->fetchAll();
?>
<style>
.svc-fields{border:1px dashed #cbd5e1;border-radius:10px;padding:12px;background:#f8fafc}
.svc-field-item{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:10px;margin-bottom:10px}
.svc-field-row{display:grid;grid-template-columns:1fr 160px 1fr auto;gap:8px;align-items:center}
.svc-opt-row{display:grid;grid-template-columns:1fr 120px auto;gap:6px;margin-top:6px}
.chip{display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;font-weight:600}
.chip.api{background:#e0e7ff;color:#3730a3}
.chip.custom{background:#dcfce7;color:#166534}
.chip.pinned{background:#fef3c7;color:#92400e}
.chip.closed{background:#fee2e2;color:#991b1b}
.chip.hidden{background:#e2e8f0;color:#475569}
</style>

<h2 style="margin-bottom:14px">🎯 সার্ভিস</h2>

<div class="card" style="margin-bottom:20px">
<h3><?=$edit?'✏️ Edit':'➕ নতুন'?> Service</h3>
<form method="post" id="svcForm" enctype="multipart/form-data"><?=csrf_field()?>
<input type="hidden" name="action" value="save_service">
<input type="hidden" name="id" value="<?=e($edit['id']??'')?>">

<div class="grid g2">
  <div class="field"><label>নাম</label>
    <input class="input" name="name" value="<?=e($edit['name']??'')?>" required></div>

  <div class="field"><label>মূল্য (ডিফল্ট)</label>
    <input class="input" name="price" type="number" step="0.01" value="<?=e($edit['price']??'5')?>" required></div>

  <div class="field"><label>ধরন</label>
    <select class="input" name="kind" id="svcKind" onchange="toggleKind()">
      <option value="custom" <?=($edit['kind']??'custom')==='custom'?'selected':''?>>কাস্টম সার্ভিস (এডমিন সম্পাদন)</option>
      <option value="api" <?=($edit['kind']??'')==='api'?'selected':''?>>API সার্ভিস (Auto Server Copy)</option>
    </select>
    <small style="color:#64748b">API সার্ভিস কেবল Auto Server Copy পেজে দেখাবে, সার্ভিস অপশনে না।</small>
  </div>

  <div class="field" id="apiPicker">
    <label>API</label>
    <select name="api_id" class="input">
      <option value="">-- নেই --</option>
      <?php foreach($apis as $a):?>
        <option value="<?=$a['id']?>" <?=($edit['api_id']??0)==$a['id']?'selected':''?>><?=e($a['name'])?></option>
      <?php endforeach;?>
    </select>
  </div>

  <div class="field"><label>স্ট্যাটাস</label>
    <select class="input" name="status">
      <?php $st=$edit['status']??'open'; ?>
      <option value="open" <?=$st==='open'?'selected':''?>>চালু</option>
      <option value="closed" <?=$st==='closed'?'selected':''?>>বন্ধ (অর্ডার নেওয়া যাবে না)</option>
      <option value="hidden" <?=$st==='hidden'?'selected':''?>>হাইড (ইউজার দেখবে না)</option>
    </select></div>

  <div class="field"><label style="display:flex;gap:6px;align-items:center;margin-top:22px">
    <input type="checkbox" name="pinned" <?=!empty($edit['pinned'])?'checked':''?>> পিন করুন (উপরে দেখাবে)
  </label></div>

  <div class="field" style="grid-column:1/-1"><label>বর্ণনা</label>
    <textarea class="input" name="description" rows="2"><?=e($edit['description']??'')?></textarea></div>

  <div class="field" style="grid-column:1/-1"><label>অটো এক্সেস লিংক / টেক্সট (ঐচ্ছিক)</label>
    <textarea class="input" name="auto_access_link" rows="2" placeholder="এখানে লিংক/টেক্সট দিলে অর্ডার প্লেস করার সাথে সাথে ইউজার পেয়ে যাবে (auto delivered)"><?=e($edit['auto_access_link']??'')?></textarea></div>

  <div class="field" style="grid-column:1/-1"><label>সার্ভিস ছবি (ঐচ্ছিক)</label>
    <?php if(!empty($edit['image'])): ?>
      <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
        <img src="../uploads/services/<?=e($edit['image'])?>" alt="" style="width:80px;height:80px;object-fit:cover;border-radius:8px;border:1px solid #e2e8f0">
        <label style="display:flex;gap:6px;align-items:center;font-size:13px;color:#dc2626">
          <input type="checkbox" name="remove_image" value="1"> ছবি রিমুভ করুন
        </label>
      </div>
    <?php endif; ?>
    <input class="input" type="file" name="image" accept="image/*">
    <small style="color:#64748b">jpg / png / gif / webp। ছবি না দিলে ডিফল্ট ডিজাইনেই দেখাবে।</small>
  </div>
</div>

<hr style="margin:20px 0">
<div style="display:flex;justify-content:space-between;align-items:center">
  <h3 style="margin:0">📝 ফর্ম ফিল্ড (কাস্টম সার্ভিসের জন্য)</h3>
  <button type="button" class="btn ghost" onclick="addField()">+ ফিল্ড যোগ</button>
</div>
<p style="color:#64748b;font-size:13px;margin:6px 0 10px">সিলেক্ট টাইপে অপশনের ডানপাশে যে মূল্য দিবেন সেটিই ঐ অপশনের চূড়ান্ত মূল্য হবে (বেস মূল্য override হবে)। মূল্য শূন্য/খালি রাখলে সার্ভিসের ডিফল্ট মূল্য প্রযোজ্য হবে।</p>

<div class="svc-fields" id="fieldsWrap"></div>

<div style="margin-top:14px">
  <button class="btn"><?=$edit?'আপডেট':'যোগ করুন'?></button>
  <?php if($edit):?><a class="btn ghost" href="services.php">বাতিল</a><?php endif;?>
</div>
</form>
</div>

<table><thead><tr><th>#</th><th>ছবি</th><th>নাম</th><th>ধরন</th><th>মূল্য</th><th>স্ট্যাটাস</th><th>API</th><th>Actions</th></tr></thead><tbody>
<?php foreach($rows as $r):?>
<tr>
  <td>#<?=$r['id']?></td>
  <td><?php if(!empty($r['image'])): ?><img src="../uploads/services/<?=e($r['image'])?>" alt="" style="width:44px;height:44px;object-fit:cover;border-radius:6px;border:1px solid #e2e8f0"><?php else: ?><span style="color:#94a3b8">—</span><?php endif; ?></td>
  <td>
    <b><?=e($r['name'])?></b>
    <?php if(!empty($r['pinned'])):?><span class="chip pinned">📌 পিন</span><?php endif;?>
  </td>
  <td><span class="chip <?=e($r['kind']??'custom')?>"><?=($r['kind']??'custom')==='api'?'API':'কাস্টম'?></span></td>
  <td><?=money($r['price'])?></td>
  <td>
    <?php $st=$r['status']??'open';
      if($st==='open') echo '<span class="chip pinned" style="background:#dcfce7;color:#166534">চালু</span>';
      elseif($st==='closed') echo '<span class="chip closed">বন্ধ</span>';
      else echo '<span class="chip hidden">হাইড</span>';
    ?>
  </td>
  <td><?=e($r['api_name']??'—')?></td>
  <td>
    <a class="btn sm" href="?edit=<?=$r['id']?>">✏️</a>
    <a class="btn sm danger" href="?del=<?=$r['id']?>" onclick="return confirm('Delete?')">🗑️</a>
  </td>
</tr>
<?php endforeach;?>
</tbody></table>

<script>
const EDIT_FIELDS = <?=json_encode(array_map(function($f){
  return [
    'label'=>$f['label'],
    'type'=>$f['field_type'],
    'placeholder'=>$f['placeholder'],
    'required'=>(int)$f['required'],
    'options'=>$f['options_json']?json_decode($f['options_json'],true):[]
  ];
}, $edit_fields), JSON_UNESCAPED_UNICODE)?>;

function toggleKind(){
  const k = document.getElementById('svcKind').value;
  document.getElementById('apiPicker').style.display = (k==='api') ? '' : 'none';
  document.getElementById('fieldsWrap').parentElement.style.opacity = (k==='custom') ? '1' : '.4';
}

function el(html){ const d=document.createElement('div'); d.innerHTML=html.trim(); return d.firstChild; }

function addField(data){
  data = data || {label:'',type:'text',placeholder:'',required:0,options:[]};
  const wrap = document.getElementById('fieldsWrap');
  const idx = wrap.children.length;
  const node = el(`
    <div class="svc-field-item" data-idx="${idx}">
      <div class="svc-field-row">
        <input class="input" name="fields[${idx}][label]" placeholder="ফিল্ড নাম (যেমন: NID নম্বর)" value="${escapeHtml(data.label)}">
        <select class="input field-type" name="fields[${idx}][type]">
          <option value="text" ${data.type==='text'?'selected':''}>টেক্সট</option>
          <option value="select" ${data.type==='select'?'selected':''}>সিলেক্ট (অপশন)</option>
        </select>
        <input class="input" name="fields[${idx}][placeholder]" placeholder="প্লেসহোল্ডার" value="${escapeHtml(data.placeholder)}">
        <button type="button" class="btn sm danger" onclick="this.closest('.svc-field-item').remove()">🗑️</button>
      </div>
      <label style="display:flex;gap:6px;align-items:center;margin:6px 0;font-size:13px">
        <input type="checkbox" name="fields[${idx}][required]" value="1" ${data.required?'checked':''}> আবশ্যক (অবশ্যই পূরণ করতে হবে)
      </label>
      <div class="opts-wrap" style="display:${data.type==='select'?'block':'none'}">
        <div class="opts-list"></div>
        <button type="button" class="btn ghost sm" onclick="addOpt(this)">+ অপশন যোগ করুন</button>
      </div>
    </div>
  `);
  wrap.appendChild(node);
  (data.options||[]).forEach(op => addOpt(node.querySelector('button.ghost'), op));
  node.querySelector('.field-type').addEventListener('change', function(){
    node.querySelector('.opts-wrap').style.display = this.value==='select' ? 'block':'none';
  });
}
function addOpt(btn, data){
  data = data || {name:'', price:0};
  const item = btn.closest('.svc-field-item');
  const idx = item.getAttribute('data-idx');
  const list = item.querySelector('.opts-list');
  const oi = list.children.length;
  const row = el(`
    <div class="svc-opt-row">
      <input class="input" name="fields[${idx}][options][${oi}][name]" placeholder="অপশন নাম" value="${escapeHtml(data.name)}">
      <input class="input" type="number" step="0.01" name="fields[${idx}][options][${oi}][price]" placeholder="মূল্য" value="${data.price||0}">
      <button type="button" class="btn sm danger" onclick="this.parentElement.remove()">✕</button>
    </div>
  `);
  list.appendChild(row);
}
function escapeHtml(s){ return String(s||'').replace(/[&<>"']/g, c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c]); }

// init
toggleKind();
EDIT_FIELDS.forEach(addField);
</script>
<?php require __DIR__.'/_footer.php';
