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

// ── Filter params ─────────────────────────────────────────────────────
$search        = isset($_GET['search'])    ? trim($_GET['search'])    : '';
$filter_status = isset($_GET['status'])    ? trim($_GET['status'])    : 'all';
$date_from     = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$date_to       = isset($_GET['date_to'])   ? trim($_GET['date_to'])   : '';

// ── Build WHERE ───────────────────────────────────────────────────────
$where  = "WHERE 1=1";
$params = [];

if ($filter_status !== 'all') {
    $where .= " AND o.status = :status";
    $params['status'] = $filter_status;
}
if (!empty($search)) {
    $where .= " AND (u.username LIKE :s1 OR u.full_name LIKE :s2 OR u.email LIKE :s3
                  OR o.link LIKE :s4 OR ss.name LIKE :s5 OR o.jap_order_id LIKE :s6
                  OR o.id LIKE :s7)";
    $params['s1'] = "%$search%"; $params['s2'] = "%$search%";
    $params['s3'] = "%$search%"; $params['s4'] = "%$search%";
    $params['s5'] = "%$search%"; $params['s6'] = "%$search%";
    $params['s7'] = "%$search%";
}
if (!empty($date_from)) {
    $where .= " AND DATE(o.created_at) >= :date_from";
    $params['date_from'] = $date_from;
}
if (!empty($date_to)) {
    $where .= " AND DATE(o.created_at) <= :date_to";
    $params['date_to'] = $date_to;
}

