<?php
// Assuming you have the database connection established already
require("../../mainconfig.php");

// Function to calculate the total number of pages based on the number of records per page
function getTotalPages($totalRecords, $recordsPerPage) {
    return ceil($totalRecords / $recordsPerPage);
}

// Function to search for orders based on the search query
function searchOrders($searchQuery, $offset, $recordsPerPage, &$totalRecords) {
    global $db;

    // Add SQL injection protection
    $searchQuery = mysqli_real_escape_string($db, $searchQuery);

    $query = "SELECT * FROM orders WHERE poid LIKE '%$searchQuery%' ORDER BY id DESC LIMIT $recordsPerPage OFFSET $offset";
    $result = mysqli_query($db, $query);

    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
            "date" => $row['date'],
            "poid" => $row['poid'],
            "user" => $row['user'],
            "service" => $row['service'],
            "link" => $row['link'],
            "quantity" => $row['quantity'],
            "remains" => $row['remains'],
            "start_count" => $row['start_count'],
            "price" => $row['price'],
            "status" => $row['status'],
            "tw" => $row['tw'],
            "provider" => $row['provider'],
            "refund" => $row['refund'],
            "edit_link" => $cfg_baseurl . "admin/order/edit.php?poid=" . $row['poid'],
            "delete_link" => $cfg_baseurl . "admin/order/delete.php?poid=" . $row['poid']
        );
    }

    // Get the total number of records that match the search query
    $totalRecordsQuery = "SELECT COUNT(*) AS total FROM orders WHERE poid LIKE '%$searchQuery%'";
    $totalRecordsResult = mysqli_query($db, $totalRecordsQuery);
    $totalRecordsRow = mysqli_fetch_assoc($totalRecordsResult);
    $totalRecords = $totalRecordsRow['total'];

    return $data;
}

$recordsPerPage = isset($_GET['recordsPerPage']) ? intval($_GET['recordsPerPage']) : 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$searchQuery = isset($_GET['search']) ? $_GET['search'] : '';

// Calculate the OFFSET for the current page
$offset = ($page - 1) * $recordsPerPage;

if (!empty($searchQuery)) {
    // Perform search and get data for the current page
    $data = searchOrders($searchQuery, $offset, $recordsPerPage, $totalRecords);
} else {
    // Fetch data from the 'orders' table for the current page
    $query = "SELECT * FROM orders ORDER BY id DESC LIMIT $recordsPerPage OFFSET $offset";
    $result = mysqli_query($db, $query);

    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
            "date" => $row['date'],
            "poid" => $row['poid'],
            "user" => $row['user'],
            "service" => $row['service'],
            "link" => $row['link'],
            "quantity" => $row['quantity'],
            "remains" => $row['remains'],
            "start_count" => $row['start_count'],
            "price" => $row['price'],
            "status" => $row['status'],
            "tw" => $row['tw'],
            "provider" => $row['provider'],
            "refund" => $row['refund'],
            "edit_link" => $cfg_baseurl . "admin/order/edit.php?poid=" . $row['poid'],
            "delete_link" => $cfg_baseurl . "admin/order/delete.php?poid=" . $row['poid']
        );
    }

    // Get the total number of records in the 'orders' table
    $totalRecordsQuery = "SELECT COUNT(*) AS total FROM orders";
    $totalRecordsResult = mysqli_query($db, $totalRecordsQuery);
    $totalRecordsRow = mysqli_fetch_assoc($totalRecordsResult);
    $totalRecords = $totalRecordsRow['total'];
}

// Calculate total pages
$totalPages = getTotalPages($totalRecords, $recordsPerPage);

// Return data as JSON
echo json_encode(array(
    "orders" => $data,
    "totalPages" => $totalPages
));
?>
