<?php
require_once __DIR__ . '/config.php';
require_admin_login();

/**
 * ⚡ অটো-রিসিভ সিস্টেম
 */
$autoReceiveTime = 5; // ৫ সেকেন্ড
$pdo->prepare("UPDATE orders 
               SET status = 'received' 
               WHERE status = 'pending' 
               AND created_at <= (NOW() - INTERVAL ? SECOND)")
    ->execute([$autoReceiveTime]);


// 🧾 Handle updates (ম্যানুয়াল আপডেট)
if (is_post()) {
    verify_csrf();
    if (isset($_POST['order_update'])) {
        $oid = (int)($_POST['oid'] ?? 0);
        $status = $_POST['status'] ?? 'pending';
        $admin_msg = $_POST['admin_message'] ?? '';
        $cancel_reason = $_POST['cancel_reason'] ?? null;
        $delivery_type = $_POST['delivery_type'] ?? 'none';
        $delivery_text = $_POST['delivery_text'] ?? null;
        $delivery_file = $_FILES['delivery_file'] ?? null;
        $file_name = null;

        if ($status === 'cancelled') {
            try {
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("SELECT user_id, price, status FROM orders WHERE id=?");
                $stmt->execute([$oid]);
                $order = $stmt->fetch();

                if ($order && $order['status'] !== 'cancelled') {
                    $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")
                        ->execute([$order['price'], $order['user_id']]);
                    $pdo->prepare("UPDATE orders SET status=?, admin_message=?, cancel_reason=? WHERE id=?")
                        ->execute(['cancelled', $admin_msg, $cancel_reason, $oid]);
                    set_flash("Order #{$oid} cancelled & refunded.", "success");
                }
                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                set_flash("Refund error: ".$e->getMessage(), "danger");
            }
        } else {
            if ($delivery_file && $delivery_file['tmp_name']) {
                $ext = pathinfo($delivery_file['name'], PATHINFO_EXTENSION);
                $file_name = "delivery_{$oid}_" . time() . ".$ext";
                move_uploaded_file($delivery_file['tmp_name'], "../uploads/$file_name");
            }

            $stmt = $pdo->prepare("UPDATE orders 
                SET status=?, admin_message=?, cancel_reason=?, delivery_type=?, delivery_text=?, 
                    delivery_file=COALESCE(?, delivery_file)
                WHERE id=?");
            $stmt->execute([$status, $admin_msg, $cancel_reason, $delivery_type, $delivery_text, $file_name, $oid]);
            set_flash("Order #{$oid} updated successfully!", "success");
        }

        redirect('orders.php?tab=' . h($status));
    }
}

// 🧩 Fetch data
$search = trim($_GET['search'] ?? '');
$params = [];
$sql = "SELECT o.*, u.email, s.name AS service_name, sc.name AS subcategory_name
        FROM orders o 
        JOIN users u ON u.id=o.user_id 
        JOIN services s ON s.id=o.service_id 
        JOIN subcategories sc ON sc.id=o.subcategory_id";
if ($search !== '') {
    $sql .= " WHERE u.email LIKE ? OR o.id_number LIKE ?";
    $params = ["%$search%", "%$search%"];
}
$sql .= " ORDER BY o.id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$orders_all = $stmt->fetchAll();

// ফিল্টারিং লিস্ট
$pending = array_filter($orders_all, fn($o)=>$o['status']=='pending');
$received = array_filter($orders_all, fn($o)=>$o['status']=='received');
$completed = array_filter($orders_all, fn($o)=>$o['status']=='completed');
$cancelled = array_filter($orders_all, fn($o)=>$o['status']=='cancelled');
$active_tab = $_GET['tab'] ?? 'pending';

require_once 'header.php';
?>

<style>
:root{
 --primary: #230133;
 --success:#34c38f;
 --danger:#f46a6a;
 --warning:#f1b44c;
 --info:#50a5f1;
 --brand-hover: #3b0354;
}

.text-primary { color: var(--primary) !important; }

/* Notification Animation */
@keyframes pulse-red {
  0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(80, 165, 241, 0.7); }
  70% { transform: scale(1.02); box-shadow: 0 0 0 10px rgba(80, 165, 241, 0); }
  100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(80, 165, 241, 0); }
}
.notif-box {
    background: #eef7ff;
    border-left: 5px solid var(--info);
    animation: pulse-red 2s infinite;
}

.summary-card{
 border-radius:16px;
 box-shadow:0 4px 12px rgba(0,0,0,0.05);
 background:#fff;
 transition:all .25s;
 border-top: 4px solid var(--primary);
}
.summary-card:hover{ transform:translateY(-3px); box-shadow:0 8px 20px rgba(0,0,0,0.1);}
.summary-card h2{ font-size:2rem; margin:0;}