// ── Fetch orders ──────────────────────────────────────────────────────
try {
    $stmt = $pdo->prepare("
        SELECT o.*,
               u.username, u.full_name, u.email,
               ss.name AS service_name, ss.category AS service_category
        FROM smm_orders o
        LEFT JOIN users u         ON o.user_id = u.id
        LEFT JOIN smm_services ss ON o.smm_service_id = ss.id
        $where
        ORDER BY o.created_at DESC
    ");
    $stmt->execute($params);
    $orders      = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $total_count = count($orders);
} catch (PDOException $e) {
    $orders      = [];
    $total_count = 0;
    error_log("SMM orders fetch error: " . $e->getMessage());
}

// ── Global stats ──────────────────────────────────────────────────────
try {
    $stats_stmt = $pdo->query("
        SELECT
            COUNT(*)                                                    AS total_orders,
            SUM(CASE WHEN status='Completed'   THEN 1 ELSE 0 END)      AS completed,
            SUM(CASE WHEN status='Pending'     THEN 1 ELSE 0 END)      AS pending,
            SUM(CASE WHEN status='In progress' THEN 1 ELSE 0 END)      AS in_progress,
            SUM(CASE WHEN status='Processing'  THEN 1 ELSE 0 END)      AS processing,
            SUM(CASE WHEN status='Partial'     THEN 1 ELSE 0 END)      AS partial,
            SUM(CASE WHEN status='Cancelled'   THEN 1 ELSE 0 END)      AS cancelled,
            SUM(CASE WHEN status='Refunded'    THEN 1 ELSE 0 END)      AS refunded,
            SUM(charge)                                                 AS total_revenue,
            SUM(CASE WHEN status='Completed' THEN charge ELSE 0 END)   AS completed_revenue,
            SUM(quantity)                                               AS total_quantity
        FROM smm_orders
    ");
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $stats = array_fill_keys(['total_orders','completed','pending','in_progress','processing','partial','cancelled','refunded','total_revenue','completed_revenue','total_quantity'], 0);
}

// ── Today's stats ─────────────────────────────────────────────────────
try {
    $today_stmt = $pdo->query("
        SELECT
            COUNT(*)         AS today_orders,
            SUM(charge)      AS today_revenue
        FROM smm_orders
        WHERE DATE(created_at) = CURDATE()
    ");
    $today = $today_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $today = ['today_orders' => 0, 'today_revenue' => 0];
}

// ── Top 5 services by order count ────────────────────────────────────
try {
    $top_stmt = $pdo->query("
        SELECT ss.name AS service_name, ss.category,
               COUNT(*) AS order_count,
               SUM(o.charge) AS total_revenue
        FROM smm_orders o
        LEFT JOIN smm_services ss ON o.smm_service_id = ss.id
        GROUP BY o.smm_service_id
        ORDER BY order_count DESC
        LIMIT 5
    ");
    $top_services = $top_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $top_services = [];
}

// ── Status colour map ─────────────────────────────────────────────────
$status_colors = [
    'Pending'     => ['bg' => '#fef3c7', 'color' => '#92400e', 'icon' => 'fa-clock'],
    'In progress' => ['bg' => '#dbeafe', 'color' => '#1e40af', 'icon' => 'fa-spinner'],
    'Processing'  => ['bg' => '#ede9fe', 'color' => '#5b21b6', 'icon' => 'fa-cog'],
    'Completed'   => ['bg' => '#d1fae5', 'color' => '#065f46', 'icon' => 'fa-check-circle'],
    'Partial'     => ['bg' => '#fff7ed', 'color' => '#c2410c', 'icon' => 'fa-adjust'],
    'Cancelled'   => ['bg' => '#fee2e2', 'color' => '#991b1b', 'icon' => 'fa-times-circle'],
    'Refunded'    => ['bg' => '#f3f4f6', 'color' => '#374151', 'icon' => 'fa-undo'],
];
?>
<title>SMM Orders - <?php echo $site_data['web_name']; ?></title>
<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

<style>
    .stat-card { border-left: 4px solid; transition: transform 0.2s; }
    .stat-card:hover { transform: translateY(-4px); }
    .status-pill {
        display:inline-block; padding:3px 10px; border-radius:20px;
        font-size:0.72rem; font-weight:700; white-space:nowrap;
    }
    .revenue-sub { font-size:0.7rem; font-weight:600; padding:2px 7px; border-radius:10px;
                   background:#d1fae5; color:#065f46; display:inline-block; margin-top:4px; }
    .link-cell { max-width:180px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
    .link-cell a { font-size:0.78rem; color:#4e73df; }
    .table td { vertical-align:middle; }
    code { color:#e83e8c; background:#f8f9fc; padding:2px 5px; border-radius:3px; font-size:0.8em; }
    .overview-icon { width:44px; height:44px; border-radius:50%; display:flex; align-items:center; justify-content:center; margin:0 auto 8px; }
</style>

<div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">SMM Orders</h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">SMM Orders</li>
        </ol>
    </div>

    <!-- ── Row 1: Main Stat Cards ── -->
    <div class="row mb-4">
        <!-- Total Orders -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#4e73df;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Total Orders</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['total_orders']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-shopping-cart fa-2x text-primary"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Total Revenue -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#1cc88a;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Total Revenue</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">₦<?php echo number_format((float)$stats['total_revenue'], 2); ?></div>
                            <div class="revenue-sub"><i class="fas fa-check-circle mr-1"></i>₦<?php echo number_format((float)$stats['completed_revenue'], 2); ?> completed</div>
                        </div>
                        <div class="col-auto"><i class="fas fa-naira-sign fa-2x text-success"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Today -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#36b9cc;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Today's Orders</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($today['today_orders']); ?></div>
                            <div class="revenue-sub"><i class="fas fa-money-bill mr-1"></i>₦<?php echo number_format((float)$today['today_revenue'], 2); ?> today</div>
                        </div>
                        <div class="col-auto"><i class="fas fa-calendar-day fa-2x text-info"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Total Quantity -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#f6c23e;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Total Quantity</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['total_quantity']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-layer-group fa-2x text-warning"></i></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ── Row 2: Status Overview + Top Services ── -->
    <div class="row mb-4">
        <!-- Status Overview -->
        <div class="col-lg-7 mb-4">
            <div class="card h-100">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-chart-pie mr-2"></i>Order Status Overview
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <?php
                        $status_overview = [
                            ['label'=>'Completed',   'count'=>$stats['completed'],   'icon'=>'fa-check-circle', 'color'=>'text-success'],
                            ['label'=>'Pending',     'count'=>$stats['pending'],     'icon'=>'fa-clock',        'color'=>'text-warning'],
                            ['label'=>'In Progress', 'count'=>$stats['in_progress'], 'icon'=>'fa-spinner',      'color'=>'text-primary'],
                            ['label'=>'Processing',  'count'=>$stats['processing'],  'icon'=>'fa-cog',          'color'=>'text-info'],
                            ['label'=>'Partial',     'count'=>$stats['partial'],     'icon'=>'fa-adjust',       'color'=>'text-orange'],
                            ['label'=>'Cancelled',   'count'=>$stats['cancelled'],   'icon'=>'fa-times-circle', 'color'=>'text-danger'],
                            ['label'=>'Refunded',    'count'=>$stats['refunded'],    'icon'=>'fa-undo',         'color'=>'text-secondary'],
                        ];
                        foreach ($status_overview as $s):
                        ?>
                        <div class="col-md-3 col-6 mb-3">
                            <i class="fas <?php echo $s['icon']; ?> fa-2x <?php echo $s['color']; ?> mb-1"></i>
                            <h5 class="font-weight-bold mb-0"><?php echo number_format($s['count']); ?></h5>
                            <small class="text-muted"><?php echo $s['label']; ?></small>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        <!-- Top 5 Services -->
        <div class="col-lg-5 mb-4">
            <div class="card h-100">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-trophy mr-2"></i>Top 5 Services by Orders
                    </h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead class="thead-light">
                                <tr>
                                    <th>#</th>
                                    <th>Service</th>
                                    <th>Orders</th>
                                    <th>Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($top_services)):
                                    $rank = 0; foreach ($top_services as $ts): $rank++;
                                    $medal = $rank == 1 ? '🥇' : ($rank == 2 ? '🥈' : ($rank == 3 ? '🥉' : $rank)); ?>
                                <tr>
                                    <td><strong><?php echo $medal; ?></strong></td>
                                    <td style="max-width:160px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
                                        <small title="<?php echo htmlspecialchars($ts['service_name'] ?? 'N/A'); ?>">
                                            <?php echo htmlspecialchars($ts['service_name'] ?? 'N/A'); ?>
                                        </small>
                                    </td>
                                    <td><span class="badge badge-primary"><?php echo number_format($ts['order_count']); ?></span></td>
                                    <td><small class="text-success font-weight-bold">₦<?php echo number_format((float)$ts['total_revenue'], 2); ?></small></td>
                                </tr>
                                <?php endforeach; else: ?>
                                <tr><td colspan="4" class="text-center text-muted py-3">No data available</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ── Filters ── -->
    <div class="card mb-4">
        <div class="card-body py-3">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-4 mb-2">
                        <input type="text" name="search" class="form-control"
                               placeholder="Search user, link, service, Owlet order ID..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2 mb-2">
                        <select name="status" class="form-control">
                            <option value="all"        <?php echo $filter_status==='all'         ? 'selected':''; ?>>All Status</option>
                            <option value="Pending"    <?php echo $filter_status==='Pending'     ? 'selected':''; ?>>Pending</option>
                            <option value="In progress"<?php echo $filter_status==='In progress' ? 'selected':''; ?>>In Progress</option>
                            <option value="Processing" <?php echo $filter_status==='Processing'  ? 'selected':''; ?>>Processing</option>
                            <option value="Completed"  <?php echo $filter_status==='Completed'   ? 'selected':''; ?>>Completed</option>
                            <option value="Partial"    <?php echo $filter_status==='Partial'     ? 'selected':''; ?>>Partial</option>
                            <option value="Cancelled"  <?php echo $filter_status==='Cancelled'   ? 'selected':''; ?>>Cancelled</option>
                            <option value="Refunded"   <?php echo $filter_status==='Refunded'    ? 'selected':''; ?>>Refunded</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <input type="date" name="date_from" class="form-control"
                               value="<?php echo htmlspecialchars($date_from); ?>" placeholder="Date From">
                    </div>
                    <div class="col-md-2 mb-2">
                        <input type="date" name="date_to" class="form-control"
                               value="<?php echo htmlspecialchars($date_to); ?>" placeholder="Date To">
                    </div>
                    <div class="col-md-1 mb-2">
                        <button type="submit" class="btn btn-primary btn-block">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                    <div class="col-md-1 mb-2">
                        <button type="button" class="btn btn-success btn-block" onclick="exportToExcel()" title="Export Excel">
                            <i class="fas fa-file-excel"></i>
                        </button>
                    </div>
                </div>
                <?php if ($search || $filter_status !== 'all' || $date_from || $date_to): ?>
                <div class="row mt-1">
                    <div class="col-12">
                        <a href="smm-orders.php" class="btn btn-secondary btn-sm">
                            <i class="fas fa-redo mr-1"></i> Reset Filters
                        </a>
                        <span class="ml-2 text-muted small">Showing <strong><?php echo $total_count; ?></strong> result(s)</span>
                    </div>
                </div>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <!-- ── Orders Table ── -->
    <div class="row">
        <div class="col-lg-12">
            <div class="card mb-4">
                <div class="card-header py-3 d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-list mr-2"></i>All SMM Orders
                        <span class="badge badge-primary ml-2"><?php echo number_format($total_count); ?></span>
                    </h6>
                </div>
                <div class="table-responsive p-3">
                    <?php if (!empty($orders)): ?>
                    <table class="table table-flush table-hover align-items-center" id="dataTable">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Order ID</th>
                                <th>Owlet Order ID</th>
                                <th>User</th>
                                <th>Service</th>
                                <th>Link</th>
                                <th>Qty</th>
                                <th>Charge (₦)</th>
                                <th>Owlet Cost ($)</th>
                                <th>Remains</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; foreach ($orders as $row):
                                $st = $row['status'];
                                $sc = $status_colors[$st] ?? ['bg'=>'#f3f4f6','color'=>'#374151','icon'=>'fa-question-circle'];
                                $display_name = !empty($row['full_name']) ? $row['full_name'] : ($row['username'] ?? '—');
                                $js_status = addslashes(htmlspecialchars($st, ENT_QUOTES));
                                $js_notes  = addslashes(htmlspecialchars($row['notes'] ?? '', ENT_QUOTES));
                                $js_link   = addslashes(htmlspecialchars($row['link'], ENT_QUOTES));
                            ?>
                            <tr>
                                <td><?php echo $i++; ?></td>
                                <td><code>#<?php echo (int)$row['id']; ?></code></td>
                                <td>
                                    <?php if ($row['jap_order_id']): ?>
                                        <code class="text-muted"><?php echo (int)$row['jap_order_id']; ?></code>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($display_name); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($row['email'] ?? ''); ?></small><br>
                                    <small class="text-muted">ID: <?php echo (int)$row['user_id']; ?></small>
                                </td>
                                <td style="max-width:200px;">
                                    <strong style="font-size:0.78rem;"><?php echo htmlspecialchars($row['service_name'] ?? 'N/A'); ?></strong><br>
                                    <small class="text-muted">Owlet: <?php echo (int)$row['jap_service_id']; ?></small>
                                </td>
                                <td class="link-cell">
                                    <a href="<?php echo htmlspecialchars($row['link']); ?>" target="_blank" title="<?php echo htmlspecialchars($row['link']); ?>">
                                        <i class="fas fa-external-link-alt mr-1"></i><?php echo htmlspecialchars($row['link']); ?>
                                    </a>
                                </td>
                                <td><strong><?php echo number_format($row['quantity']); ?></strong></td>
                                <td><strong class="text-success">₦<?php echo number_format((float)$row['charge'], 2); ?></strong></td>
                                <td>
                                    <?php if ($row['jap_charge'] !== null): ?>
                                        <small class="text-muted">$<?php echo number_format((float)$row['jap_charge'], 6); ?></small>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php echo $row['remains'] !== null ? number_format($row['remains']) : '<span class="text-muted">—</span>'; ?>
                                </td>
                                <td>
                                    <span class="status-pill"
                                          style="background:<?php echo $sc['bg']; ?>;color:<?php echo $sc['color']; ?>;">
                                        <i class="fas <?php echo $sc['icon']; ?> mr-1"></i><?php echo htmlspecialchars($st); ?>
                                    </span>
                                </td>
                                <td>
                                    <small><?php echo date('M d, Y', strtotime($row['created_at'])); ?></small><br>
                                    <small class="text-muted"><?php echo date('h:i A', strtotime($row['created_at'])); ?></small>
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button type="button" class="btn btn-sm btn-primary dropdown-toggle"
                                                data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                            <i class="fas fa-cog"></i>
                                        </button>
                                        <div class="dropdown-menu dropdown-menu-right">
                                            <a class="dropdown-item" href="#"
                                               onclick="viewOrder(<?php echo (int)$row['id']; ?>)">
                                                <i class="fas fa-eye text-info"></i> View Details
                                            </a>
                                            <a class="dropdown-item" href="#"
                                               onclick="openUpdateStatusModal(<?php echo (int)$row['id']; ?>, '<?php echo $js_status; ?>', '<?php echo $js_notes; ?>')">
                                                <i class="fas fa-edit text-primary"></i> Update Status
                                            </a>
                                            <div class="dropdown-divider"></div>
                                            <a class="dropdown-item" href="#"
                                               onclick="deleteOrder(<?php echo (int)$row['id']; ?>)">
                                                <i class="fas fa-trash text-danger"></i> Delete Order
                                            </a>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php else: ?>
                    <div class="text-center py-5">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">No Orders Found</h5>
                        <p class="text-muted">No orders match your search criteria.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ══════════════ VIEW ORDER MODAL ══════════════ -->
<div class="modal fade" id="viewOrderModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-shopping-cart mr-2"></i>Order Details</h5>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body" id="viewOrderBody">
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ══════════════ UPDATE STATUS MODAL ══════════════ -->
<div class="modal fade" id="updateStatusModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-primary">
                    <i class="fas fa-edit mr-2"></i> Update Order Status
                </h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="update_order_id">
                <div class="form-group">
                    <label><strong>Status</strong></label>
                    <select class="form-control" id="update_status">
                        <option value="Pending">Pending</option>
                        <option value="In progress">In Progress</option>
                        <option value="Processing">Processing</option>
                        <option value="Completed">Completed</option>
                        <option value="Partial">Partial</option>
                        <option value="Cancelled">Cancelled</option>
                        <option value="Refunded">Refunded</option>
                    </select>
                </div>
                <div class="form-group">
                    <label><strong>Notes</strong> <small class="text-muted">(optional)</small></label>
                    <textarea class="form-control" id="update_notes" rows="3" placeholder="Add a note..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="submitUpdateStatus">
                    <i class="fas fa-save mr-1"></i> Save
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>
$(document).ready(function () {
    $('#dataTable').DataTable({
        ordering: true,
        pageLength: 25,
        order: [[0, 'desc']]
    });
});

// ── View Order Details ────────────────────────────────────────────────
function viewOrder(id) {
    $('#viewOrderBody').html('<div class="text-center py-4"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>');
    $('#viewOrderModal').modal('show');
    $.ajax({
        url: 'ajax/smm_orders.php', type: 'POST',
        data: { action: 'get_detail', id: id },
        dataType: 'json',
        success: function (res) {
            if (res.status == '1') {
                var o = res.order;
                var sc = {
                    'Completed':   { bg:'#d1fae5', color:'#065f46' },
                    'Pending':     { bg:'#fef3c7', color:'#92400e' },
                    'In progress': { bg:'#dbeafe', color:'#1e40af' },
                    'Processing':  { bg:'#ede9fe', color:'#5b21b6' },
                    'Partial':     { bg:'#fff7ed', color:'#c2410c' },
                    'Cancelled':   { bg:'#fee2e2', color:'#991b1b' },
                    'Refunded':    { bg:'#f3f4f6', color:'#374151' },
                }[o.status] || { bg:'#f3f4f6', color:'#374151' };

                var html = '<div class="row">' +
                    '<div class="col-md-6"><p><strong>Order ID:</strong> <code>#' + o.id + '</code></p>' +
                    '<p><strong>Owlet Order ID:</strong> ' + (o.jap_order_id || '—') + '</p>' +
                    '<p><strong>Owlet Service ID:</strong> ' + o.jap_service_id + '</p>' +
                    '<p><strong>Service:</strong> ' + (o.service_name || 'N/A') + '</p>' +
                    '<p><strong>User:</strong> ' + (o.full_name || o.username || '—') + ' (ID: ' + o.user_id + ')</p>' +
                    '</div><div class="col-md-6">' +
                    '<p><strong>Quantity:</strong> ' + Number(o.quantity).toLocaleString() + '</p>' +
                    '<p><strong>Charge:</strong> <span class="text-success font-weight-bold">₦' + parseFloat(o.charge).toLocaleString('en-NG', {minimumFractionDigits:2}) + '</span></p>' +
                    '<p><strong>Owlet Cost:</strong> ' + (o.jap_charge ? '$' + parseFloat(o.jap_charge).toFixed(6) : '—') + '</p>' +
                    '<p><strong>Start Count:</strong> ' + (o.start_count !== null ? Number(o.start_count).toLocaleString() : '—') + '</p>' +
                    '<p><strong>Remains:</strong> ' + (o.remains !== null ? Number(o.remains).toLocaleString() : '—') + '</p>' +
                    '</div></div>' +
                    '<hr>' +
                    '<p><strong>Link:</strong> <a href="' + o.link + '" target="_blank">' + o.link + '</a></p>' +
                    '<p><strong>Status:</strong> <span class="status-pill" style="background:' + sc.bg + ';color:' + sc.color + ';">' + o.status + '</span></p>' +
                    (o.notes ? '<p><strong>Notes:</strong> ' + o.notes + '</p>' : '') +
                    '<p><strong>Created:</strong> ' + o.created_at + '</p>' +
                    '<p><strong>Updated:</strong> ' + o.updated_at + '</p>';
                $('#viewOrderBody').html(html);
            } else {
                $('#viewOrderBody').html('<div class="alert alert-danger">' + (res.msg || 'Failed to load order.') + '</div>');
            }
        },
        error: function () {
            $('#viewOrderBody').html('<div class="alert alert-danger">An error occurred. Please try again.</div>');
        }
    });
}

// ── Update Status ─────────────────────────────────────────────────────
function openUpdateStatusModal(id, status, notes) {
    $('#update_order_id').val(id);
    $('#update_status').val(status);
    $('#update_notes').val(notes);
    $('#updateStatusModal').modal('show');
}

$('#submitUpdateStatus').on('click', function () {
    var id     = $('#update_order_id').val();
    var status = $('#update_status').val();
    var notes  = $('#update_notes').val();
    $('#submitUpdateStatus').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Saving...');
    $.ajax({
        url: 'ajax/smm_orders.php', type: 'POST',
        data: { action: 'update_status', id: id, status: status, notes: notes },
        dataType: 'json',
        success: function (res) {
            $('#submitUpdateStatus').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save');
            if (res.status == '1') {
                $('#updateStatusModal').modal('hide');
                Swal.fire({ title: 'Updated!', text: res.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                    .then(() => { location.reload(); });
            } else { Swal.fire('Error!', res.msg, 'error'); }
        },
        error: function () {
            $('#submitUpdateStatus').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save');
            Swal.fire('Error!', 'An error occurred.', 'error');
        }
    });
});

// ── Delete Order ──────────────────────────────────────────────────────
function deleteOrder(id) {
    Swal.fire({
        title: 'Delete Order?',
        html: 'Are you sure you want to delete order <strong>#' + id + '</strong>?<br><small class="text-danger">This cannot be undone.</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Delete',
        focusCancel: true
    }).then(function (result) {
        if (result.isConfirmed) {
            Swal.fire({ title: 'Processing...', html: 'Please wait...', allowOutsideClick: false, allowEscapeKey: false, didOpen: () => Swal.showLoading() });
            $.ajax({
                url: 'ajax/smm_orders.php', type: 'POST',
                data: { action: 'delete', id: id }, dataType: 'json',
                success: function (res) {
                    Swal.close();
                    if (res.status == '1') {
                        Swal.fire({ title: 'Deleted!', text: res.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                            .then(() => { location.reload(); });
                    } else { Swal.fire('Error!', res.msg, 'error'); }
                },
                error: function () { Swal.close(); Swal.fire('Error!', 'An error occurred.', 'error'); }
            });
        }
    });
}

// ── Export Excel ──────────────────────────────────────────────────────
function exportToExcel() {
    var wb = XLSX.utils.table_to_book(document.getElementById('dataTable'), { sheet: 'SMM Orders' });
    XLSX.writeFile(wb, 'smm_orders_' + new Date().toISOString().slice(0,10) + '.xlsx');
    Swal.fire({ title: 'Exported!', text: 'Exported successfully.', icon: 'success', timer: 2000, showConfirmButton: false });
}
</script>

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