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

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

// ── Pagination ───────────────────────────────────────────────────────
$per_page    = 20;
$current_page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset      = ($current_page - 1) * $per_page;

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

if ($filter_status !== 'all') {
    $where .= " AND s.status = :status";
    $params['status'] = (int)$filter_status;
}
if ($filter_cat !== 'all') {
    $where .= " AND s.category = :category";
    $params['category'] = $filter_cat;
}
if (!empty($search)) {
    $where .= " AND (s.name LIKE :s1 OR s.category LIKE :s2 OR s.type LIKE :s3 OR s.jap_service_id LIKE :s4)";
    $params['s1'] = "%$search%";
    $params['s2'] = "%$search%";
    $params['s3'] = "%$search%";
    $params['s4'] = "%$search%";
}

// ── Total count (for pagination) ─────────────────────────────────────
try {
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM smm_services s $where");
    $count_stmt->execute($params);
    $total_count = (int)$count_stmt->fetchColumn();
} catch (PDOException $e) {
    $total_count = 0;
    error_log("SMM services count error: " . $e->getMessage());
}

$total_pages = $total_count > 0 ? (int)ceil($total_count / $per_page) : 1;
// Clamp current page
if ($current_page > $total_pages) $current_page = $total_pages;
$offset = ($current_page - 1) * $per_page;

// ── Fetch services (paginated) ───────────────────────────────────────
try {
    $paged_params = array_merge($params, ['limit' => $per_page, 'offset' => $offset]);
    $stmt = $pdo->prepare("SELECT s.* FROM smm_services s $where ORDER BY s.id DESC LIMIT :limit OFFSET :offset");
    // Bind named params first, then limit/offset as INT
    foreach ($params as $key => $val) {
        $stmt->bindValue(':' . $key, $val);
    }
    $stmt->bindValue(':limit',  $per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset,   PDO::PARAM_INT);
    $stmt->execute();
    $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $services = [];
    error_log("SMM services fetch error: " . $e->getMessage());
}

// ── Fetch unique categories for filter ───────────────────────────────
try {
    $cat_stmt = $pdo->query("SELECT DISTINCT category FROM smm_services ORDER BY category ASC");
    $categories = $cat_stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    $categories = [];
}

