<?php
require_once __DIR__ . '/includes/admin_bootstrap.php';
$settings = getAllSettings($pdo);
$msg = '';

// ── Update status ──
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_status'])) {
    $oid    = (int)$_POST['order_id'];
    $status = $_POST['status'] ?? 'pending';
    $type   = $_POST['order_type'] ?? 'online';
    $allowed = ['pending','processing','shipped','delivered','cancelled','offline'];
    if(in_array($status,$allowed)) {
        $pdo->prepare("UPDATE orders SET status=?, order_type=? WHERE id=?")->execute([$status,$type,$oid]);

        // Steadfast courier — auto-submit when status=shipped
        if ($status==='shipped' && ($settings['steadfast_enabled']??'0')==='1') {
            $os=$pdo->prepare("SELECT * FROM orders WHERE id=?"); $os->execute([$oid]); $ord=$os->fetch();
            if($ord) {
                $items=$pdo->prepare("SELECT oi.*,p.name as pname FROM order_items oi LEFT JOIN products p ON oi.product_id=p.id WHERE oi.order_id=?");
                $items->execute([$oid]); $its=$items->fetchAll();
                $note=implode(', ', array_map(fn($i)=>$i['pname'].'×'.$i['quantity'], $its));
                $sfResult = steadfastSubmit($settings, [
                    'invoice'   => str_pad($oid,6,'0',STR_PAD_LEFT),
                    'recipient_name'    => $ord['customer_name'],
                    'recipient_phone'   => $ord['customer_phone'],
                    'recipient_address' => $ord['customer_address'],
                    'cod_amount'        => $ord['total_amount'],
                    'note'              => $note,
                ]);
                if($sfResult) {
                    $pdo->prepare("INSERT INTO courier_logs(order_id,consignment_id,tracking_code,courier_status,response) VALUES(?,?,?,?,?)")
                        ->execute([$oid,$sfResult['consignment_id']??'',$sfResult['tracking_code']??'','submitted',json_encode($sfResult)]);
                    $msg='<div class="alert alert-success"><i class="fas fa-truck"></i> স্ট্যাটাস আপডেট ও Steadfast কুরিয়ারে সাবমিট হয়েছে।</div>';
                } else {
                    $msg='<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> স্ট্যাটাস আপডেট হয়েছে কিন্তু Steadfast সাবমিট ব্যর্থ। API কী চেক করুন।</div>';
                }
            }
        } else {
            $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> অর্ডার স্ট্যাটাস আপডেট হয়েছে।</div>';
        }
    }
}

// ── Edit order details ──
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['edit_order'])) {
    $oid     = (int)$_POST['order_id'];
    $name    = trim($_POST['customer_name']    ?? '');
    $phone   = trim($_POST['customer_phone']   ?? '');
    $address = trim($_POST['customer_address'] ?? '');
    $total   = (float)($_POST['total_amount']  ?? 0);
    $delivery= (float)($_POST['delivery_charge']?? 0);
    if($name && $phone && $address) {
        $pdo->prepare("UPDATE orders SET customer_name=?,customer_phone=?,customer_address=?,total_amount=?,delivery_charge=? WHERE id=?")
            ->execute([$name,$phone,$address,$total,$delivery,$oid]);
        $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> অর্ডার তথ্য আপডেট হয়েছে।</div>';
    } else {
        $msg='<div class="alert alert-error">নাম, ফোন ও ঠিকানা আবশ্যক।</div>';
    }
}

