<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('header.php');
$page_title  = WEB_NAME . " | My SMM Orders";
$page_title2 = "My Orders";

try {
    $stmt = $pdo->prepare("SELECT o.*, s.name AS service_name, s.category, s.refill, s.cancel FROM smm_orders o LEFT JOIN smm_services s ON o.smm_service_id = s.id WHERE o.user_id = :uid ORDER BY o.id DESC");
    $stmt->execute(['uid' => $user['id']]);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $orders = []; }

$total_orders = count($orders);
$total_spent = $completed_orders = $pending_orders = 0;
foreach ($orders as $o) {
    $total_spent += $o['charge'];
    if ($o['status'] === 'Completed') $completed_orders++;
    if (in_array($o['status'], ['Pending','Processing','In progress'])) $pending_orders++;
}
?>
<title><?php echo htmlspecialchars($page_title); ?></title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}
.ord-hero{background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 40%,#4D148C 80%,#4D148C 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:14px}
.ord-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:14px;padding:14px;transition:border-color .2s}
.ord-card:hover{border-color:rgba(77,20,140,.2)}
.stat-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:12px;padding:12px;display:flex;align-items:center;gap:10px}
.action-btn{font-size:.68rem;font-weight:600;padding:5px 10px;border-radius:7px;border:none;cursor:pointer;display:flex;align-items:center;gap:4px;transition:all .15s}
</style>

<div class="max-w-4xl mx-auto">

<!-- Hero -->
<div class="ord-hero anim anim-1">
    <div style="position:absolute;width:140px;height:140px;border-radius:50%;filter:blur(50px);background:radial-gradient(circle,rgba(77,20,140,.2),transparent);top:-30px;right:-30px;pointer-events:none;"></div>
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:14px;">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;margin-bottom:4px;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-list-check text-emerald-300 text-base"></i>My SMM Orders
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem;">Track all your social media boost orders in real-time.</p>
        </div>
        <a href="boost" style="background:white;color:#4D148C;font-weight:700;font-size:.78rem;padding:10px 16px;border-radius:10px;text-decoration:none;display:inline-flex;align-items:center;gap:6px;">
            <i class="fas fa-plus text-xs"></i>New Order
        </a>
    </div>
</div>

<!-- Stats -->
<div class="anim anim-1" style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:14px;" class="md:grid-cols-4">
    <?php foreach ([
        ['fas fa-list','rgba(77,20,140,.1)','#4D148C',$total_orders,'Total'],
        ['fas fa-circle-check','rgba(77,20,140,.1)','#6b23c2',$completed_orders,'Completed'],
        ['fas fa-clock','rgba(245,158,11,.1)','#d97706',$pending_orders,'Pending'],
        ['fas fa-naira-sign','rgba(59,130,246,.1)','#2563eb','₦'.number_format($total_spent,2),'Total Spent'],
    ] as [$ic,$bg,$col,$val,$lbl]): ?>
    <div class="stat-card">
        <div style="width:36px;height:36px;border-radius:9px;background:<?php echo $bg; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="<?php echo $ic; ?>" style="font-size:.85rem;color:<?php echo $col; ?>;"></i>
        </div>
        <div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:500;"><?php echo $lbl; ?></p>
            <p style="font-weight:800;font-size:.95rem;color:var(--text-primary);font-family:monospace;"><?php echo $val; ?></p>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Orders -->
