<?php
header('Content-Type: application/json');


ini_set("display_errors", 1);

if (!isset($baseDir)) {
	$baseDir = $_SERVER['DOCUMENT_ROOT'];
}

require_once $baseDir . '/../scripts/session_functions.php';

ini_wkvs_session();

check_user_permission('wk_leitung');

verify_csrf();

require $baseDir . '/../scripts/db/db-functions.php';
require $baseDir . '/../scripts/db/db-tables.php';


$type = 'wkl';
$dbconnection = require $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($dbconnection['success'] !== true){
    echo json_encode(['success' => false, 'message' => 'Critical DB Error.']);
    exit;
}
                

$action = $_POST['action'] ?? '';

if ($action === 'update') {
    $abt_id = intval($_POST['abt'] ?? 0);
    $field = $_POST['type'] ?? '';
    $type_id = intval($_POST['type_id'] ?? 0);

    $value = $_POST['value'] ?? '';

    if (!preg_match('/^\d{2}:\d{2}$/', $value)) {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters.']);
        http_response_code(400);
        exit;
    }

    $allowedFields = ['start', 'end'];
    if (
        $abt_id > 0 &&
        $type_id > 0 && 
        db_check_var($mysqli, $db_tabelle_gruppen, 'id = ?', [$abt_id]) &&
        db_check_var($mysqli, $db_tabelle_zeitplan_types, 'id = ?', [$type_id]) &&
        ($field === 'start' || ($field === 'end'  && db_check_var($mysqli, $db_tabelle_zeitplan_types, 'id = ? AND has_endtime = ?', [$type_id, 1])))
    ) {

        $stmt = $mysqli->prepare("INSERT INTO $db_tabelle_gruppen_zeiten (`abt_id`, `zeitplan_id`, `" . $field . "_time`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `" . $field . "_time` = VALUES(`" . $field . "_time`)");

        $stmt->bind_param("iis", $abt_id, $type_id, $value);

        $stmt->execute();

        $stmt->close();

        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters.']);
        http_response_code(400);
        exit;
    }

} elseif ($action === 'delete') {
    $abt_id = intval($_POST['abt'] ?? 0);
    $type_id = intval($_POST['type_id'] ?? 0);

    if ($type_id > 0 && $abt_id > 0) {
        db_delete($mysqli, $db_tabelle_gruppen_zeiten, ['abt_id' => $abt_id, 'zeitplan_id' => $type_id]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid ID.']);
        http_response_code(400);
        exit;
    }

} else {
    echo json_encode(['success' => false, 'message' => 'Action not found.']);
}