// ── Steadfast helper ──
function steadfastSubmit($settings, $data) {
    $url = 'https://portal.steadfast.com.bd/api/v1/create_order';
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => [
            'Api-Key: ' . ($settings['steadfast_api_key']??''),
            'Secret-Key: ' . ($settings['steadfast_api_secret']??''),
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS     => json_encode($data),
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    curl_close($ch);
    if($err || !$resp) return false;
    $res = json_decode($resp, true);
    return (isset($res['status']) && $res['status']==200) ? $res['consignment'] : false;
}

// ── View single order ──
$viewId = (int)($_GET['view'] ?? 0);
$statusFilter = $_GET['status'] ?? '';
$search = trim($_GET['search'] ?? '');

$statusLabels=['pending'=>'অপেক্ষমান','processing'=>'প্রক্রিয়াধীন',
    'shipped'=>'পাঠানো হয়েছে','delivered'=>'ডেলিভারি হয়েছে',
    'cancelled'=>'বাতিল','offline'=>'অফলাইন সেল'];

$include = include __DIR__ . '/includes/admin_header.php';
?>
<h2>অর্ডার ব্যবস্থাপনা</h2>
<?=$msg?>

<?php if($viewId):
    $vs=$pdo->prepare("SELECT * FROM orders WHERE id=?"); $vs->execute([$viewId]); $ord=$vs->fetch();
    if(!$ord){echo '<div class="alert alert-error">অর্ডার পাওয়া যায়নি।</div>'; include __DIR__.'/includes/admin_footer.php'; exit;}
    $is=$pdo->prepare("SELECT oi.*,p.name as product_name,p.image FROM order_items oi LEFT JOIN products p ON oi.product_id=p.id WHERE oi.order_id=?");
    $is->execute([$viewId]); $items=$is->fetchAll();
    $courier=$pdo->prepare("SELECT * FROM courier_logs WHERE order_id=? ORDER BY created_at DESC LIMIT 1");
    $courier->execute([$viewId]); $courierLog=$courier->fetch();
?>
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:10px;">
    <span style="font-size:1.1rem;font-weight:700;color:var(--navy);">অর্ডার #<?=str_pad($viewId,6,'0',STR_PAD_LEFT)?></span>
    <a href="?" class="topbar-btn btn-gray"><i class="fas fa-arrow-left"></i> সব অর্ডার</a>
</div>

<div style="display:grid;grid-template-columns:1fr;gap:18px;">
  <div style="display:grid;grid-template-columns:1fr;gap:18px;">
  @media(min-width:700px){display:grid;grid-template-columns:1fr 300px;}

    <!-- Items -->
    <div class="card">
        <div class="card-header"><h3>পণ্যসমূহ</h3></div>
        <div class="table-wrap">
            <table>
                <thead><tr><th>ছবি</th><th>পণ্য</th><th>ভ্যারিয়েশন</th><th>পরিমাণ</th><th>মূল্য</th><th>সাবটোটাল</th></tr></thead>
                <tbody>
                <?php foreach($items as $it): ?>
                <tr>
                    <td><?php if($it['image']): ?><img src="<?=UPLOADS_URL.e($it['image'])?>" class="thumb"><?php else: ?><div class="thumb-placeholder"><i class="fas fa-image"></i></div><?php endif; ?></td>
                    <td><?=e($it['product_name'])?></td>
                    <td style="font-size:.8rem;color:var(--g600);"><?=e($it['variation_info'])?></td>
                    <td><?=$it['quantity']?></td>
                    <td>৳<?=number_format($it['price'],2)?></td>
                    <td><strong>৳<?=number_format($it['price']*$it['quantity'],2)?></strong></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div style="padding:12px 18px;display:flex;justify-content:flex-end;gap:20px;flex-wrap:wrap;font-size:.9rem;">
            <span>পণ্য: <strong>৳<?=number_format($ord['total_amount']-$ord['delivery_charge'],2)?></strong></span>
            <span>ডেলিভারি: <strong>৳<?=number_format($ord['delivery_charge'],2)?></strong></span>
            <span style="font-size:1rem;color:var(--navy);">মোট: <strong>৳<?=number_format($ord['total_amount'],2)?></strong></span>
        </div>
    </div>
  </div>

  <!-- Right col: info + status + edit -->
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:18px;align-items:start;flex-wrap:wrap;">

    <!-- Customer Info + Edit -->
    <div class="card">
        <div class="card-header"><h3>গ্রাহক তথ্য সম্পাদনা</h3></div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="order_id" value="<?=$viewId?>">
                <div class="form-group">
                    <label class="form-label">নাম</label>
                    <input type="text" class="form-control" name="customer_name" value="<?=e($ord['customer_name'])?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">ফোন</label>
                    <input type="tel" class="form-control" name="customer_phone" value="<?=e($ord['customer_phone'])?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">ঠিকানা</label>
                    <textarea class="form-control" name="customer_address" rows="3" required><?=e($ord['customer_address'])?></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">মোট পরিমাণ (৳)</label>
                    <input type="number" class="form-control" name="total_amount" value="<?=$ord['total_amount']?>" step="0.01" min="0">
                </div>
                <div class="form-group">
                    <label class="form-label">ডেলিভারি চার্জ (৳)</label>
                    <input type="number" class="form-control" name="delivery_charge" value="<?=$ord['delivery_charge']?>" step="0.01" min="0">
                </div>
                <div style="font-size:.82rem;color:var(--g600);margin-bottom:10px;">
                    <strong>ডেলিভারি:</strong> <?=$ord['inside_dhaka']?'ঢাকার ভিতরে':'ঢাকার বাইরে'?><br>
                    <strong>তারিখ:</strong> <?=date('d/m/Y H:i',strtotime($ord['created_at']))?>
                </div>
                <button type="submit" name="edit_order" class="topbar-btn btn-gold" style="width:100%;justify-content:center;">
                    <i class="fas fa-save"></i> তথ্য আপডেট করুন
                </button>
            </form>
        </div>
    </div>

    <!-- Status + Courier -->
    <div>
        <div class="card" style="margin-bottom:16px;">
            <div class="card-header"><h3>স্ট্যাটাস পরিবর্তন</h3></div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="order_id" value="<?=$viewId?>">
                    <div class="form-group">
                        <label class="form-label">অর্ডার স্ট্যাটাস</label>
                        <select class="form-control" name="status">
                            <?php foreach($statusLabels as $k=>$v): ?>
                                <option value="<?=$k?>" <?=$ord['status']===$k?'selected':''?>><?=$v?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">অর্ডারের ধরন</label>
                        <select class="form-control" name="order_type">
                            <option value="online" <?=($ord['order_type']??'online')==='online'?'selected':''?>>অনলাইন অর্ডার</option>
                            <option value="offline" <?=($ord['order_type']??'')==='offline'?'selected':''?>>অফলাইন সেল</option>
                        </select>
                    </div>
                    <?php if(($settings['steadfast_enabled']??'0')==='1'): ?>
                    <div style="background:rgba(49,130,206,.08);padding:10px;border-radius:var(--r);margin-bottom:12px;font-size:.82rem;">
                        <i class="fas fa-truck" style="color:#3182ce;"></i>
                        স্ট্যাটাস "পাঠানো হয়েছে" করলে Steadfast কুরিয়ারে স্বয়ংক্রিয়ভাবে সাবমিট হবে।
                    </div>
                    <?php endif; ?>
                    <button type="submit" name="update_status" class="topbar-btn btn-gold" style="width:100%;justify-content:center;">
                        <i class="fas fa-sync"></i> আপডেট করুন
                    </button>
                </form>
            </div>
        </div>

        <?php if($courierLog): ?>
        <div class="card">
            <div class="card-header"><h3>কুরিয়ার তথ্য</h3></div>
            <div class="card-body" style="font-size:.86rem;">
                <p><strong>Consignment ID:</strong> <?=e($courierLog['consignment_id'])?></p>
                <p><strong>Tracking Code:</strong> <?=e($courierLog['tracking_code'])?></p>
                <p><strong>সাবমিট:</strong> <?=date('d/m/Y H:i',strtotime($courierLog['created_at']))?></p>
                <?php if($courierLog['tracking_code']): ?>
                <a href="https://steadfast.com.bd/t/<?=e($courierLog['tracking_code'])?>" target="_blank" class="topbar-btn btn-navy" style="margin-top:10px;">
                    <i class="fas fa-search"></i> ট্র্যাক করুন
                </a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
  </div>
</div>

<?php else: // Order list view
    $where='WHERE 1=1'; $params=[];
    if($statusFilter){$where.=' AND o.status=?';$params[]=$statusFilter;}
    if($search){$where.=' AND (o.customer_name LIKE ? OR o.customer_phone LIKE ?)';$params[]="%$search%";$params[]="%$search%";}
    $stmt=$pdo->prepare("SELECT o.* FROM orders o $where ORDER BY o.created_at DESC");
    $stmt->execute($params); $orders=$stmt->fetchAll();
?>
<div class="card">
    <div class="card-header" style="flex-wrap:wrap;gap:10px;">
        <form method="GET" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <input type="text" class="form-control" name="search" placeholder="নাম/ফোন..." value="<?=e($search)?>" style="max-width:180px;">
            <select class="form-control" name="status" style="max-width:170px;">
                <option value="">সব স্ট্যাটাস</option>
                <?php foreach($statusLabels as $k=>$v): ?><option value="<?=$k?>" <?=$statusFilter===$k?'selected':''?>><?=$v?></option><?php endforeach; ?>
            </select>
            <button type="submit" class="topbar-btn btn-navy"><i class="fas fa-search"></i></button>
            <a href="?" class="topbar-btn btn-gray">রিসেট</a>
        </form>
        <span style="color:var(--g600);font-size:.88rem;margin-left:auto;">মোট: <?=count($orders)?> অর্ডার</span>
    </div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>নং</th><th>গ্রাহক</th><th>ফোন</th><th>মোট</th><th>ধরন</th><th>স্ট্যাটাস</th><th>তারিখ</th><th>অ্যাকশন</th></tr></thead>
            <tbody>
            <?php foreach($orders as $o): ?>
            <tr>
                <td><strong>#<?=str_pad($o['id'],6,'0',STR_PAD_LEFT)?></strong></td>
                <td><?=e($o['customer_name'])?></td>
                <td><?=e($o['customer_phone'])?></td>
                <td>৳<?=number_format($o['total_amount'],2)?></td>
                <td><?=($o['order_type']??'online')==='offline'?'<span class="badge" style="background:rgba(113,128,150,.15);color:#4a5568;">অফলাইন</span>':'<span class="badge badge-processing">অনলাইন</span>'?></td>
                <td><span class="badge badge-<?=$o['status']?>"><?=$statusLabels[$o['status']]??$o['status']?></span></td>
                <td style="white-space:nowrap;"><?=date('d/m/Y',strtotime($o['created_at']))?></td>
                <td><a href="?view=<?=$o['id']?>" class="topbar-btn btn-navy"><i class="fas fa-eye"></i></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
