<?php
require_once 'header.php';

$success = '';
$error = '';

if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = $_GET['action'];
    $order_id = (int)$_GET['id'];

    if ($action === 'approve') {
        $stmt = $pdo->prepare("UPDATE orders SET status = 'approved', approved_at = NOW() WHERE id = ?");
        if ($stmt->execute([$order_id])) {
            $success = "Order has been successfully approved! User can now download the file.";
        } else {
            $error = "Failed to approve order.";
        }
    } elseif ($action === 'reject') {
        $stmt = $pdo->prepare("UPDATE orders SET status = 'failed' WHERE id = ?");
        if ($stmt->execute([$order_id])) {
            $success = "Order has been rejected/marked as failed.";
        }
    } elseif ($action === 'delete') {
        $stmt = $pdo->prepare("DELETE FROM orders WHERE id = ?");
        if ($stmt->execute([$order_id])) {
            $success = "Order deleted permanently.";
        }
    }
}

$stmt = $pdo->query("
    SELECT o.*, u.name as user_name, u.email as user_email, p.title as product_title 
    FROM orders o 
    LEFT JOIN users u ON o.user_id = u.id 
    LEFT JOIN products p ON o.product_id = p.id 
    ORDER BY o.id DESC
");
$orders = $stmt->fetchAll();
$total_orders = count($orders);

$currency = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳';
if (is_numeric($currency)) {
    $currency = '৳';
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&family=Noto+Serif+Bengali:wght@300;400;500;600;700&display=swap');

    :root {
        --primary: #84cc16; 
        --primary-hover: #65a30d;
        --bg-light: #f8fafc;
        --card-bg: #ffffff;
        --border: #e2e8f0;
        --text-main: #0f172a;
        --text-muted: #64748b;
    }

    * {
        box-sizing: border-box;
    }

    body { 
        background: var(--bg-light); 
        color: var(--text-main); 
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif; 
        margin: 0; 
        overflow-x: hidden;
    }
    
    .settings-container { 
        max-width: 1000px; 
        margin: 0 auto; 
        padding: 15px; 
        width: 100%;
    }

    .page-header { 
        display: flex; justify-content: space-between; align-items: center; 
        margin-bottom: 15px; flex-wrap: wrap; gap: 10px; 
    }
    
    .page-title { 
        font-size: 1.3rem; font-weight: 800; color: var(--text-main); margin: 0; 
    }

    .total-orders-badge {
        background: #f4fce3;
        color: #65a30d;
        padding: 6px 14px;
        border-radius: 20px;
        font-weight: 700;
        font-size: 0.9rem;
        border: 1px solid #d9f99d;
    }

    .orders-list { 
        display: flex; flex-direction: column; gap: 12px; margin-bottom: 30px; 
    }
    
    .order-card { 
        background: var(--card-bg); 
        border: 1px solid var(--border); 
        border-radius: 6px; 
        box-shadow: none !important; 
        overflow: hidden;
        transition: border-color 0.3s ease;
        max-width: 100%;
    }
    
    .order-card:hover {
        border-color: #cbd5e1;
    }

    .order-header { 
        display: flex; justify-content: space-between; align-items: center; 
        padding: 10px 15px; border-bottom: 1px solid var(--border); background: #f1f5f9; 
        flex-wrap: wrap; gap: 8px;
    }

    .invoice-wrap { display: flex; align-items: center; gap: 6px; min-width: 0; }
    .invoice-label { font-size: 0.75rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; }
    .invoice-id { font-weight: 800; color: var(--primary); font-family: monospace; font-size: 1rem; word-break: break-all; }

    .order-body { 
        padding: 15px; 
        display: grid; 
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); 
        gap: 15px; 
    }

    .info-block { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
    .block-title { font-size: 0.75rem; text-transform: uppercase; color: var(--text-muted); font-weight: 700; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; margin-bottom: 2px;}
    
    .main-val { font-size: 0.9rem; color: var(--text-main); font-weight: 700; line-height: 1.3; word-wrap: break-word; }
    .sub-val { font-size: 0.8rem; color: var(--text-muted); font-weight: 500; display: flex; align-items: center; gap: 5px; word-break: break-all; }

    .gateway-block { background: #f8fafc; padding: 10px; border-radius: 4px; border: 1px solid #e2e8f0; }
    .gateway-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; font-size: 0.8rem; flex-wrap: wrap; gap: 4px; }
    .gateway-row:last-child { margin-bottom: 0; }
    .gateway-row span:first-child { color: var(--text-muted); font-weight: 600; }
    
    .gateway-amount { font-size: 1.1rem; font-weight: 800; color: var(--primary); }

    .badge-solid { padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: 700; display: inline-block; font-family: monospace; word-break: break-all;}
    .badge-method { background: #334155; color: #ffffff; }
    .badge-trx { background: #0f172a; color: #ffffff; text-align: right;}

    .status-badge { padding: 4px 10px; border-radius: 4px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; display: inline-flex; align-items: center; letter-spacing: 0.5px; }
    .status-approved { background: #10b981; color: #ffffff; }
    .status-pending { background: #f59e0b; color: #ffffff; }
    .status-failed { background: #ef4444; color: #ffffff; }

    .order-footer { 
        padding: 10px 15px; 
        border-top: 1px solid var(--border); 
        display: flex; 
        justify-content: flex-end; 
        background: #ffffff; 
        gap: 8px; 
        flex-wrap: wrap;
    }

    .btn-action { font-size: 0.8rem; font-weight: 700; padding: 8px 14px; border-radius: 4px; text-decoration: none; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: none; cursor: pointer; white-space: nowrap; box-shadow: none !important;}
    
    .btn-approve { background: #10b981; color: white; }
    .btn-approve:hover { background: #059669; }
    
    .btn-reject { background: #f59e0b; color: white; }
    .btn-reject:hover { background: #d97706; }
    
    .btn-delete { background: #ef4444; color: white; }
    .btn-delete:hover { background: #dc2626; }

    .toast-success { background: #10b981 !important; color: #fff !important; font-weight: 700; border-radius: 4px !important; box-shadow: none !important; border: none !important; padding: 10px 20px !important;}
    .toast-error { background: #ef4444 !important; color: #fff !important; font-weight: 700; border-radius: 4px !important; box-shadow: none !important; border: none !important; padding: 10px 20px !important;}

    @media (max-width: 576px) {
        .settings-container { padding: 10px; }
        .order-header { flex-direction: column; align-items: flex-start; padding: 10px; }
        .order-body { grid-template-columns: 1fr; gap: 12px; padding: 10px; }
        .order-footer { flex-direction: column; justify-content: stretch; padding: 10px; }
        .btn-action { width: 100%; }
        .gateway-row { flex-direction: column; align-items: flex-start; }
        .badge-trx { text-align: left; }
    }
</style>

<div class="settings-container">
    <div class="page-header">
        <h1 class="page-title">Manage Orders</h1>
        <span class="total-orders-badge">Total Orders: <?php echo $total_orders; ?></span>
    </div>

    <div class="orders-list">
        <?php foreach($orders as $o): ?>
            <div class="order-card">
                
                <div class="order-header">
                    <div class="invoice-wrap">
                        <span class="invoice-label">Invoice</span>
                        <span class="invoice-id">#<?php echo htmlspecialchars($o['invoice_no']); ?></span>
                    </div>
                    <?php 
                        $status_class = 'status-pending'; 
                        if ($o['status'] === 'approved' || $o['status'] === 'completed') $status_class = 'status-approved';
                        if ($o['status'] === 'failed' || $o['status'] === 'rejected') $status_class = 'status-failed';
                    ?>
                    <div class="status-badge <?php echo $status_class; ?>">
                        <?php echo htmlspecialchars($o['status']); ?>
                    </div>
                </div>
                
                <div class="order-body">
                    <div class="info-block">
                        <div class="block-title">Customer</div>
                        <div class="main-val"><?php echo htmlspecialchars($o['user_name'] ?? 'Guest'); ?></div>
                        <div class="sub-val">
                            <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                            <?php echo htmlspecialchars($o['user_email'] ?? 'No Email'); ?>
                        </div>
                        <?php if(!empty($o['user_phone'])): ?>
                        <div class="sub-val">
                            <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/></svg>
                            <?php echo htmlspecialchars($o['user_phone']); ?>
                        </div>
                        <?php endif; ?>
                    </div>

                    <div class="info-block">
                        <div class="block-title">Product</div>
                        <div class="main-val"><?php echo htmlspecialchars($o['product_title'] ?? 'Unknown Product'); ?></div>
                        <div class="sub-val" style="margin-top: 4px;">
                            <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                            <?php echo date('d M Y, h:i A', strtotime($o['created_at'])); ?>
                        </div>
                    </div>

                    <div class="info-block gateway-block">
                        <div class="block-title" style="border-bottom: none; margin-bottom: 6px;">Payment</div>
                        
                        <div class="gateway-row">
                            <span>Amount</span>
                            <span class="gateway-amount"><?php echo $currency . number_format($o['amount'], 2); ?></span>
                        </div>
                        
                        <div class="gateway-row">
                            <span>Gateway</span>
                            <span class="badge-solid badge-method"><?php echo htmlspecialchars(strtoupper($o['payment_method'] ?? 'AutoPay')); ?></span>
                        </div>
                        
                        <div class="gateway-row">
                            <span>TrxID</span>
                            <span class="badge-solid badge-trx"><?php echo htmlspecialchars($o['transaction_id'] ?? 'N/A'); ?></span>
                        </div>

                        <?php if(!empty($o['sender_number'])): ?>
                        <div class="gateway-row" style="margin-top: 4px; border-top: 1px dashed #cbd5e1; padding-top: 8px;">
                            <span>Sender A/C</span>
                            <strong style="color: #0f172a; font-size:0.85rem; word-break: break-all;"><?php echo htmlspecialchars($o['sender_number']); ?></strong>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="order-footer">
                    <?php if ($o['status'] === 'pending'): ?>
                        <a href="?action=approve&id=<?php echo $o['id']; ?>" class="btn-action btn-approve" onclick="return confirm('Approve this order? User will get download access.');">
                            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                            Approve
                        </a>
                        <a href="?action=reject&id=<?php echo $o['id']; ?>" class="btn-action btn-reject" onclick="return confirm('Reject this order?');">
                            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                            Reject
                        </a>
                    <?php endif; ?>
                    <a href="?action=delete&id=<?php echo $o['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Delete this order permanently?');">
                        <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                        Delete
                    </a>
                </div>

            </div>
        <?php endforeach; ?>
        
        <?php if(count($orders) == 0): ?>
            <div style="text-align: center; padding: 40px 15px; color: var(--text-muted); border: 1px solid var(--border); border-radius: 6px; background: var(--card-bg);">
                <svg width="40" height="40" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24" style="margin-bottom: 10px; color: #cbd5e1;"><path stroke-linecap="round" stroke-linejoin="round" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"/></svg><br>
                <span style="font-size: 1rem; color: #0f172a; font-weight: 700;">No Orders Found</span><br>
                <span style="font-size: 0.85rem;">There are no transactions to display at this time.</span>
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script>
    <?php if($success): ?>
    Toastify({
        text: "<?php echo addslashes($success); ?>",
        duration: 3000,
        gravity: "top", 
        position: "center",
        className: "toast-success",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    <?php if($error): ?>
    Toastify({
        text: "<?php echo addslashes($error); ?>",
        duration: 4000,
        gravity: "top", 
        position: "center",
        className: "toast-error",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>
</script>

<?php require_once 'footer.php'; ?>
