<?php
$tenant = $_REQUEST['tenant'] ?? '';
if (file_exists('../../../' . $tenant . '/config.php')) { require_once('../../../' . $tenant . '/config.php'); }
if (file_exists('/config.php')) { require_once('/config.php'); }

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['status' => 'error', 'message' => 'DB connection unavailable']);
    exit();
}

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

function jumpPlantAffectedItems(string $code): array
{
    $stmt = $GLOBALS['con']->prepare("
        SELECT i.`itemnumber`,
               i.`clientnumber`,
               i.`desc`,
               i.`plantnumber`,
               i.`serialnumber`,
               COALESCE(c.`clientname`, '') AS `clientname`
        FROM `itemdetails` i
        LEFT JOIN `clientdetails` c
          ON c.`clientnumber` = i.`clientnumber`
        WHERE i.`statuslive` = 1
          AND i.`code` = ?
        ORDER BY c.`clientname` ASC, i.`itemnumber` ASC
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('s', $code);
    $stmt->execute();
    $rs = $stmt->get_result();
    $stmt->close();

    $items = [];
    while ($rs && ($row = $rs->fetch_assoc())) {
        $items[] = [
            'itemnumber' => (int)($row['itemnumber'] ?? 0),
            'clientnumber' => (int)($row['clientnumber'] ?? 0),
            'clientname' => (string)($row['clientname'] ?? ''),
            'description' => (string)($row['desc'] ?? ''),
            'plantnumber' => (string)($row['plantnumber'] ?? ''),
            'serialnumber' => (string)($row['serialnumber'] ?? ''),
        ];
    }

    return $items;
}

function jumpPlantOptions(string $excludeCode = ''): array
{
    $stmt = $GLOBALS['con']->prepare("
        SELECT `code`, `description`, `frequency`
        FROM `dd_plant`
        WHERE `code` <> ?
        ORDER BY `code` ASC
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('s', $excludeCode);
    $stmt->execute();
    $rs = $stmt->get_result();
    $stmt->close();

    $options = [];
    while ($rs && ($row = $rs->fetch_assoc())) {
        $code = trim((string)($row['code'] ?? ''));
        if ($code === '') {
            continue;
        }

        $options[] = [
            'code' => $code,
            'description' => (string)($row['description'] ?? ''),
            'frequency' => (string)($row['frequency'] ?? ''),
        ];
    }

    return $options;
}

if ($action === 'plantUsage') {
    header('Content-Type: application/json; charset=utf-8');

    $id = (int)($_REQUEST['id'] ?? 0);
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid id']);
        exit();
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `code` FROM `dd_plant` WHERE `id` = ? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $rs = $stmt->get_result();
    $row = $rs ? $rs->fetch_assoc() : null;
    $stmt->close();

    if (!$row || empty($row['code'])) {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Not found']);
        exit();
    }

    $code = (string)$row['code'];

    $items = jumpPlantAffectedItems($code);

    echo json_encode([
        'status' => 'success',
        'id' => $id,
        'code' => $code,
        'count' => count($items),
        'items' => $items,
        'plant_options' => jumpPlantOptions($code),
    ]);
    exit();
}

if ($action === 'plantUsageByCode') {
    header('Content-Type: application/json; charset=utf-8');

    $code = trim((string)($_REQUEST['code'] ?? ''));
    if ($code === '') {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid code']);
        exit();
    }

    $items = jumpPlantAffectedItems($code);

    echo json_encode([
        'status' => 'success',
        'code' => $code,
        'count' => count($items),
        'items' => $items,
        'plant_options' => jumpPlantOptions($code),
    ]);
    exit();
}

if ($action === 'reassignItemsAndRemovePlant') {
    header('Content-Type: application/json; charset=utf-8');

    $id = (int)($_REQUEST['id'] ?? 0);
    $assignmentsRaw = (string)($_REQUEST['assignments'] ?? '');
    $assignments = json_decode($assignmentsRaw, true);

    if ($id <= 0 || !is_array($assignments)) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid reassignment request.']);
        exit();
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `code` FROM `dd_plant` WHERE `id` = ? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $rs = $stmt->get_result();
    $plant = $rs ? $rs->fetch_assoc() : null;
    $stmt->close();

    $oldCode = trim((string)($plant['code'] ?? ''));
    if ($oldCode === '') {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Plant entry not found.']);
        exit();
    }

    $affectedItems = jumpPlantAffectedItems($oldCode);
    if (empty($affectedItems)) {
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `dd_plant` WHERE `id` = ?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $id);
        $ok = $stmt->execute();
        $stmt->close();

        echo json_encode(['status' => $ok ? 'success' : 'error', 'message' => $ok ? 'Plant entry removed.' : 'Plant entry could not be removed.']);
        exit();
    }

    $cleanAssignments = [];
    foreach ($assignments as $assignment) {
        if (!is_array($assignment)) {
            continue;
        }
        $itemnumber = (int)($assignment['itemnumber'] ?? 0);
        $newCode = trim((string)($assignment['code'] ?? ''));
        if ($itemnumber > 0 && $newCode !== '') {
            $cleanAssignments[$itemnumber] = $newCode;
        }
    }

    $affectedItemNumbers = [];
    foreach ($affectedItems as $item) {
        $itemnumber = (int)($item['itemnumber'] ?? 0);
        if ($itemnumber > 0) {
            $affectedItemNumbers[$itemnumber] = $itemnumber;
        }
    }

    foreach ($affectedItemNumbers as $itemnumber) {
        if (empty($cleanAssignments[$itemnumber])) {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'Every affected item must have a replacement plant code.']);
            exit();
        }
        if ($cleanAssignments[$itemnumber] === $oldCode) {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'Replacement code cannot be the plant code being removed.']);
            exit();
        }
    }

    $replacementRows = [];
    $uniqueCodes = array_values(array_unique($cleanAssignments));
    foreach ($uniqueCodes as $newCode) {
        $stmt = $GLOBALS['con']->prepare("SELECT `code`, `description` FROM `dd_plant` WHERE `code` = ? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('s', $newCode);
        $stmt->execute();
        $rs = $stmt->get_result();
        $row = $rs ? $rs->fetch_assoc() : null;
        $stmt->close();

        if (!$row) {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'Replacement plant code not found: ' . $newCode]);
            exit();
        }
        $replacementRows[$newCode] = (string)($row['description'] ?? '');
    }

    $GLOBALS['con']->begin_transaction();
    try {
        $updateStmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `code` = ?, `desc` = ? WHERE `itemnumber` = ? AND `statuslive` = 1 AND `code` = ?") or die(mysqli_error($GLOBALS['con']));
        $updated = 0;
        foreach ($affectedItemNumbers as $itemnumber) {
            $newCode = $cleanAssignments[$itemnumber];
            $newDesc = $replacementRows[$newCode];
            $updateStmt->bind_param('ssis', $newCode, $newDesc, $itemnumber, $oldCode);
            $updateStmt->execute();
            $updated += $updateStmt->affected_rows;
        }
        $updateStmt->close();

        $checkItems = jumpPlantAffectedItems($oldCode);
        if (!empty($checkItems)) {
            throw new RuntimeException('Some affected items were not updated.');
        }

        $deleteStmt = $GLOBALS['con']->prepare("DELETE FROM `dd_plant` WHERE `id` = ?") or die(mysqli_error($GLOBALS['con']));
        $deleteStmt->bind_param('i', $id);
        $deleteStmt->execute();
        $deleted = $deleteStmt->affected_rows;
        $deleteStmt->close();

        if ($deleted < 1) {
            throw new RuntimeException('Plant entry could not be removed.');
        }

        $GLOBALS['con']->commit();
        echo json_encode(['status' => 'success', 'message' => 'Updated ' . $updated . ' item(s) and removed the plant entry.']);
    } catch (Throwable $e) {
        $GLOBALS['con']->rollback();
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit();
}

if ($action === 'updateItemPlantData' || $action === 'updateItemPlantCodes') {
    header('Content-Type: text/plain; charset=utf-8');

    $oldCode = trim((string)($_REQUEST['old_code'] ?? ''));
    $newCode = trim((string)($_REQUEST['new_code'] ?? ''));
    $newDesc = trim((string)($_REQUEST['new_desc'] ?? ''));

    if ($oldCode === '' || $newCode === '') {
        http_response_code(400);
        echo 'e';
        exit();
    }

    if ($newDesc === '') {
        $stmt = $GLOBALS['con']->prepare("SELECT `description` FROM `dd_plant` WHERE `code` = ? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('s', $newCode);
        $stmt->execute();
        $rs = $stmt->get_result();
        $row = $rs ? $rs->fetch_assoc() : null;
        $stmt->close();
        $newDesc = trim((string)($row['description'] ?? ''));
    }

    if ($newDesc === '') {
        http_response_code(400);
        echo 'e';
        exit();
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `code` = ?, `desc` = ? WHERE `statuslive` = 1 AND `code` = ?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('sss', $newCode, $newDesc, $oldCode);
    $ok = $stmt->execute();
    $stmt->close();

    echo $ok ? 's' : 'e';
    exit();
}

http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
exit();