<?php if (!empty($orders)): ?>
<div class="anim anim-2" style="display:flex;flex-direction:column;gap:8px;">
    <?php foreach ($orders as $o):
        switch ($o['status']) {
            case 'Completed':   $bc='rgba(77,20,140,.1)'; $tc='#6b23c2'; $ic='fa-circle-check'; break;
            case 'In progress': $bc='rgba(59,130,246,.08)'; $tc='#2563eb'; $ic='fa-spinner fa-spin'; break;
            case 'Processing':  $bc='rgba(77,20,140,.08)'; $tc='#4D148C'; $ic='fa-gear fa-spin'; break;
            case 'Partial':     $bc='rgba(245,158,11,.08)'; $tc='#d97706'; $ic='fa-circle-half-stroke'; break;
            case 'Cancelled':   $bc='rgba(100,116,139,.08)'; $tc='#64748b'; $ic='fa-ban'; break;
            default:            $bc='rgba(245,158,11,.08)'; $tc='#d97706'; $ic='fa-clock'; break;
        }
        $progress = 0;
        if (!empty($o['quantity']) && !empty($o['start_count']) && $o['status'] === 'In progress') {
            $delivered = max(0, $o['quantity'] - intval($o['remains'] ?? $o['quantity']));
            $progress  = min(100, max(0, round(($delivered / $o['quantity']) * 100)));
        } elseif ($o['status'] === 'Completed') { $progress = 100; }
    ?>
    <div class="ord-card">
        <div style="display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;">
            <!-- Left info -->
            <div style="flex:1;min-width:0;">
                <div style="display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:6px;">
                    <span style="font-size:.65rem;font-weight:700;color:var(--text-muted);font-family:monospace;">#<?php echo $o['id']; ?></span>
                    <?php if ($o['jap_order_id']): ?>
                    <span style="font-size:.65rem;color:var(--text-muted);">ID: <?php echo $o['jap_order_id']; ?></span>
                    <?php endif; ?>
                    <span style="font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:99px;background:rgba(77,20,140,.08);color:#4D148C;">
                        <?php echo htmlspecialchars($o['category'] ?? '—'); ?>
                    </span>
                    <span style="font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:99px;background:<?php echo $bc; ?>;color:<?php echo $tc; ?>;display:flex;align-items:center;gap:4px;">
                        <i class="fas <?php echo $ic; ?>" style="font-size:.55rem;"></i><?php echo $o['status']; ?>
                    </span>
                </div>
                <p style="font-weight:600;font-size:.82rem;color:var(--text-primary);margin-bottom:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                    <?php echo htmlspecialchars($o['service_name'] ?? 'Deleted Service'); ?>
                </p>
                <p style="font-size:.72rem;color:var(--text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:8px;">
                    <i class="fas fa-link text-xs mr-1"></i>
                    <a href="<?php echo htmlspecialchars($o['link']); ?>" target="_blank" style="color:inherit;text-decoration:none;"><?php echo htmlspecialchars($o['link']); ?></a>
                </p>
                <?php if ($o['status'] === 'In progress' || $o['status'] === 'Partial'): ?>
                <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                    <div style="flex:1;height:4px;background:rgba(77,20,140,.1);border-radius:99px;overflow:hidden;">
                        <div style="height:100%;width:<?php echo $progress; ?>%;background:linear-gradient(90deg,#4D148C,#6b23c2);border-radius:99px;transition:width 1s;"></div>
                    </div>
                    <span style="font-size:.65rem;font-family:monospace;color:var(--text-muted);"><?php echo $progress; ?>%</span>
                </div>
                <?php endif; ?>
                <div style="display:flex;gap:6px;flex-wrap:wrap;">
                    <button onclick="checkOrderStatus(<?php echo $o['id']; ?>,<?php echo (int)$o['jap_order_id']; ?>)"
                            class="action-btn" style="background:rgba(77,20,140,.08);color:#4D148C;">
                        <i class="fas fa-rotate-right text-xs"></i>Refresh
                    </button>
                    <?php if ($o['refill'] && $o['status'] === 'Completed'): ?>
                    <button onclick="requestRefill(<?php echo $o['id']; ?>,<?php echo (int)$o['jap_order_id']; ?>)"
                            class="action-btn" style="background:rgba(77,20,140,.08);color:#6b23c2;">
                        <i class="fas fa-rotate-right text-xs"></i>Refill
                    </button>
                    <?php endif; ?>
                    <?php if ($o['cancel'] && in_array($o['status'],['Pending','Processing'])): ?>
                    <button onclick="cancelOrder(<?php echo $o['id']; ?>,<?php echo (int)$o['jap_order_id']; ?>)"
                            class="action-btn" style="background:rgba(239,68,68,.07);color:#dc2626;">
                        <i class="fas fa-ban text-xs"></i>Cancel
                    </button>
                    <?php endif; ?>
                </div>
            </div>
            <!-- Right meta -->
            <div style="text-align:right;flex-shrink:0;">
                <p style="font-weight:800;font-size:1rem;color:#4D148C;font-family:monospace;">₦<?php echo number_format($o['charge'],2); ?></p>
                <p style="font-size:.7rem;color:var(--text-muted);"><?php echo number_format($o['quantity']); ?> units</p>
                <?php if (!empty($o['remains']) && $o['status'] !== 'Completed'): ?>
                <p style="font-size:.68rem;color:#d97706;"><?php echo number_format($o['remains']); ?> left</p>
                <?php endif; ?>
                <p style="font-size:.68rem;color:var(--text-muted);margin-top:3px;"><?php echo date('M d, Y', strtotime($o['created_at'])); ?></p>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="anim anim-2" style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:16px;padding:40px;text-align:center;">
    <div style="width:56px;height:56px;border-radius:50%;background:rgba(77,20,140,.07);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;">
        <i class="fas fa-list-check" style="font-size:1.4rem;color:var(--text-muted);"></i>
    </div>
    <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:6px;">No Orders Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto 16px;">You haven't placed any SMM orders yet. Start boosting your social media today!</p>
    <a href="boost" style="display:inline-flex;align-items:center;gap:8px;padding:11px 22px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.82rem;border-radius:10px;text-decoration:none;box-shadow:0 4px 14px rgba(77,20,140,.25);">
        <i class="fas fa-rocket"></i>Place First Order
    </a>