.badge-status{
 padding:0.4em 0.8em; border-radius:8px; font-size:0.85rem;
}
.bg-pending{background:var(--warning)!important; color:#000;}
.bg-received{background:var(--info)!important; color:#fff;}
.bg-completed{background:var(--success)!important; color:#fff;}
.bg-cancelled{background:var(--danger)!important; color:#fff;}

.order-card{
 border: 1px solid #eee; border-radius:14px; background:#fff;
 box-shadow:0 4px 10px rgba(0,0,0,0.05); transition:.25s;
}
.order-card:hover{ transform:translateY(-3px); border-color: var(--primary); }

.btn-primary {
    background-color: var(--primary) !important;
    border-color: var(--primary) !important;
}
.btn-primary:hover {
    background-color: var(--brand-hover) !important;
}

.nav-tabs .nav-link { color: #666; font-weight: 600; }
.nav-tabs .nav-link.active {
    color: var(--primary) !important;
    border-bottom: 3px solid var(--primary) !important;
}

@media (max-width:768px){
 .summary-card h2{font-size:1.5rem;}
}
</style>

<div class="container-fluid py-3">
 
 <!-- 🔔 নতুন নোটিফিকেশন সিস্টেম (সাউন্ডসহ) -->
 <?php if (count($received) > 0): ?>
    <audio id="adminNotifSound" loop>
        <source src="https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3" type="audio/mpeg">
    </audio>
    <div class="alert notif-box d-flex align-items-center mb-4">
        <i class="bi bi-megaphone-fill fs-3 me-3 text-info"></i>
        <div class="flex-grow-1">
            <h6 class="mb-0 fw-bold text-dark">নতুন অর্ডার রিসিভ হয়েছে!</h6>
            <p class="mb-0 small text-muted">বর্তমানে <strong><?php echo count($received); ?>টি</strong> অর্ডার Received অবস্থায় আছে।</p>
        </div>
        <button class="btn btn-sm btn-secondary fw-bold" onclick="document.getElementById('adminNotifSound').pause();">সাউন্ড বন্ধ করুন</button>
    </div>
    <script>
        const audio = document.getElementById('adminNotifSound');
        function playAlert() {
            audio.play().catch(e => console.log("সাউন্ড বাজানোর জন্য ইউজার ইন্টারঅ্যাকশন প্রয়োজন।"));
        }
        // পেজ লোড হলে এবং প্রথম ক্লিকে সাউন্ড চালু হবে
        window.addEventListener('load', playAlert);
        document.addEventListener('click', playAlert, { once: true });
    </script>
 <?php endif; ?>

 <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4">
   <h1 class="h3 text-primary fw-bold mb-0"><i class="bi bi-list-check me-2"></i>Orders Overview</h1>
   <form method="get" class="d-flex">
     <input type="text" name="search" class="form-control me-2 border-primary" placeholder="Search..." value="<?php echo h($search); ?>" style="width:200px;">
     <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i></button>
   </form>
 </div>

 <div class="row g-3 mb-4 text-center">
  <div class="col-6 col-md-3">
   <div class="summary-card p-3" style="border-top-color: var(--warning);">
    <small class="text-muted uppercase fw-bold">Pending</small>
    <h2 class="fw-bold text-warning mb-0"><?php echo count($pending); ?></h2>
   </div>
  </div>
  <div class="col-6 col-md-3">
   <div class="summary-card p-3" style="border-top-color: var(--info);">
    <small class="text-muted uppercase fw-bold">Received</small>
    <h2 class="fw-bold text-info mb-0"><?php echo count($received); ?></h2>
   </div>
  </div>
  <div class="col-6 col-md-3">
   <div class="summary-card p-3" style="border-top-color: var(--success);">
    <small class="text-muted uppercase fw-bold">Completed</small>
    <h2 class="fw-bold text-success mb-0"><?php echo count($completed); ?></h2>
   </div>
  </div>
  <div class="col-6 col-md-3">
   <div class="summary-card p-3" style="border-top-color: var(--danger);">
    <small class="text-muted uppercase fw-bold">Cancelled</small>
    <h2 class="fw-bold text-danger mb-0"><?php echo count($cancelled); ?></h2>
   </div>
  </div>
 </div>

 <ul class="nav nav-tabs nav-fill mb-4">
  <li class="nav-item"><a class="nav-link <?php if($active_tab=='pending')echo'active';?>" href="?tab=pending">Pending</a></li>
  <li class="nav-item"><a class="nav-link <?php if($active_tab=='received')echo'active';?>" href="?tab=received">Received</a></li>
  <li class="nav-item"><a class="nav-link <?php if($active_tab=='completed')echo'active';?>" href="?tab=completed">Completed</a></li>
  <li class="nav-item"><a class="nav-link <?php if($active_tab=='cancelled')echo'active';?>" href="?tab=cancelled">Cancelled</a></li>
 </ul>

 <div class="row g-3">
  <?php
   if($active_tab == 'completed') $showList = $completed;
   elseif($active_tab == 'cancelled') $showList = $cancelled;
   elseif($active_tab == 'received') $showList = $received;
   else $showList = $pending;

   if(!$showList){ echo "<div class='text-center p-5 w-100'><i class='bi bi-inbox fs-1 text-muted'></i><h5 class='text-muted'>No orders found here.</h5></div>";}
   else foreach($showList as $o): ?>
   <div class="col-lg-4 col-md-6">
     <div class="order-card p-3 h-100">
       <div class="d-flex justify-content-between align-items-center mb-2">
         <h6 class="fw-bold text-primary m-0">Order #<?php echo $o['id']; ?></h6>
         <span class="badge-status 
          <?php if($o['status']=='completed')echo'bg-completed';
                elseif($o['status']=='cancelled')echo'bg-cancelled';
                elseif($o['status']=='received')echo'bg-received';
                else echo'bg-pending'; ?>">
          <?php echo ucfirst($o['status']); ?></span>
       </div>
       <ul class="list-unstyled small mb-3">
         <li class="mb-1"><strong>User:</strong> <?php echo h($o['email']); ?></li>
         <li class="mb-1"><strong>Service:</strong> <?php echo h($o['service_name']); ?></li>
         <li class="mb-1"><strong>Category:</strong> <?php echo h($o['subcategory_name']); ?></li>
         <li class="mb-1"><strong>Player ID:</strong> <span class="badge bg-light text-dark border"><?php echo h($o['id_number']); ?></span></li>
       </ul>
       <a class="btn btn-outline-secondary btn-sm w-100 fw-bold" data-bs-toggle="collapse" href="#u<?php echo $o['id']; ?>">
         <i class="bi bi-pencil-square me-1"></i> Update Status
       </a>
       <div class="collapse mt-3" id="u<?php echo $o['id']; ?>">
         <div class="card card-body border-primary-light">
           <form method="post" enctype="multipart/form-data">
             <?php csrf_field(); ?>
             <input type="hidden" name="oid" value="<?php echo $o['id']; ?>">
             <div class="mb-2">
               <label class="form-label small fw-bold">Admin Message</label>
               <textarea name="admin_message" class="form-control form-control-sm"><?php echo h($o['admin_message']); ?></textarea>
             </div>
             <div class="mb-2">
               <label class="form-label small fw-bold text-danger">Cancel Reason (If Cancel)</label>
               <input type="text" name="cancel_reason" class="form-control form-control-sm" value="<?php echo h($o['cancel_reason']); ?>">
             </div>
             <div class="mb-2">
               <label class="form-label small fw-bold">Set Status</label>
               <select name="status" class="form-select form-select-sm">
                 <option value="pending" <?php if($o['status']=='pending')echo'selected';?>>Pending</option>
                 <option value="received" <?php if($o['status']=='received')echo'selected';?>>Received</option>
                 <option value="completed" <?php if($o['status']=='completed')echo'selected';?>>Completed</option>
                 <option value="cancelled" <?php if($o['status']=='cancelled')echo'selected';?>>Cancelled</option>
               </select>
             </div>
             <div class="mb-2">
               <label class="form-label small fw-bold">Delivery Type</label>
               <select name="delivery_type" class="form-select form-select-sm" onchange="toggleDelivery(<?php echo $o['id'];?>,this)">
                 <option value="none">None</option>
                 <option value="text" <?php if($o['delivery_type']=='text')echo'selected';?>>Text Info</option>
                 <option value="file" <?php if($o['delivery_type']=='file')echo'selected';?>>File/Screenshot</option>
               </select>
             </div>
             <div id="textField<?php echo $o['id'];?>" class="mb-2" style="display:<?php echo $o['delivery_type']=='text'?'block':'none';?>">
               <label class="form-label small">Delivery Text</label>
               <textarea name="delivery_text" class="form-control form-control-sm" rows="3"><?php echo h($o['delivery_text']); ?></textarea>
             </div>
             <div id="fileField<?php echo $o['id'];?>" class="mb-2" style="display:<?php echo $o['delivery_type']=='file'?'block':'none';?>">
               <label class="form-label small">Delivery File</label>
               <input type="file" name="delivery_file" class="form-control form-control-sm">
             </div>
             <button class="btn btn-primary btn-sm w-100 fw-bold" name="order_update">Save Changes</button>
           </form>
         </div>
       </div>
     </div>
   </div>
  <?php endforeach; ?>
 </div>
</div>

<script>
function toggleDelivery(id,sel){
 document.getElementById('textField'+id).style.display=(sel.value==='text')?'block':'none';
 document.getElementById('fileField'+id).style.display=(sel.value==='file')?'block':'none';
}
</script>

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