<?php
session_start();
require "api/Prozigzig.php";

$h = new Prozigzig();

if (!isset($_SESSION['stype']) || $_SESSION['stype'] != 'sowner') {
    // Unauthorized access
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $price_type = $_POST['price_type'] ?? '';

    // Validate input
    if (!in_array($price_type, ['FIXED', 'ROUTE'])) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid price type']);
        exit;
    }

    // Fetch operator data (you already have email stored in session)
    $query = "SELECT * FROM tbl_bus_operator WHERE email='" . $h->real_string($_SESSION['busname']) . "'";
    $sdata = $h->fetchData($query);

    if (!$sdata) {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Operator not found']);
        exit;
    }

    // Prepare update
    $table = "tbl_bus_operator";
    $field = ['price_type' => $price_type];
    $where = "WHERE id=" . intval($sdata["id"]);

    $update = $h->updateData($field, $table, $where);

    if ($update) {
        echo json_encode(['status' => 'success', 'message' => 'Price type updated', 'price_type' => $price_type]);
    } else {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Failed to update']);
    }
} else {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>
