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

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

$GLOBALS['con']->set_charset('utf8mb4');

function puwerSetResponse(string $status, string $message, array $extra = []): void
{
    echo json_encode(array_merge([
        'status' => $status,
        'message' => $message
    ], $extra));
    exit;
}

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

switch ($FUNCTION) {
    case 'savePuwerSet':
        $setId = (int)($_REQUEST['set_id'] ?? 0);
        $clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
        $templateId = (int)($_REQUEST['template_id'] ?? 0);
        $setTitle = trim((string)($_REQUEST['set_title'] ?? ''));
        $status = !empty($_REQUEST['status']) ? 1 : 0;

        if ($clientnumber <= 0) {
            puwerSetResponse('error', 'Invalid client');
        }

        if ($templateId <= 0) {
            puwerSetResponse('error', 'Please select a template');
        }

        if ($setTitle === '') {
            puwerSetResponse('error', 'Set title is required');
        }

        $itemnumbers = json_decode((string)($_REQUEST['itemnumbers_json'] ?? '[]'), true);
        if (!is_array($itemnumbers)) {
            $itemnumbers = [];
        }

        $cleanItemnumbers = [];
        foreach ($itemnumbers as $itemnumber) {
            $itemnumber = (int)$itemnumber;
            if ($itemnumber > 0 && !in_array($itemnumber, $cleanItemnumbers, true)) {
                $cleanItemnumbers[] = $itemnumber;
            }
        }

        if (empty($cleanItemnumbers)) {
            puwerSetResponse('error', 'Select at least one item');
        }

        /*
         * Validate template exists
         */
        $stmt = $GLOBALS['con']->prepare("
            SELECT `id`
            FROM `puwer_templates`
            WHERE `id` = ?
            LIMIT 1
        ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $templateId);
        $stmt->execute();
        $templateRes = $stmt->get_result();
        $stmt->close();

        if (!$templateRes || $templateRes->num_rows < 1) {
            puwerSetResponse('error', 'Selected template was not found');
        }

        /*
         * Validate all selected items belong to this client
         */
        $itemIdList = implode(',', array_map('intval', $cleanItemnumbers));
        $sql = "
            SELECT `itemnumber`
            FROM `itemdetails`
            WHERE `clientnumber` = ?
              AND `itemnumber` IN ($itemIdList)
        ";
        $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $clientnumber);
        $stmt->execute();
        $validItemRes = $stmt->get_result();
        $stmt->close();

        $validItemnumbers = [];
        while ($row = mysqli_fetch_assoc($validItemRes)) {
            $validItemnumbers[] = (int)$row['itemnumber'];
        }

        sort($validItemnumbers);
        $tmpSelected = $cleanItemnumbers;
        sort($tmpSelected);

        if ($validItemnumbers !== $tmpSelected) {
            puwerSetResponse('error', 'One or more selected items are invalid for this client');
        }

        /*
         * Check selected items are not already in another active PUWER set
         */
        $stmt = $GLOBALS['con']->prepare("
            SELECT `id`, `set_title`, `itemnumbers_json`
            FROM `puwer_item_sets`
            WHERE `clientnumber` = ?
              AND `status` = 1
              AND `id` != ?
        ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $clientnumber, $setId);
        $stmt->execute();
        $existingRes = $stmt->get_result();
        $stmt->close();

        $conflicts = [];
        while ($row = mysqli_fetch_assoc($existingRes)) {
            $existingItems = json_decode((string)($row['itemnumbers_json'] ?? '[]'), true);
            if (!is_array($existingItems)) {
                continue;
            }

            $existingItems = array_map('intval', $existingItems);
            $overlap = array_intersect($cleanItemnumbers, $existingItems);

            if (!empty($overlap)) {
                $conflicts[] = [
                    'set_title' => (string)($row['set_title'] ?? ''),
                    'items' => array_values($overlap)
                ];
            }
        }

        if (!empty($conflicts)) {
            $parts = [];
            foreach ($conflicts as $conflict) {
                $parts[] = ($conflict['set_title'] !== '' ? $conflict['set_title'] : 'Existing set')
                    . ' [' . implode(', ', $conflict['items']) . ']';
            }

            puwerSetResponse(
                'error',
                'Some selected items are already assigned to another active PUWER set: ' . implode('; ', $parts)
            );
        }

        $itemnumbersJson = json_encode(array_values($cleanItemnumbers));
        $createdBy = (int)($_SESSION['admin_id'] ?? 0);
        $dateCreated = time();

        if ($setId > 0) {
            $stmt = $GLOBALS['con']->prepare("
                UPDATE `puwer_item_sets`
                SET `template_id` = ?,
                    `set_title` = ?,
                    `itemnumbers_json` = ?,
                    `status` = ?
                WHERE `id` = ?
                  AND `clientnumber` = ?
            ") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('issiii', $templateId, $setTitle, $itemnumbersJson, $status, $setId, $clientnumber);
            $stmt->execute();
            $stmt->close();

            puwerSetResponse('success', 'PUWER set updated');
        }

        $stmt = $GLOBALS['con']->prepare("
            INSERT INTO `puwer_item_sets`
                (`clientnumber`, `template_id`, `set_title`, `itemnumbers_json`, `status`, `date_created`, `created_by`)
            VALUES
                (?, ?, ?, ?, ?, ?, ?)
        ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('iissiii', $clientnumber, $templateId, $setTitle, $itemnumbersJson, $status, $dateCreated, $createdBy);
        $stmt->execute();
        $stmt->close();

        puwerSetResponse('success', 'PUWER set created');
        break;

    case 'deletePuwerSet':
        $setId = (int)($_REQUEST['set_id'] ?? 0);
        $clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);

        if ($setId <= 0 || $clientnumber <= 0) {
            puwerSetResponse('error', 'Invalid PUWER set');
        }

        $stmt = $GLOBALS['con']->prepare("
            DELETE FROM `puwer_item_sets`
            WHERE `id` = ?
              AND `clientnumber` = ?
        ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $setId, $clientnumber);
        $stmt->execute();
        $stmt->close();

        puwerSetResponse('success', 'PUWER set deleted');
        break;

    default:
        puwerSetResponse('error', 'Invalid function');
        break;
}