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

// Mendapatkan ID produk dari request body
$input_raw = file_get_contents('php://input');
$input = json_decode($input_raw, true);
$input = sanitize_input($input);

if (empty($input['id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Produk ID is required']);
    exit;
}

$id_produk = $input['id'];

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_detail.php");
        exit;
    }

    // 2) Ambil detail produk berdasarkan ID
    $stmt = $pdo->prepare("
        SELECT 
            p.id, 
            p.judul, 
            p.harga, 
            p.kuantitas, 
            p.diskon, 
            p.path_gambar, 
            p.catatan,
            p.kategori_id,
            p.id_penjual,  -- Tambahkan id_penjual ke dalam query
            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
        WHERE p.id = ?
    ");
    $stmt->execute([$id_produk]);
    $produk = $stmt->fetch();

    if (!$produk) {
        http_response_code(404);
        echo json_encode(['error' => 'Produk not found']);
        exit;
    }

    // 3) Response data produk
    http_response_code(200);
    echo json_encode($produk);
    log_activity("Produk detail retrieved for produk ID '$id_produk'.");

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

?>