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

// config includes
if (isset($_POST['tenant']) && file_exists('../../../'.$_POST['tenant'].'/config.php')) {
    require_once('../../../'.$_POST['tenant'].'/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
$con = $GLOBALS['con'] ?? null;
if (!$con) { echo json_encode(['draw'=>0,'recordsTotal'=>0,'recordsFiltered'=>0,'data'=>[]]); exit; }
$con->set_charset('utf8mb4');

// DataTables params
$draw   = (int)($_POST['draw']   ?? 0);
$start  = (int)($_POST['start']  ?? 0);
$length = (int)($_POST['length'] ?? 25);
$search = trim($_POST['search']['value'] ?? '');
$type   = $_POST['type'] ?? 'phrases';
$group  = preg_replace('/[^A-Za-z0-9_\-]/', '', (string)($_POST['group'] ?? ''));

function formOptionsTableExists(mysqli $con, string $table): bool {
    $table = $con->real_escape_string($table);
    $res = $con->query("SHOW TABLES LIKE '$table'");
    return $res && $res->num_rows > 0;
}

function formOptionsColumnExists(mysqli $con, string $table, string $column): bool {
    $table = $con->real_escape_string($table);
    $column = $con->real_escape_string($column);
    $res = $con->query("SHOW COLUMNS FROM `$table` LIKE '$column'");
    return $res && $res->num_rows > 0;
}

// map type -> table + fields
$map = [
  'phrases'  => ['table'=>'dd_phrases',  'id'=>'id',       'code'=>'phrasecode', 'text'=>'phrase',      'extra'=>['discipline']],
  'results'  => ['table'=>'dd_results',  'id'=>'phrasecode','code'=>'phrasecode', 'text'=>'phrase',      'extra'=>['discipline']],
  'examtype' => ['table'=>'dd_examtype', 'id'=>'phrasecode','code'=>'phrasecode', 'text'=>'phrase',      'extra'=>['discipline']],
  'plant'    => ['table'=>'dd_plant',    'id'=>'code',      'code'=>'code',       'text'=>'description', 'extra'=>[]],
];

if (!isset($map[$type])) { echo json_encode(['draw'=>$draw,'recordsTotal'=>0,'recordsFiltered'=>0,'data'=>[]]); exit; }

$tbl   = $map[$type]['table'];
$idCol = $map[$type]['id'];
$code  = $map[$type]['code'];
$text  = $map[$type]['text'];
$extra = $map[$type]['extra'];

// filtering
$whereParts = [];
if ($search !== '') {
    $s = '%'.$con->real_escape_string($search).'%';
    if ($type === 'plant') {
        $whereParts[] = "(`$code` LIKE '$s' OR `$text` LIKE '$s')";
    } else {
        $disc = in_array('discipline', $extra, true) ? " OR `discipline` LIKE '$s'" : '';
        $whereParts[] = "(`$code` LIKE '$s' OR `$text` LIKE '$s'".$disc.")";
    }
}

$canFilterPhraseGroup = $type === 'phrases'
    && $group !== ''
    && formOptionsTableExists($con, 'dd_phrase_groups')
    && formOptionsColumnExists($con, 'dd_phrases', 'group_id');

$usePhraseGroupFilter = false;
if ($canFilterPhraseGroup) {
    $groupSql = $con->real_escape_string($group);
    $groupCount = $con->query("
        SELECT COUNT(p.`id`)
        FROM `dd_phrase_groups` g
        INNER JOIN `dd_phrases` p ON p.`group_id` = g.`id`
        WHERE g.`group_name` = '$groupSql'
          AND g.`status` = 1
    ");
    $usePhraseGroupFilter = $groupCount && (int)$groupCount->fetch_row()[0] > 0;
}

if ($usePhraseGroupFilter) {
    $whereParts[] = "`group_id` IN (
        SELECT `id`
        FROM `dd_phrase_groups`
        WHERE `group_name` = '$groupSql'
        AND `status` = 1
    )";
}

$where = !empty($whereParts) ? 'WHERE ' . implode(' AND ', $whereParts) : '';

// totals
$resTotal = $con->query("SELECT COUNT(*) FROM `$tbl`");
$recordsTotal = (int)($resTotal ? $resTotal->fetch_row()[0] : 0);

$resFiltered = $con->query("SELECT COUNT(*) FROM `$tbl` $where");
$recordsFiltered = (int)($resFiltered ? $resFiltered->fetch_row()[0] : 0);

// ordering
$orderColIdx = isset($_POST['order'][0]['column']) ? (int)$_POST['order'][0]['column'] : 0;
$orderDir    = (isset($_POST['order'][0]['dir']) && strtolower($_POST['order'][0]['dir'])==='desc') ? 'DESC' : 'ASC';
$columnsForOrder = [
  0 => $code, // first visible column
  1 => $text, // second visible column
  2 => $idCol // action column not sortable, fallback safe
];
$orderBy = $columnsForOrder[$orderColIdx] ?? $code;

// query data
$q = "SELECT * FROM `$tbl` $where ORDER BY `$orderBy` $orderDir LIMIT $start, $length";
$result = $con->query($q);

$data = [];
if ($result) {
  while ($row = $result->fetch_assoc()) {
    // Prepare safe display values
    $phrasecode = isset($row['phrasecode']) ? $row['phrasecode'] : (isset($row['code']) ? $row['code'] : '');
    $phrase     = isset($row['phrase']) ? nl2br( $row['phrase']) : null;
    $description= isset($row['description']) ? $row['description'] : null;

    // URL-encode payloads for JS "updateField"
    $phraseEncoded = $phrase !== null ? rawurlencode($row['phrase']) : null;
    $codeEncoded   = isset($row['code']) ? rawurlencode($row['code']) : null;

    $data[] = [
      'id'            => $row[$idCol] ?? '',
      'phrasecode'    => $phrasecode,
      'phrase'        => $phrase,
      'description'   => $description,
      'discipline'    => $row['discipline'] ?? '',
      'code'          => $row['code'] ?? '',
      'phraseEncoded' => $phraseEncoded,
      'codeEncoded'   => $codeEncoded
    ];
  }
}

echo json_encode([
  'draw' => $draw,
  'recordsTotal' => $recordsTotal,
  'recordsFiltered' => $recordsFiltered,
  'data' => $data
]);
