<?php
require_once('includes/load.php');
global $db;

// Ambil parameter halaman dan panjang data dari URL
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['length']) ? (int)$_GET['length'] : 10;
$start = ($page - 1) * $limit;

$product_id = isset($_GET['product_id']) ? (int)$_GET['product_id'] : null;

// Validasi input
if (!$product_id) {
    echo json_encode(['success' => false, 'message' => 'Product ID is required.']);
    exit();
}

// Total data untuk pagination
$total_query = $db->prepare("SELECT COUNT(*) as total FROM sales s JOIN products p ON s.product_id = p.id WHERE p.id = ?");
$total_query->bind_param("i", $product_id);
$total_query->execute();
$total_result = $total_query->get_result();
$total_row = $total_result->fetch_assoc();
$total_records = $total_row['total'];

// Ambil data berdasarkan limit dan halaman
$query = $db->prepare("SELECT CAST(s.qty AS UNSIGNED) AS qty, s.date, s.remark, s.loc 
                         FROM sales s 
                         JOIN products p ON s.product_id = p.id 
                         WHERE p.id = ? 
                         ORDER BY s.id DESC 
                         LIMIT ?, ?");
$query->bind_param("iii", $product_id, $start, $limit);
$query->execute();
$result = $query->get_result();

$sales = [];
while ($row = $result->fetch_assoc()) {
    $sales[] = $row;
}

// Kembalikan data dalam format JSON
echo json_encode([
    'success' => true,
    'data' => $sales,
    'recordsTotal' => $total_records,
    'recordsFiltered' => $total_records
]);
exit();
