<?php

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

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

// --- Fungsi Helper ---

function get_user_id_from_token($pdo, $token) {
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();
    if (!$tokenData) {
        return null;
    }
    return $tokenData['user_id'];
}

// --- Create Produk ---

function create_produk($pdo, $userId, $produk_data) {
    // Jika input hanya satu produk, ubah menjadi array agar bisa diproses sama
    if (!isset($produk_data[0])) {
        $produk_data = [$produk_data];
    }

    foreach ($produk_data as $item) {
        $judul = $item['judul'];
        $harga = $item['harga'];
        $kuantitas = $item['kuantitas'];
        $diskon = isset($item['diskon']) ? $item['diskon'] : 0.00;
        $path_gambar = isset($item['path_gambar']) ? $item['path_gambar'] : null;
        $catatan = isset($item['catatan']) ? $item['catatan'] : null;
        $kategori_id = isset($item['kategori_id']) ? $item['kategori_id'] : null;

        // Simpan data produk ke database
        try {
            $stmt = $pdo->prepare("
                INSERT INTO produk (id_penjual, judul, harga, kuantitas, diskon, path_gambar, catatan, kategori_id) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$userId, $judul, $harga, $kuantitas, $diskon, $path_gambar, $catatan, $kategori_id]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Server error: ' . $e->getMessage()]);
            exit;
        }
    }

    http_response_code(201);
    echo json_encode(['message' => 'Produk created successfully']);
}

// ---  CRUD Operations ---

if ($_SERVER['REQUEST_METHOD'] === 'POST') { 
    // 1.  Otentikasi
    $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']);
        exit;
    }

    $userId = get_user_id_from_token($pdo, $token);
    if (!$userId) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        exit;
    }

    // 2. Ambil data produk dari request body
    $input_raw = file_get_contents('php://input');
    $input = json_decode($input_raw, true);
    $input = sanitize_input($input);

    // Panggil fungsi create_produk
    create_produk($pdo, $userId, $input);

} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // --- Read Produk ---

    // 1. Otentikasi
    $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']);
        exit;
    }

    $userId = get_user_id_from_token($pdo, $token);
    if (!$userId) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        exit;
    }


    // 2. Ambil data produk dari database (bisa dengan filter, pagination, dll.)
    try {
        $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 -- Mengambil nama kategori
            FROM produk p
            LEFT JOIN kategori k ON p.kategori_id = k.id
            WHERE p.id_penjual = ? 
        ");
        $stmt->execute([$userId]);
        $produk = $stmt->fetchAll();

        http_response_code(200);
        echo json_encode($produk);

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

} elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    // --- Update Produk ---

    // 1. Otentikasi
    $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']);
        exit;
    }

    $userId = get_user_id_from_token($pdo, $token);
    if (!$userId) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        exit;
    }

    // 2. Ambil ID produk dan data yang akan diupdate
    $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'];
    $judul = isset($input['judul']) ? $input['judul'] : null;
    $harga = isset($input['harga']) ? $input['harga'] : null;
    $kuantitas = isset($input['kuantitas']) ? $input['kuantitas'] : null;
    $diskon = isset($input['diskon']) ? $input['diskon'] : null;
    $path_gambar = isset($input['path_gambar']) ? $input['path_gambar'] : null;
    $catatan = isset($input['catatan']) ? $input['catatan'] : null;
    $kategori_id = isset($input['kategori_id']) ? $input['kategori_id'] : null;

    // 3. Update data produk di database
    try {
        $stmt = $pdo->prepare("
            UPDATE produk 
            SET 
                judul = COALESCE(?, judul), 
                harga = COALESCE(?, harga), 
                kuantitas = COALESCE(?, kuantitas), 
                diskon = COALESCE(?, diskon), 
                path_gambar = COALESCE(?, path_gambar), 
                catatan = COALESCE(?, catatan),
                kategori_id = COALESCE(?, kategori_id)
            WHERE id = ? AND id_penjual = ?
        ");
        $stmt->execute([$judul, $harga, $kuantitas, $diskon, $path_gambar, $catatan, $kategori_id, $id_produk, $userId]);

        http_response_code(200);
        echo json_encode(['message' => 'Produk updated successfully']);

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

} elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    // --- Delete Produk ---

    // 1. Otentikasi
    $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']);
        exit;
    }

    $userId = get_user_id_from_token($pdo, $token);
    if (!$userId) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        exit;
    }

    // 2. Ambil ID produk yang akan dihapus
    $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'];

    // 3. Hapus data produk dari database
    try {
        $stmt = $pdo->prepare("DELETE FROM produk WHERE id = ? AND id_penjual = ?");
        $stmt->execute([$id_produk, $userId]);

        http_response_code(200);
        echo json_encode(['message' => 'Produk deleted successfully']);

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

} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

?>