// ── Stats ────────────────────────────────────────────────────────────
try {
    $stats_stmt = $pdo->query("
        SELECT
            COUNT(*)                                             AS total_services,
            SUM(status = 1)                                      AS active_services,
            SUM(status = 0)                                      AS hidden_services,
            COUNT(DISTINCT category)                             AS total_categories,
            SUM(refill = 1)                                      AS refill_services,
            AVG(our_rate)                                        AS avg_rate
        FROM smm_services
    ");
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $stats = ['total_services'=>0,'active_services'=>0,'hidden_services'=>0,'total_categories'=>0,'refill_services'=>0,'avg_rate'=>0];
}

// ── Build base query string for pagination links ─────────────────────
$query_parts = [];
if ($search         !== '')    $query_parts['search']   = $search;
if ($filter_status  !== 'all') $query_parts['status']   = $filter_status;
if ($filter_cat     !== 'all') $query_parts['category'] = $filter_cat;
$base_query = http_build_query($query_parts);
$page_link  = 'smm-services.php?' . ($base_query ? $base_query . '&' : '') . 'page=';
?>
<title>SMM Services - <?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); }
    .badge-active   { background:#d1fae5; color:#065f46; }
    .badge-hidden   { background:#fee2e2; color:#991b1b; }
    .badge-refill   { background:#dbeafe; color:#1e40af; }
    .badge-cancel   { background:#fef3c7; color:#92400e; }
    .cat-pill {
        display:inline-block; max-width:220px; overflow:hidden;
        white-space:nowrap; text-overflow:ellipsis;
        background:#f0f4ff; color:#3b5bdb;
        padding:2px 8px; border-radius:12px; font-size:0.75rem;
        vertical-align:middle;
    }
    code { color:#e83e8c; background:#f8f9fc; padding:2px 5px; border-radius:3px; font-size:0.82em; }
    .table td { vertical-align: middle; }
    .status-pill {
        padding:3px 10px; border-radius:20px;
        font-size:0.75rem; font-weight:600; display:inline-block;
    }
    /* Pagination tweaks */
    .pagination .page-link { font-size: 0.85rem; }
    .pagination-info { font-size: 0.85rem; color: #6c757d; }
</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 Services</h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">SMM Services</li>
        </ol>
    </div>

    <!-- ── Stat Cards ── -->
    <div class="row mb-4">
        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#4e73df;">
                <div class="card-body py-3">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Total Services</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['total_services']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-layer-group fa-2x text-primary"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#1cc88a;">
                <div class="card-body py-3">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Active</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['active_services']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-check-circle fa-2x text-success"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#e74a3b;">
                <div class="card-body py-3">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Hidden</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['hidden_services']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-eye-slash fa-2x text-danger"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#36b9cc;">
                <div class="card-body py-3">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Categories</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['total_categories']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-tags fa-2x text-info"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#f6c23e;">
                <div class="card-body py-3">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Refill Support</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['refill_services']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-redo fa-2x text-warning"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color:#858796;">
                <div class="card-body py-3">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Avg Rate (₦)</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">₦<?php echo number_format((float)$stats['avg_rate'], 2); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-chart-line fa-2x text-secondary"></i></div>
                    </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 service name, category, type, Owlet ID..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-3 mb-2">
                        <select name="category" class="form-control">
                            <option value="all">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo htmlspecialchars($cat); ?>"
                                    <?php echo $filter_cat === $cat ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </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="1"   <?php echo $filter_status==='1'   ? 'selected':'' ?>>Active</option>
                            <option value="0"   <?php echo $filter_status==='0'   ? 'selected':'' ?>>Hidden</option>
                        </select>
                    </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-2 mb-2">
                        <button type="button" class="btn btn-success btn-block" onclick="openAddModal()">
                            <i class="fas fa-plus mr-1"></i> Add Service
                        </button>
                    </div>
                </div>
                <?php if ($search || $filter_status !== 'all' || $filter_cat !== 'all'): ?>
                <div class="row mt-1">
                    <div class="col-12">
                        <a href="smm-services.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">
                            Found <strong><?php echo number_format($total_count); ?></strong> result(s)
                        </span>
                    </div>
                </div>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <!-- ── 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 Services
                        <span class="badge badge-primary ml-2"><?php echo number_format($total_count); ?></span>
                    </h6>
                    <button class="btn btn-sm btn-outline-success" onclick="exportToExcel()">
                        <i class="fas fa-file-excel mr-1"></i> Export Page
                    </button>
                </div>
                <div class="table-responsive p-3">
                    <?php if (!empty($services)): ?>
                    <table class="table table-flush table-hover align-items-center" id="dataTable">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Owlet ID</th>
                                <th>Service Name</th>
                                <th>Category</th>
                                <th>Type</th>
                                <th>Owlet Rate (₦)</th>
                                <th>Our Rate (₦)</th>
                                <th>Min / Max</th>
                                <th>Refill</th>
                                <th>Cancel</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // Row numbering continues across pages
                            $row_start = $offset + 1;
                            $i = $row_start;
                            foreach ($services as $row):
                                $statusBadge = $row['status'] == 1
                                    ? '<span class="status-pill badge-active">Active</span>'
                                    : '<span class="status-pill badge-hidden">Hidden</span>';
                                $refillBadge = $row['refill'] == 1
                                    ? '<span class="status-pill badge-refill"><i class="fas fa-redo fa-xs mr-1"></i>Yes</span>'
                                    : '<span class="text-muted small">—</span>';
                                $cancelBadge = $row['cancel'] == 1
                                    ? '<span class="status-pill badge-cancel"><i class="fas fa-ban fa-xs mr-1"></i>Yes</span>'
                                    : '<span class="text-muted small">—</span>';
                                $js_name = addslashes(htmlspecialchars($row['name'], ENT_QUOTES));
                                $js_cat  = addslashes(htmlspecialchars($row['category'], ENT_QUOTES));
                                $js_type = addslashes(htmlspecialchars($row['type'] ?? 'Default', ENT_QUOTES));
                            ?>
                            <tr>
                                <td><?php echo $i++; ?></td>
                                <td><code><?php echo (int)$row['jap_service_id']; ?></code></td>
                                <td style="max-width:280px;">
                                    <strong style="font-size:0.82rem;"><?php echo htmlspecialchars($row['name']); ?></strong>
                                </td>
                                <td><span class="cat-pill" title="<?php echo htmlspecialchars($row['category']); ?>"><?php echo htmlspecialchars($row['category']); ?></span></td>
                                <td><small><?php echo htmlspecialchars($row['type'] ?? 'Default'); ?></small></td>
                                <td><span class="text-muted small">₦<?php echo number_format((float)$row['jap_rate'], 6); ?></span></td>
                                <td><strong class="text-success">₦<?php echo number_format((float)$row['our_rate'], 2); ?></strong></td>
                                <td>
                                    <small>
                                        <span class="text-primary"><?php echo number_format($row['min_quantity']); ?></span>
                                        <span class="text-muted"> / </span>
                                        <span class="text-secondary"><?php echo number_format($row['max_quantity']); ?></span>
                                    </small>
                                </td>
                                <td><?php echo $refillBadge; ?></td>
                                <td><?php echo $cancelBadge; ?></td>
                                <td><?php echo $statusBadge; ?></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> Actions
                                        </button>
                                        <div class="dropdown-menu dropdown-menu-right">
                                            <a class="dropdown-item" href="#" onclick="openEditModal(
                                                <?php echo (int)$row['id']; ?>,
                                                <?php echo (int)$row['jap_service_id']; ?>,
                                                '<?php echo $js_name; ?>',
                                                '<?php echo $js_cat; ?>',
                                                '<?php echo $js_type; ?>',
                                                <?php echo (float)$row['jap_rate']; ?>,
                                                <?php echo (float)$row['our_rate']; ?>,
                                                <?php echo (int)$row['min_quantity']; ?>,
                                                <?php echo (int)$row['max_quantity']; ?>,
                                                <?php echo (int)$row['refill']; ?>,
                                                <?php echo (int)$row['cancel']; ?>,
                                                <?php echo (int)$row['status']; ?>
                                            )">
                                                <i class="fas fa-edit text-primary"></i> Edit Service
                                            </a>
                                            <div class="dropdown-divider"></div>
                                            <a class="dropdown-item" href="#" onclick="deleteService(<?php echo (int)$row['id']; ?>, '<?php echo $js_name; ?>')">
                                                <i class="fas fa-trash text-danger"></i> Delete Service
                                            </a>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <!-- ── Pagination Bar ── -->
                    <?php
                    $range     = 2; // pages to show either side of current
                    $start_row = $offset + 1;
                    $end_row   = min($offset + $per_page, $total_count);
                    ?>
                    <div class="d-flex align-items-center justify-content-between mt-3 flex-wrap">
                        <div class="pagination-info mb-2">
                            Showing <strong><?php echo number_format($start_row); ?></strong>
                            – <strong><?php echo number_format($end_row); ?></strong>
                            of <strong><?php echo number_format($total_count); ?></strong> services
                            &nbsp;|&nbsp; Page <strong><?php echo $current_page; ?></strong>
                            of <strong><?php echo $total_pages; ?></strong>
                        </div>
                        <nav aria-label="Services pagination">
                            <ul class="pagination pagination-sm mb-2">
                                <!-- First -->
                                <li class="page-item <?php echo $current_page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="<?php echo $page_link . 1; ?>" title="First">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <!-- Prev -->
                                <li class="page-item <?php echo $current_page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="<?php echo $page_link . max(1, $current_page - 1); ?>" title="Previous">
                                        <i class="fas fa-angle-left"></i>
                                    </a>
                                </li>

                                <?php
                                $p_start = max(1, $current_page - $range);
                                $p_end   = min($total_pages, $current_page + $range);

                                // Always show first page
                                if ($p_start > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="<?php echo $page_link . 1; ?>">1</a>
                                    </li>
                                    <?php if ($p_start > 2): ?>
                                        <li class="page-item disabled"><span class="page-link">…</span></li>
                                    <?php endif; ?>
                                <?php endif; ?>

                                <?php for ($p = $p_start; $p <= $p_end; $p++): ?>
                                    <li class="page-item <?php echo $p === $current_page ? 'active' : ''; ?>">
                                        <a class="page-link" href="<?php echo $page_link . $p; ?>"><?php echo $p; ?></a>
                                    </li>
                                <?php endfor; ?>

                                <?php if ($p_end < $total_pages): ?>
                                    <?php if ($p_end < $total_pages - 1): ?>
                                        <li class="page-item disabled"><span class="page-link">…</span></li>
                                    <?php endif; ?>
                                    <li class="page-item">
                                        <a class="page-link" href="<?php echo $page_link . $total_pages; ?>"><?php echo $total_pages; ?></a>
                                    </li>
                                <?php endif; ?>

                                <!-- Next -->
                                <li class="page-item <?php echo $current_page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="<?php echo $page_link . min($total_pages, $current_page + 1); ?>" title="Next">
                                        <i class="fas fa-angle-right"></i>
                                    </a>
                                </li>
                                <!-- Last -->
                                <li class="page-item <?php echo $current_page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="<?php echo $page_link . $total_pages; ?>" title="Last">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                    <!-- ── / Pagination Bar ── -->

                    <?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 Services Found</h5>
                        <p class="text-muted">No services match your search criteria.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ══════════════ ADD SERVICE MODAL ══════════════ -->
<div class="modal fade" id="addModal" 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">
                <h5 class="modal-title font-weight-bold text-primary">
                    <i class="fas fa-plus-circle mr-2"></i> Add New SMM Service
                </h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>JAP Service ID</strong></label>
                            <input type="number" class="form-control" id="add_jap_service_id" placeholder="e.g. 7566">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Type</strong></label>
                            <input type="text" class="form-control" id="add_type" value="Default" placeholder="e.g. Default">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Service Name</strong></label>
                    <input type="text" class="form-control" id="add_name" placeholder="e.g. Instagram Followers">
                </div>
                <div class="form-group">
                    <label><strong>Category</strong></label>
                    <input type="text" class="form-control" id="add_category" placeholder="e.g. Instagram Followers">
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>JAP Rate (USD per 1000)</strong></label>
                            <div class="input-group">
                                <div class="input-group-prepend"><span class="input-group-text">$</span></div>
                                <input type="number" step="0.000001" min="0" class="form-control" id="add_jap_rate" placeholder="0.000000">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Our Rate (₦ per 1000)</strong></label>
                            <div class="input-group">
                                <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                                <input type="number" step="0.01" min="0" class="form-control" id="add_our_rate" placeholder="0.00">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Min Quantity</strong></label>
                            <input type="number" min="1" class="form-control" id="add_min_quantity" value="10">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Max Quantity</strong></label>
                            <input type="number" min="1" class="form-control" id="add_max_quantity" value="1000000">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label><strong>Refill</strong></label>
                            <select class="form-control" id="add_refill">
                                <option value="0">No</option>
                                <option value="1">Yes</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label><strong>Cancel</strong></label>
                            <select class="form-control" id="add_cancel">
                                <option value="0">No</option>
                                <option value="1">Yes</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label><strong>Status</strong></label>
                            <select class="form-control" id="add_status">
                                <option value="1">Active</option>
                                <option value="0">Hidden</option>
                            </select>
                        </div>
                    </div>
                </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="submitAdd">
                    <i class="fas fa-plus mr-1"></i> Add Service
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ══════════════ EDIT SERVICE MODAL ══════════════ -->
<div class="modal fade" id="editModal" 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">
                <h5 class="modal-title font-weight-bold text-primary">
                    <i class="fas fa-edit mr-2"></i> Edit SMM Service
                </h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="edit_id">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Owlet Service ID</strong></label>
                            <input type="number" class="form-control" id="edit_jap_service_id">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Type</strong></label>
                            <input type="text" class="form-control" id="edit_type">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Service Name</strong></label>
                    <input type="text" class="form-control" id="edit_name">
                </div>
                <div class="form-group">
                    <label><strong>Category</strong></label>
                    <input type="text" class="form-control" id="edit_category">
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Owlet Rate (USD per 1000)</strong></label>
                            <div class="input-group">
                                <div class="input-group-prepend"><span class="input-group-text">$</span></div>
                                <input type="number" step="0.000001" min="0" class="form-control" id="edit_jap_rate">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Our Rate (₦ per 1000)</strong></label>
                            <div class="input-group">
                                <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                                <input type="number" step="0.01" min="0" class="form-control" id="edit_our_rate">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Min Quantity</strong></label>
                            <input type="number" min="1" class="form-control" id="edit_min_quantity">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Max Quantity</strong></label>
                            <input type="number" min="1" class="form-control" id="edit_max_quantity">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label><strong>Refill</strong></label>
                            <select class="form-control" id="edit_refill">
                                <option value="0">No</option>
                                <option value="1">Yes</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label><strong>Cancel</strong></label>
                            <select class="form-control" id="edit_cancel">
                                <option value="0">No</option>
                                <option value="1">Yes</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label><strong>Status</strong></label>
                            <select class="form-control" id="edit_status">
                                <option value="1">Active</option>
                                <option value="0">Hidden</option>
                            </select>
                        </div>
                    </div>
                </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="submitEdit">
                    <i class="fas fa-save mr-1"></i> Save Changes
                </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 is now used only for column sorting — paging is server-side
    $('#dataTable').DataTable({
        ordering:   true,
        paging:     false,   // server handles paging
        info:       false,   // hide "Showing X of Y entries" (we render our own)
        searching:  false,   // server handles search
        order:      [[0, 'asc']]
    });
});

// ── Open Add Modal ────────────────────────────────────────────────────
function openAddModal() {
    $('#add_jap_service_id,#add_name,#add_category,#add_jap_rate,#add_our_rate').val('');
    $('#add_type').val('Default');
    $('#add_min_quantity').val(10);
    $('#add_max_quantity').val(1000000);
    $('#add_refill,#add_cancel').val('0');
    $('#add_status').val('1');
    $('#addModal').modal('show');
}

// ── Submit Add ────────────────────────────────────────────────────────
$('#submitAdd').on('click', function () {
    var data = collectForm('add');
    if (!data) return;
    $('#submitAdd').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Adding...');
    $.ajax({
        url: 'ajax/smm_services.php', type: 'POST',
        data: Object.assign({ action: 'add' }, data),
        dataType: 'json',
        success: function (res) {
            $('#submitAdd').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Service');
            if (res.status == '1') {
                $('#addModal').modal('hide');
                Swal.fire({ title: 'Success!', text: res.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                    .then(() => { location.reload(); });
            } else { Swal.fire('Error!', res.msg, 'error'); }
        },
        error: function () {
            $('#submitAdd').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Service');
            Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
        }
    });
});

// ── Open Edit Modal ───────────────────────────────────────────────────
function openEditModal(id, jap_id, name, cat, type, jap_rate, our_rate, min_q, max_q, refill, cancel, status) {
    $('#edit_id').val(id);
    $('#edit_jap_service_id').val(jap_id);
    $('#edit_name').val(name);
    $('#edit_category').val(cat);
    $('#edit_type').val(type);
    $('#edit_jap_rate').val(jap_rate);
    $('#edit_our_rate').val(our_rate);
    $('#edit_min_quantity').val(min_q);
    $('#edit_max_quantity').val(max_q);
    $('#edit_refill').val(refill);
    $('#edit_cancel').val(cancel);
    $('#edit_status').val(status);
    $('#editModal').modal('show');
}

// ── Submit Edit ───────────────────────────────────────────────────────
$('#submitEdit').on('click', function () {
    var data = collectForm('edit');
    if (!data) return;
    data.id = $('#edit_id').val();
    $('#submitEdit').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Saving...');
    $.ajax({
        url: 'ajax/smm_services.php', type: 'POST',
        data: Object.assign({ action: 'edit' }, data),
        dataType: 'json',
        success: function (res) {
            $('#submitEdit').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Changes');
            if (res.status == '1') {
                $('#editModal').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 () {
            $('#submitEdit').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Changes');
            Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
        }
    });
});

// ── Delete ────────────────────────────────────────────────────────────
function deleteService(id, name) {
    Swal.fire({
        title: 'Delete Service?',
        html: 'Are you sure you want to delete <strong>' + name + '</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_services.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'); }
            });
        }
    });
}

// ── Shared form collector ─────────────────────────────────────────────
function collectForm(prefix) {
    var p = prefix + '_';
    var jap_id   = $.trim($('#' + p + 'jap_service_id').val());
    var name     = $.trim($('#' + p + 'name').val());
    var category = $.trim($('#' + p + 'category').val());
    var type     = $.trim($('#' + p + 'type').val()) || 'Default';
    var jap_rate = $.trim($('#' + p + 'jap_rate').val());
    var our_rate = $.trim($('#' + p + 'our_rate').val());
    var min_q    = $.trim($('#' + p + 'min_quantity').val());
    var max_q    = $.trim($('#' + p + 'max_quantity').val());

    if (!jap_id || !name || !category || !our_rate) {
        Swal.fire('Validation Error', 'Owlet ID, Name, Category and Our Rate are required.', 'warning');
        return null;
    }
    return {
        jap_service_id: jap_id, name: name, category: category, type: type,
        jap_rate: jap_rate, our_rate: our_rate,
        min_quantity: min_q, max_quantity: max_q,
        refill: $('#' + p + 'refill').val(),
        cancel: $('#' + p + 'cancel').val(),
        status: $('#' + p + 'status').val()
    };
}

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

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