</div>
<?php endif; ?>

</div><!-- /max-w -->

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function checkOrderStatus(dbId, japOrderId) {
    Swal.fire({title:'Checking...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
    $.ajax({url:'ajax/smm_handler.php',type:'POST',data:{action:'check_status',db_order_id:dbId,jap_order_id:japOrderId},dataType:'json',
        success(res){Swal.close();if(res.status==='1'){Swal.fire({title:'Order Status',html:'<div style="text-align:left;font-size:.85rem;line-height:2;"><p><strong>Status:</strong> '+res.order_status+'</p><p><strong>Start Count:</strong> '+(res.start_count||'—')+'</p><p><strong>Remains:</strong> '+(res.remains||'0')+'</p><p><strong>Charge:</strong> '+(res.charge||'—')+'</p></div>',icon:'info',confirmButtonColor:'#4D148C',confirmButtonText:'Refresh Page'}).then(()=>location.reload());}else{Swal.fire('Error',res.msg,'error');}},
        error(){Swal.close();Swal.fire('Error','Request failed.','error');}
    });
}
function requestRefill(dbId, japOrderId) {
    Swal.fire({title:'Request Refill?',text:'This will request a refill for followers/likes that dropped.',icon:'question',showCancelButton:true,confirmButtonText:'Yes, Refill',confirmButtonColor:'#4D148C'})
        .then(r=>{if(!r.isConfirmed)return;Swal.fire({title:'Processing...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            $.ajax({url:'ajax/smm_handler.php',type:'POST',data:{action:'request_refill',db_order_id:dbId,jap_order_id:japOrderId},dataType:'json',
                success(res){Swal.close();if(res.status==='1'){Swal.fire({title:'Refill Requested!',text:res.msg,icon:'success',timer:2000,showConfirmButton:false}).then(()=>location.reload());}else{Swal.fire('Failed',res.msg,'error');}},
                error(){Swal.close();Swal.fire('Error','Request failed.','error');}
            });
        });
}
function cancelOrder(dbId, japOrderId) {
    Swal.fire({title:'Cancel Order?',html:'The undelivered portion will be <strong>refunded</strong> to your balance.',icon:'warning',showCancelButton:true,confirmButtonText:'Yes, Cancel',confirmButtonColor:'#dc2626'})
        .then(r=>{if(!r.isConfirmed)return;Swal.fire({title:'Cancelling...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            $.ajax({url:'ajax/smm_handler.php',type:'POST',data:{action:'cancel_order',db_order_id:dbId,jap_order_id:japOrderId},dataType:'json',
                success(res){Swal.close();if(res.status==='1'){Swal.fire({title:'Cancelled!',text:res.msg,icon:'success',confirmButtonColor:'#4D148C'}).then(()=>location.reload());}else{Swal.fire('Failed',res.msg,'error');}},
                error(){Swal.close();Swal.fire('Error','Request failed.','error');}
            });
        });
}
</script>

<?php include('footer.php'); ?>