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

// Load parent item
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['parent']);
$stmt->execute();
$cc = $stmt->get_result();
$stmt->close();
$d = mysqli_fetch_array($cc);

// Ensure arrays exist
$do = [];

// Process clones
$rowCount = (int)($_REQUEST['rowCount'] ?? 0);
foreach (range(1, $rowCount) as $i) {
    $plant = $_REQUEST['plantnumber' . $i] ?? '';
    $serial = $_REQUEST['serialnumber' . $i] ?? '';
    if ($plant === '' && $serial === '') {
        continue;
    }

    // Base values
    $d['plantnumber']  = $plant;
    $d['serialnumber'] = $serial;

    // Copy-or-override fields
    $do['manf']        = ($_REQUEST['manf' . $i]        ?? '') !== '' ? $_REQUEST['manf' . $i]        : ($d['manf']        ?? '');
    $do['dateofmanf']  = ($_REQUEST['dateofmanf' . $i]  ?? '') !== '' ? $_REQUEST['dateofmanf' . $i]  : ($d['dateofmanf']  ?? '');
    $do['model']       = ($_REQUEST['model' . $i]       ?? '') !== '' ? $_REQUEST['model' . $i]       : ($d['model']       ?? '');
    $do['swl']         = ($_REQUEST['swl' . $i]         ?? '') !== '' ? $_REQUEST['swl' . $i]         : ($d['swl']         ?? '');

    // NEW: subloc override (blank = keep parent's subloc)
    $sublocParam = ($_REQUEST['subloc' . $i] ?? '') !== '' ? $_REQUEST['subloc' . $i] : ($d['subloc'] ?? null);

    // NEW: duedate override from hidden UNIX field; '' => NULL
    $dueIn = $_REQUEST['duedate' . $i] ?? '';
    $duedateParam = ($dueIn === '' || $dueIn === null) ? null : (int)$dueIn;

    $lastReportParam = '';
    $linkedParam = $d['linked'] ?? '';
    $createdParam = strtotime('now');
    $archivedParam = $d['archived'] ?? null;
    $nfcParam = null;
    $pressureDataParam = $d['pressure_data'] ?? null;
    $levDataParam = $d['lev_data'] ?? null;

    $stmt = $GLOBALS['con']->prepare("
        INSERT INTO `itemdetails` (
            `locnumber`,
            `clientnumber`,
            `code`,
            `desc`,
            `swl`,
            `plantnumber`,
            `serialnumber`,
            `ancillarynumber`,
            `model`,
            `dateofmanf`,
            `manf`,
            `subloc`,
            `detailedloc`,
            `currdate`,
            `duedate`,
            `statuslive`,
            `itemnotes`,
            `history`,
            `lastReport`,
            `multi_flag`,
            `cont_freq`,
            `condition`,
            `surveyor`,
            `agent`,
            `broker`,
            `reptype`,
            `linked`,
            `contractor`,
            `created`,
            `archived`,
            `nfc`,
            `pressure_data`,
            `lev_data`
        ) VALUES (
            ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
        )
    ") or die(mysqli_error($GLOBALS['con']));

    $stmt->bind_param(
        str_repeat('s', 33),
        $d['locnumber'],
        $d['clientnumber'],
        $d['code'],
        $d['desc'],
        $do['swl'],
        $d['plantnumber'],
        $d['serialnumber'],
        $d['ancillarynumber'],
        $do['model'],
        $do['dateofmanf'],
        $do['manf'],
        $sublocParam,                // <- was $d['subloc']
        $d['detailedloc'],
        $d['currdate'],
        $duedateParam,
        $d['statuslive'],
        $d['itemnotes'],
        $d['history'],
        $lastReportParam,
        $d['multi_flag'],
        $d['cont_freq'],
        $d['condition'],
        $d['surveyor'],
        $d['agent'],
        $d['broker'],
        $d['reptype'],
        $linkedParam,
        $d['contractor'],
        $createdParam,
        $archivedParam,
        $nfcParam,
        $pressureDataParam,
        $levDataParam
    );

    if ($stmt->execute()) {
        $newItemnumber = (int)$GLOBALS['con']->insert_id;
        if ($newItemnumber > 0 && function_exists('plantChangeLogAdd')) {
            plantChangeLogAdd($newItemnumber, 'clone');
        }
    }
    $stmt->close();
}

echo "success";
