<?php
// produk.php

header("Content-Type: application/json; charset=UTF-8");

require 'security.php';
require 'logger.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on produk.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Mendapatkan token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in produk.php");
    exit;
}

try {
    // 1) Cari user_id berdasarkan token
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in produk.php");
        exit;
    }

    // 2) Mengambil parameter pagination dari body request
    $inputData = json_decode(file_get_contents('php://input'), true);
    log_activity("Input data: " . print_r($inputData, true)); // Log input data

    $page = isset($inputData['page']) ? (int)$inputData['page'] : 1;
    $limit = isset($inputData['limit']) ? (int)$inputData['limit'] : 10;
    $search = isset($inputData['search']) ? $inputData['search'] : null;

    $offset = ($page - 1) * $limit;
    
    // 3) Query dasar untuk mengambil produk
    $sql = "
        SELECT 
            p.id, 
            p.judul, 
            p.harga, 
            p.kuantitas, 
            p.diskon, 
            p.path_gambar, 
            p.catatan,
            p.kategori_id,
            p.id_penjual,  -- Menambahkan id_penjual
            k.nama_kategori,
            u.name AS nama_penjual
        FROM produk p
        LEFT JOIN kategori k ON p.kategori_id = k.id
        JOIN users u ON p.id_penjual = u.id
    ";

    if ($search !== "" && $search !== null) {
        $sql .= " WHERE p.judul LIKE :search";
    }

    $sql .= " ORDER BY p.id DESC LIMIT :limit OFFSET :offset";

    // 4) Eksekusi query
    $stmt = $pdo->prepare($sql);

    if ($search !== "" && $search !== null) {
        $searchParam = '%' . $search . '%';
        $stmt->bindValue(':search', $searchParam, PDO::PARAM_STR);
    }

    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    
    // Eksekusi query
    $stmt->execute();
    
    $produk = $stmt->fetchAll();

    // 5) Hitung total produk untuk pagination
    $countSql = "SELECT COUNT(*) as total FROM produk";
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute();
    $totalProduk = $countStmt->fetchColumn();

    // 6) Response data produk dengan informasi pagination
    http_response_code(200);
    echo json_encode([
        'data' => $produk,
        'pagination' => [
            'page' => $page,
            'limit' => $limit,
            'total' => $totalProduk,
            'total_pages' => ceil($totalProduk / $limit)
        ]
    ]);
    log_activity("All produk retrieved.");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error', 'message' => $e->getMessage()]); // Tampilkan pesan error
    log_activity("produk.php error: " . $e->getMessage());
    exit;
}
?>
