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

// -------- POST actions (receive / complete / cancel / edit note) --------
if ($_SERVER['REQUEST_METHOD']==='POST') {
    csrf_check();
    $act = $_POST['action'] ?? '';
    $id  = (int)($_POST['id'] ?? 0);

    $s = $pdo->prepare("SELECT * FROM orders WHERE id=?"); $s->execute([$id]); $o = $s->fetch();
    if (!$o) { redirect('orders.php'); }

    if ($act === 'receive') {
        $pdo->prepare("UPDATE orders SET status='received' WHERE id=?")->execute([$id]);
        redirect("orders.php?view=$id");
    }

    if ($act === 'cancel') {
        $reason = trim($_POST['cancel_reason'] ?? '');
        if (!in_array($o['status'], ['cancelled','refund'], true) && (float)$o['price'] > 0) {
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id=?")
                ->execute([(float)$o['price'], (int)$o['user_id']]);
            log_txn($pdo, (int)$o['user_id'], 'refund', (float)$o['price'], 'order#'.$id, 'Order cancel refund');
        }
        $pdo->prepare("UPDATE orders SET status='cancelled', cancel_reason=?, cancelled_at=NOW(), user_notified=0 WHERE id=?")
            ->execute([$reason, $id]);
        redirect("orders.php?view=$id");
    }

    if ($act === 'complete') {
        $dtype   = in_array($_POST['delivery_type']??'text', ['text','link','pdf','file'], true) ? $_POST['delivery_type'] : 'text';
        $content = trim($_POST['delivery_content'] ?? '');
        $file    = null;
        if (in_array($dtype, ['pdf','file'], true) && !empty($_FILES['delivery_file']['name'])) {
            $up = $_FILES['delivery_file'];
            if ($up['error'] === UPLOAD_ERR_OK) {
                $ext = pathinfo($up['name'], PATHINFO_EXTENSION);
                $safe = 'order'.$id.'_'.time().'_'.bin2hex(random_bytes(4)).($ext?'.'.preg_replace('/[^a-zA-Z0-9]/','',$ext):'');
                $dest = __DIR__.'/../uploads/deliveries/'.$safe;
                @mkdir(dirname($dest), 0775, true);
                if (move_uploaded_file($up['tmp_name'], $dest)) $file = $safe;
            }
        } else {
            $file = $o['delivery_file'];
        }

        if (in_array($o['status'], ['cancelled','refund'], true) && (float)$o['price'] > 0) {
            $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id=?")
                ->execute([(float)$o['price'], (int)$o['user_id']]);
            log_txn($pdo, (int)$o['user_id'], 'debit', (float)$o['price'], 'order#'.$id, 'Re-completed order');
        }

        $pdo->prepare("UPDATE orders SET status='completed', delivery_type=?, delivery_content=?, delivery_file=?, completed_at=NOW(), user_notified=0, cancel_reason=NULL WHERE id=?")
            ->execute([$dtype, $content, $file, $id]);
        redirect("orders.php?view=$id");
    }

    if ($act === 'save_meta') {
        $note = $_POST['note'] ?? '';
        $allowed = ['pending','received','completed','cancelled'];
        $st   = in_array($_POST['status'] ?? '', $allowed, true) ? $_POST['status'] : $o['status'];
        $old  = $o['status'];

        $was_charged = !in_array($old, ['cancelled','refund'], true);
        $now_charged = !in_array($st,  ['cancelled','refund'], true);
        $price = (float)$o['price'];

        if ($price > 0 && $was_charged && !$now_charged) {
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id=?")->execute([$price, (int)$o['user_id']]);
            log_txn($pdo, (int)$o['user_id'], 'refund', $price, 'order#'.$id, 'Manual status → '.$st);
        } elseif ($price > 0 && !$was_charged && $now_charged) {
            $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$price, (int)$o['user_id']]);
            log_txn($pdo, (int)$o['user_id'], 'debit', $price, 'order#'.$id, 'Manual status → '.$st);
        }

        $pdo->prepare("UPDATE orders SET note=?, status=?, user_notified=0 WHERE id=?")->execute([$note,$st,$id]);
        redirect("orders.php?view=$id");
    }
}

