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

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

if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['update_status'])){
    $oid=(int)$_POST['order_id'];
    $st=$_POST['status']??'pending';
    $ot=$_POST['order_type']??'online';
    if(in_array($st,['pending','processing','shipped','delivered','cancelled'])){
        $pdo->prepare("UPDATE orders SET status=?,order_type=? WHERE id=?")->execute([$st,$ot,$oid]);
        if($st==='shipped'&&($settings['steadfast_enabled']??'0')==='1'&&!empty($settings['steadfast_api_key'])){
            $o2=$pdo->prepare("SELECT * FROM orders WHERE id=?");$o2->execute([$oid]);$ord2=$o2->fetch();
            if($ord2){
                $ii=$pdo->prepare("SELECT oi.*,p.name as pn FROM order_items oi LEFT JOIN products p ON oi.product_id=p.id WHERE oi.order_id=?");
                $ii->execute([$oid]);$iArr=$ii->fetchAll();
                $note=implode(', ',array_map(fn($x)=>$x['pn'].'×'.$x['quantity'],$iArr));
                $sf=steadfastSubmit($settings,['invoice'=>str_pad($oid,6,'0',STR_PAD_LEFT),'recipient_name'=>$ord2['customer_name'],'recipient_phone'=>$ord2['customer_phone'],'recipient_address'=>$ord2['customer_address'],'cod_amount'=>(float)$ord2['total_amount'],'note'=>$note]);
                if($sf){$pdo->prepare("INSERT INTO courier_logs(order_id,consignment_id,tracking_code,courier_status,response)VALUES(?,?,?,?,?)")->execute([$oid,$sf['consignment_id']??'',$sf['tracking_code']??'','submitted',json_encode($sf)]);$msg='<div class="alert alert-success"><i class="fas fa-truck"></i> Steadfast সাবমিট হয়েছে। Tracking: '.e($sf['tracking_code']??'N/A').'</div>';}
                else{$msg='<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> স্ট্যাটাস আপডেট হয়েছে। Steadfast ব্যর্থ।</div>';}
            }
        }else{$msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> স্ট্যাটাস আপডেট হয়েছে।</div>';}
    }
}

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

$statusLabels=['pending'=>'অপেক্ষমান','processing'=>'প্রক্রিয়াধীন','shipped'=>'পাঠানো হয়েছে','delivered'=>'ডেলিভারি হয়েছে','cancelled'=>'বাতিল'];
$viewId=(int)($_GET['view']??0);
$statusFilter=$_GET['status']??'';
$search=trim($_GET['search']??'');
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();
$cl=$pdo->prepare("SELECT * FROM courier_logs WHERE order_id=? ORDER BY created_at DESC LIMIT 1");
$cl->execute([$viewId]);$clog=$cl->fetch();
?>
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;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 class="badge badge-<?=$ord['status']?>"><?=$statusLabels[$ord['status']]??$ord['status']?></span></span>
    <a href="?" class="topbar-btn btn-gray"><i class="fas fa-arrow-left"></i> সব অর্ডার</a>
</div>

<!-- Items card -->
<div class="card" style="margin-bottom:16px;">
    <div class="card-header"><h3><i class="fas fa-box"></i> পণ্যসমূহ</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><strong><?=e($it['product_name'])?></strong></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;border-top:1px solid var(--g100);">
        <span>পণ্য মোট: <strong>৳<?=number_format($ord['total_amount']-($ord['delivery_charge']??0),2)?></strong></span>
        <span>ডেলিভারি: <strong>৳<?=number_format($ord['delivery_charge']??0,2)?></strong></span>
        <span style="font-weight:700;color:var(--navy);">সর্বমোট: ৳<?=number_format($ord['total_amount'],2)?></span>
    </div>
</div>

<!-- Status form + Edit form side by side -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;">

    <!-- STATUS UPDATE -->
    <div class="card">
        <div class="card-header" style="background:var(--navy);border-radius:var(--r) var(--r) 0 0;">
            <h3 style="color:var(--gold);"><i class="fas fa-sync-alt"></i> স্ট্যাটাস পরিবর্তন করুন</h3>
        </div>
        <div class="card-body" style="padding:20px;">
            <form method="POST" action="orders.php?view=<?=$viewId?>">
                <input type="hidden" name="order_id" value="<?=$viewId?>">

                <div class="form-group">
                    <label class="form-label" style="font-size:.95rem;">অর্ডার স্ট্যাটাস বাছাই করুন</label>
                    <select class="form-control" name="status" style="font-size:.95rem;padding:12px;">
                        <option value="pending"    <?=$ord['status']==='pending'   ?'selected':''?>>⏳ অপেক্ষমান</option>
                        <option value="processing" <?=$ord['status']==='processing'?'selected':''?>>🔄 প্রক্রিয়াধীন</option>
                        <option value="shipped"    <?=$ord['status']==='shipped'   ?'selected':''?>>🚚 পাঠানো হয়েছে</option>
                        <option value="delivered"  <?=$ord['status']==='delivered' ?'selected':''?>>✅ ডেলিভারি হয়েছে</option>
                        <option value="cancelled"  <?=$ord['status']==='cancelled' ?'selected':''?>>❌ বাতিল</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label" style="font-size:.95rem;">অর্ডারের ধরন</label>
                    <select class="form-control" name="order_type" style="font-size:.95rem;padding:12px;">
                        <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:14px;font-size:.82rem;color:#2c5282;">
                    <i class="fas fa-info-circle"></i> "পাঠানো হয়েছে" করলে Steadfast এ অটো সাবমিট হবে।
                </div>
                <?php endif;?>

                <button type="submit" name="update_status" class="topbar-btn btn-gold"
                        style="width:100%;justify-content:center;padding:14px;font-size:1rem;">
                    <i class="fas fa-check-circle"></i> স্ট্যাটাস আপডেট করুন
                </button>
            </form>
        </div>
    </div>

    <!-- EDIT ORDER INFO -->
    <div class="card">
        <div class="card-header"><h3><i class="fas fa-edit"></i> গ্রাহক তথ্য সম্পাদনা</h3></div>
        <div class="card-body">
            <form method="POST" action="orders.php?view=<?=$viewId?>">
                <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="2"><?=e($ord['customer_address'])?></textarea>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <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">
                    </div>
                    <div class="form-group">
                        <label class="form-label">ডেলিভারি (৳)</label>
                        <input type="number" class="form-control" name="delivery_charge" value="<?=$ord['delivery_charge']??0?>" step="0.01">
                    </div>
                </div>
                <div style="font-size:.8rem;color:var(--g600);margin-bottom:10px;">
                    <?=$ord['inside_dhaka']?'ঢাকার ভিতরে':'ঢাকার বাইরে'?> | <?=date('d/m/Y H:i',strtotime($ord['created_at']))?>
                </div>
                <button type="submit" name="edit_order" class="topbar-btn btn-navy" style="width:100%;justify-content:center;padding:12px;">
                    <i class="fas fa-save"></i> তথ্য সংরক্ষণ
                </button>
            </form>
        </div>
    </div>
</div>

<?php if($clog):?>
<div class="card" style="margin-top:16px;">
    <div class="card-header"><h3><i class="fas fa-truck"></i> Steadfast কুরিয়ার তথ্য</h3></div>
    <div class="card-body" style="display:flex;gap:20px;flex-wrap:wrap;font-size:.88rem;">
        <span><strong>Consignment:</strong> <?=e($clog['consignment_id'])?></span>
        <span><strong>Tracking:</strong> <?=e($clog['tracking_code'])?></span>
        <span><strong>সময়:</strong> <?=date('d/m/Y H:i',strtotime($clog['created_at']))?></span>
        <?php if($clog['tracking_code']):?><a href="https://steadfast.com.bd/t/<?=e($clog['tracking_code'])?>" target="_blank" class="topbar-btn btn-navy"><i class="fas fa-search"></i> ট্র্যাক</a><?php endif;?>
    </div>
</div>
<?php endif;?>

<?php else:
$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;">মোট: <?=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><?=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;?>
            <?php if(empty($orders)):?><tr><td colspan="8" style="text-align:center;padding:28px;color:var(--g400);">কোনো অর্ডার নেই।</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>
<?php endif;?>
<?php include __DIR__.'/includes/admin_footer.php';?>
