<?php
// best_seller.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 best_seller.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 best_seller.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 best_seller.php");
        exit;
    }

    // 2) Ambil produk best seller 
    $stmt = $pdo->prepare("
        SELECT 
            p.id, 
            p.judul, 
            p.harga, 
            p.kuantitas, 
            p.diskon, 
            p.path_gambar, 
            p.catatan,
            p.kategori_id,
            k.nama_kategori,
            u.name AS nama_penjual,
            p.pembelian
        FROM produk p
        LEFT JOIN kategori k ON p.kategori_id = k.id
        JOIN users u ON p.id_penjual = u.id
        WHERE p.pembelian > 0 ORDER BY p.pembelian DESC
        LIMIT 5; 
    ");
    $stmt->execute();
    $produk = $stmt->fetchAll();

    // 3) Response data produk
    http_response_code(200);
    echo json_encode($produk);
    log_activity("Best seller produk retrieved.");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("best_seller.php error: " . $e->getMessage());
    exit;
}

?>