// -------- Delete custom order (with files) --------
function _admin_delete_order($pdo, $id){
    $id = (int)$id;
    if (!$id) return false;
    $q = $pdo->prepare("SELECT o.*, s.kind AS skind FROM orders o LEFT JOIN services s ON s.id=o.service_id WHERE o.id=?");
    $q->execute([$id]); $o = $q->fetch();
    if (!$o) return false;
    if (($o['skind'] ?? 'custom') === 'api') return false;
    if (!empty($o['delivery_file'])) {
        $fp = __DIR__.'/../uploads/deliveries/'.$o['delivery_file'];
        if (is_file($fp)) @unlink($fp);
    }
    $pdo->prepare("DELETE FROM orders WHERE id=?")->execute([$id]);
    return true;
}
if ($_SERVER['REQUEST_METHOD']==='POST' && (($_POST['action']??'')==='delete')) {
    csrf_check();
    _admin_delete_order($pdo, (int)($_POST['id']??0));
    redirect('orders.php');
}
if (isset($_GET['del'])) {
    _admin_delete_order($pdo, (int)$_GET['del']);
    redirect('orders.php');
}

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

// -------- View single order --------
if (isset($_GET['view'])) {
    $s = $pdo->prepare("SELECT o.*, u.name AS uname, u.email, s.name AS sname, s.kind AS skind
                        FROM orders o
                        LEFT JOIN users u ON u.id=o.user_id
                        LEFT JOIN services s ON s.id=o.service_id
                        WHERE o.id=?");
    $s->execute([(int)$_GET['view']]);
    $o = $s->fetch();
    if (!$o) { echo "<p>Not found</p>"; require __DIR__.'/_footer.php'; exit; }
    $custom = $o['custom_data'] ? json_decode($o['custom_data'], true) : null;
    ?>
    <h2><a href="orders.php">← Back</a> — Order #<?=$o['id']?></h2>
    <div class="grid g2" style="margin-top:14px">
      <div class="card">
        <h3>কাস্টমার</h3>
        <p><b><?=e($o['uname'])?></b> — <?=e($o['email'])?></p>
        <p>সার্ভিস: <b><?=e($o['sname'])?></b> (<?=e($o['skind']??'')?>)</p>
        <?php if(!empty($o['nid'])):?><p>NID: <b><?=e($o['nid'])?></b> | DOB: <?=e($o['dob'])?></p><?php endif;?>
        <p>মূল্য: <?=money($o['price'])?> | স্ট্যাটাস: <span class="badge <?=$o['status']==='completed'||$o['status']==='success'?'ok':'fail'?>"><?=e($o['status'])?></span></p>
        <p>তারিখ: <?=e($o['created_at'])?></p>

        <?php if($custom): ?>
          <hr><h4>ফর্ম ডাটা</h4>
          <?php foreach($custom as $k=>$v): ?>
            <div style="padding:4px 0;font-size:13px"><b><?=e($k)?>:</b> <?=e(is_array($v)?json_encode($v,JSON_UNESCAPED_UNICODE):$v)?></div>
          <?php endforeach; ?>
        <?php endif; ?>

        <?php if(($o['skind']??'')==='api' && !empty($o['response_json'])):
            $__raw = $o['response_json'];
            $__dec = json_decode($__raw, true);
            $__pretty = ($__dec!==null) ? json_encode($__dec, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) : $__raw;
        ?>
          <hr>
          <div style="display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px">
            <h4 style="margin:0">🔌 API রেসপন্স (JSON)</h4>
            <button type="button" class="btn sm ghost" onclick="(function(t){navigator.clipboard&&navigator.clipboard.writeText(t);this.event&&this.event.preventDefault&&this.event.preventDefault();}).call(this, document.getElementById('apiJson').innerText); this.innerText='✅ কপি হয়েছে';">📋 কপি</button>
          </div>
          <pre id="apiJson" style="background:#0f172a;color:#e2e8f0;padding:12px;border-radius:8px;max-height:420px;overflow:auto;font-size:12px;white-space:pre-wrap;word-break:break-all;margin:0"><?=e($__pretty)?></pre>
        <?php endif; ?>

        <?php if($o['status']==='cancelled' && !empty($o['cancel_reason'])): ?>
          <div class="alert err" style="margin-top:10px"><b>বাতিলের কারণ:</b> <?=e($o['cancel_reason'])?></div>
        <?php endif; ?>
      </div>

      <div class="card">
        <h3>এডমিন এ্যাকশন</h3>

        <?php if($o['status']==='pending'): ?>
          <form method="post" style="display:inline"><?=csrf_field()?>
            <input type="hidden" name="id" value="<?=$o['id']?>">
            <input type="hidden" name="action" value="receive">
            <button class="btn">📥 রিসিভ করা হয়েছে</button>
          </form>
        <?php endif; ?>

        <details <?=in_array($o['status'],['pending','received','cancelled','refund'],true)?'open':''?> style="margin-top:14px">
          <summary style="cursor:pointer;font-weight:600">✅ অর্ডার সম্পাদন (Complete)</summary>
          <form method="post" enctype="multipart/form-data" style="margin-top:10px"><?=csrf_field()?>
            <input type="hidden" name="id" value="<?=$o['id']?>">
            <input type="hidden" name="action" value="complete">
            <div class="field"><label>ডেলিভারি ধরন</label>
              <select name="delivery_type" class="input" id="dtype" onchange="toggleD()">
                <option value="text" <?=$o['delivery_type']==='text'?'selected':''?>>টেক্সট</option>
                <option value="link" <?=$o['delivery_type']==='link'?'selected':''?>>লিংক</option>
                <option value="pdf"  <?=$o['delivery_type']==='pdf'?'selected':''?>>PDF ফাইল</option>
                <option value="file" <?=$o['delivery_type']==='file'?'selected':''?>>অন্য ফাইল</option>
              </select>
            </div>
            <div class="field" id="dtext"><label>কন্টেন্ট (টেক্সট / লিংক)</label>
              <textarea class="input" name="delivery_content" rows="4"><?=e($o['delivery_content']??'')?></textarea>
            </div>
            <div class="field" id="dfile"><label>ফাইল আপলোড</label>
              <input type="file" name="delivery_file" class="input">
              <?php if(!empty($o['delivery_file'])): ?><small>বর্তমান: <?=e($o['delivery_file'])?></small><?php endif; ?>
            </div>
            <button class="btn">সম্পাদন করুন</button>
          </form>
        </details>

        <details style="margin-top:14px">
          <summary style="cursor:pointer;font-weight:600;color:#dc2626">❌ অর্ডার বাতিল</summary>
          <form method="post" style="margin-top:10px" onsubmit="return confirm('বাতিল করলে ইউজারকে টাকা রিফান্ড হবে। নিশ্চিত?')"><?=csrf_field()?>
            <input type="hidden" name="id" value="<?=$o['id']?>">
            <input type="hidden" name="action" value="cancel">
            <div class="field"><label>বাতিলের কারণ (ইউজার দেখবে)</label>
              <textarea class="input" name="cancel_reason" rows="3" required><?=e($o['cancel_reason']??'')?></textarea>
            </div>
            <button class="btn danger">বাতিল ও রিফান্ড</button>
          </form>
        </details>

        <?php if($o['status']==='completed'): ?>
          <hr>
          <p>📊 ডাউনলোড: <b><?=(int)$o['download_count']?></b> বার | কপি: <b><?=(int)$o['copy_count']?></b> বার</p>
        <?php endif; ?>

        <hr>
        <form method="post"><?=csrf_field()?>
          <input type="hidden" name="id" value="<?=$o['id']?>">
          <input type="hidden" name="action" value="save_meta">
          <div class="field"><label>স্ট্যাটাস (ম্যানুয়াল)</label>
            <select name="status" class="input">
              <?php $labels=['pending'=>'পেন্ডিং','received'=>'রিসিভড','completed'=>'সাকসেসফুল','cancelled'=>'ক্যানসেল']; ?>
              <?php foreach($labels as $st=>$lbl):?>
                <option value="<?=$st?>" <?=$o['status']===$st?'selected':''?>><?=$lbl?></option>
              <?php endforeach;?>
            </select>
            <small style="color:#64748b">ক্যানসেল করলে অটো রিফান্ড; আবার সাকসেসফুল করলে অটো ডিডাক্ট হবে।</small></div>
          <div class="field"><label>এডমিন নোট</label><textarea class="input" name="note" rows="2"><?=e($o['note']??'')?></textarea></div>
          <button class="btn ghost">সেভ</button>
        </form>
      </div>
    </div>
    <script>
    function toggleD(){
      const t=document.getElementById('dtype').value;
      document.getElementById('dtext').style.display=(t==='text'||t==='link')?'':'none';
      document.getElementById('dfile').style.display=(t==='pdf'||t==='file')?'':'none';
    }
    toggleD();
    </script>
    <?php
    require __DIR__.'/_footer.php'; exit;
}

// -------- List with status filter tabs --------
$q      = trim($_GET['q'] ?? '');
$status = trim($_GET['status'] ?? 'all');

// Status → SQL clause
$status_sql = '';
$status_params = [];
switch ($status) {
    case 'pending':    $status_sql = "o.status='pending'"; break;
    case 'received':   $status_sql = "o.status='received'"; break;
    case 'successful': $status_sql = "o.status IN ('completed','success')"; break;
    case 'cancelled':  $status_sql = "o.status IN ('cancelled','refund')"; break;
    case 'failed':     $status_sql = "o.status IN ('failed','rejected')"; break;
    default:           $status_sql = ''; // all
}

// Count for each tab (single query)
$counts = ['all'=>0,'pending'=>0,'received'=>0,'successful'=>0,'cancelled'=>0,'failed'=>0];
$cntRows = $pdo->query("SELECT status, COUNT(*) c FROM orders GROUP BY status")->fetchAll();
foreach ($cntRows as $cr) {
    $st = $cr['status']; $c = (int)$cr['c']; $counts['all'] += $c;
    if ($st==='pending') $counts['pending']+=$c;
    elseif ($st==='received') $counts['received']+=$c;
    elseif (in_array($st,['completed','success'],true)) $counts['successful']+=$c;
    elseif (in_array($st,['cancelled','refund'],true)) $counts['cancelled']+=$c;
    elseif (in_array($st,['failed','rejected'],true)) $counts['failed']+=$c;
}

$where_parts = [];
$params = [];
if ($status_sql !== '') { $where_parts[] = $status_sql; }
if ($q !== '') {
    $like = '%'.$q.'%'; $qid = (int)ltrim($q,'#');
    $where_parts[] = "(o.id=? OR u.email LIKE ? OR u.phone LIKE ? OR u.name LIKE ? OR o.nid LIKE ?)";
    $params = array_merge($params, [$qid,$like,$like,$like,$like]);
}
$where = $where_parts ? ('WHERE '.implode(' AND ', $where_parts)) : '';
$st = $pdo->prepare("SELECT o.*, u.name AS uname, s.name AS sname, s.kind AS skind
                     FROM orders o
                     LEFT JOIN users u ON u.id=o.user_id
                     LEFT JOIN services s ON s.id=o.service_id
                     $where
                     ORDER BY o.id DESC LIMIT 300");
$st->execute($params);
$rows = $st->fetchAll();

$tab_qs = function($k) use ($q){ $qs=['status'=>$k]; if($q!=='') $qs['q']=$q; return 'orders.php?'.http_build_query($qs); };
$tabs = [
  ['all',       '🗂️ সব',        $counts['all']],
  ['pending',   '⏳ পেন্ডিং',    $counts['pending']],
  ['received',  '📥 রিসিভড',    $counts['received']],
  ['successful','✅ সাকসেসফুল', $counts['successful']],
  ['cancelled', '❌ ক্যানসেল',   $counts['cancelled']],
  ['failed',    '⚠️ ফেইল্ড',    $counts['failed']],
];
?>
<h2 style="margin-bottom:14px">📦 অর্ডার</h2>
<style>
.otabs{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:14px}
.otabs a{padding:8px 14px;border-radius:999px;background:#fff;border:1px solid #e2e8f0;color:#334155;font-size:13px;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;gap:6px;transition:all .15s ease}
.otabs a:hover{border-color:#c7d2fe;color:#4338ca}
.otabs a.active{background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;border-color:transparent;box-shadow:0 6px 14px rgba(99,102,241,.35)}
.otabs a .cnt{background:rgba(15,23,42,.08);color:inherit;padding:1px 8px;border-radius:999px;font-size:11px;font-weight:700;min-width:20px;text-align:center}
.otabs a.active .cnt{background:rgba(255,255,255,.25);color:#fff}
</style>
<div class="otabs">
<?php foreach($tabs as $t): ?>
  <a href="<?=e($tab_qs($t[0]))?>" class="<?=$status===$t[0]?'active':''?>"><?=$t[1]?> <span class="cnt"><?=(int)$t[2]?></span></a>
<?php endforeach; ?>
</div>
<form method="get" style="margin-bottom:14px;display:flex;gap:8px;flex-wrap:wrap">
  <input type="hidden" name="status" value="<?=e($status)?>">
  <input class="input" name="q" value="<?=e($q)?>" placeholder="🔍 Order ID, ইমেইল, ফোন, NID" style="flex:1;min-width:240px">
  <button class="btn">সার্চ</button>
  <?php if($q!==''):?><a class="btn" style="background:#64748b" href="<?=e($tab_qs($status))?>">✕ Clear</a><?php endif;?>
</form>
<table><thead><tr><th>#</th><th>Date</th><th>User</th><th>Service</th><th>Info</th><th>Price</th><th>Status</th><th>Action</th></tr></thead><tbody>
<?php foreach($rows as $r):
  $ok = in_array($r['status'],['completed','success'],true);
  $bad = in_array($r['status'],['failed','cancelled','refund','rejected'],true);
  $badge = $ok?'ok':($bad?'fail':'pending');
?>
<tr>
  <td>#<?=$r['id']?></td>
  <td><?=e($r['created_at'])?></td>
  <td><?=e($r['uname'])?></td>
  <td><?=e($r['sname'])?></td>
  <td><?=e($r['nid']?:'—')?></td>
  <td><?=money($r['price'])?></td>
  <td><span class="badge <?=$badge?>"><?=e($r['status'])?></span></td>
  <td>
    <a class="btn sm" href="?view=<?=$r['id']?>">👁️ View</a>
    <?php if(($r['skind']??'custom')!=='api'): ?>
      <a class="btn sm danger" href="?del=<?=$r['id']?>" onclick="return confirm('এই কাস্টম অর্ডার ডিলিট করবেন? (ছবি/ফাইলসহ ডিলিট হবে)')">🗑️</a>
    <?php endif; ?>
  </td>
</tr>
<?php endforeach;?>
<?php if(!$rows):?><tr><td colspan="8" style="text-align:center;padding:20px;color:#64748b">কোন অর্ডার নেই</td></tr><?php endif;?>
</tbody></table>
<?php require __DIR__.'/_footer.php';
