<?php
/* GET  /api/materials.php?element_type=order&element_id=X — Liste
 * POST /api/materials.php?element_type=order&element_id=X — Body { label, qty, unit, note } → anlegen
 * DELETE /api/materials.php?id=X — löschen
 */
require_once __DIR__.'/_inc.php';

api_authenticate();
global $db, $user;

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'DELETE' || ($method === 'POST' && ($_GET['delete'] ?? '') === '1')) {
    if (!$user->hasRight('bericht', 'delete')) api_fail('Permission denied', 403);
    $id = (int) ($_GET['id'] ?? 0);
    if (!$id) api_fail('id fehlt');
    if (!$db->query("DELETE FROM ".$db->prefix()."bericht_material WHERE rowid = ".$id)) api_fail($db->lasterror(), 500);
    api_ok();
}

$el_type = (string) ($_GET['element_type'] ?? 'order');
$el_id   = (int) ($_GET['element_id'] ?? 0);
if (!$el_id) api_fail('element_id erforderlich');
if (!in_array($el_type, array('order', 'invoice', 'propal'), true)) api_fail('element_type ungültig');

if ($method === 'GET') {
    $sql = "SELECT rowid, label, qty, unit, note, fk_user_creat, datec"
        ." FROM ".$db->prefix()."bericht_material"
        ." WHERE element_type = '".$db->escape($el_type)."' AND fk_element = ".$el_id
        ." ORDER BY datec DESC, rowid DESC";
    $res = $db->query($sql);
    if (!$res) api_fail($db->lasterror(), 500);
    $items = array();
    while ($o = $db->fetch_object($res)) {
        $items[] = array(
            'id' => (int) $o->rowid,
            'label' => $o->label,
            'qty' => (float) $o->qty,
            'unit' => $o->unit,
            'note' => $o->note,
            'datec' => $db->jdate($o->datec),
        );
    }
    api_ok(array('materials' => $items, 'count' => count($items)));
}

if ($method === 'POST') {
    if (!$user->hasRight('bericht', 'write')) api_fail('Permission denied', 403);
    $in = api_input();
    $label = trim((string) ($in['label'] ?? ''));
    $qty   = (float) ($in['qty'] ?? 1);
    $unit  = trim((string) ($in['unit'] ?? 'Stk'));
    $note  = trim((string) ($in['note'] ?? ''));
    if (empty($label)) api_fail('label erforderlich');

    $sql = "INSERT INTO ".$db->prefix()."bericht_material "
        ."(element_type, fk_element, label, qty, unit, note, fk_user_creat, datec) VALUES ("
        ."'".$db->escape($el_type)."',"
        .$el_id.","
        ."'".$db->escape($label)."',"
        .((float) $qty).","
        ."'".$db->escape($unit)."',"
        .($note ? "'".$db->escape($note)."'" : "NULL").","
        .((int) $user->id).","
        ."'".$db->idate(dol_now())."'"
        .")";
    if (!$db->query($sql)) api_fail($db->lasterror(), 500);
    $id = $db->last_insert_id($db->prefix()."bericht_material");
    api_ok(array('id' => (int) $id));
}

api_fail('Methode nicht unterstützt', 405);
