<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
session_start();

/* Include DB */
include_once('script/condb.php');

if (isset($con)) {
    $conn = $con;
} else {
    echo json_encode(['ok'=>false,'msg'=>'$con not found (DB not connected)']);
    exit;
}

function out($x){ echo json_encode($x); exit; }
function clean($x){ return trim($x); }

/* Resolve PID / project_ref */
$PID =
    $_POST['project_ref'] ??
    $_GET['project_ref'] ??
    $_POST['pid'] ??
    $_GET['pid'] ??
    $_SESSION['pid'] ??
    '';

if (!$PID) out(['ok'=>false,'msg'=>'No project_ref or pid supplied']);
$_SESSION['pid'] = $PID;

/* Make sure tables exist */
$conn->query("
CREATE TABLE IF NOT EXISTS project_stage_labels (
  id INT AUTO_INCREMENT PRIMARY KEY,
  project_ref VARCHAR(128),
  stage_key VARCHAR(128),
  label_text VARCHAR(255),
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY(project_ref, stage_key)
) ENGINE=InnoDB;
");

$conn->query("
CREATE TABLE IF NOT EXISTS project_selected_stages (
  id INT AUTO_INCREMENT PRIMARY KEY,
  project_ref VARCHAR(128),
  stage_key VARCHAR(128),
  sort_order INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY(project_ref, stage_key)
) ENGINE=InnoDB;
");

/* Detect action */
$action = $_POST['action'] ?? $_GET['action'] ?? '';

/* SAVE SINGLE LABEL */
if ($action === 'save_label') {
    $key   = clean($_POST['key'] ?? '');
    $label = clean($_POST['label'] ?? '');

    if (!$key) out(['ok'=>false,'msg'=>'Missing key']);

    $stmt = $conn->prepare("
      INSERT INTO project_stage_labels (project_ref, stage_key, label_text)
      VALUES (?, ?, ?)
      ON DUPLICATE KEY UPDATE label_text = VALUES(label_text)
    ");
    $stmt->bind_param("sss", $PID, $key, $label);
    $stmt->execute();
    $stmt->close();

    out(['ok'=>true]);
}

/* SAVE ALL LABELS */
if ($action === 'save_all_labels') {

    $labels = $_POST['labels'] ?? '{}';
    if (is_string($labels)) $labels = json_decode($labels, true);
    if (!is_array($labels)) $labels = [];

    $stmt = $conn->prepare("
      INSERT INTO project_stage_labels (project_ref, stage_key, label_text)
      VALUES (?, ?, ?)
      ON DUPLICATE KEY UPDATE label_text = VALUES(label_text)
    ");

    foreach ($labels as $key => $val) {
        $k = clean($key);
        $v = clean($val);
        $stmt->bind_param("sss", $PID, $k, $v);
        $stmt->execute();
    }

    $stmt->close();
    out(['ok'=>true]);
}

/* TOGGLE SELECTION */
if ($action === 'toggle_selection') {

    $key     = clean($_POST['key'] ?? '');
    $checked = ($_POST['checked'] ?? '') === "1";

    if (!$key) out(['ok'=>false, 'msg'=>'Missing key']);

    if ($checked) {
        // Put at bottom of list
        $conn->query("UPDATE project_selected_stages SET sort_order = sort_order + 1 WHERE project_ref = '$PID'");

        $stmt = $conn->prepare("
            INSERT IGNORE INTO project_selected_stages (project_ref, stage_key, sort_order)
            VALUES (?, ?, 9999)
        ");
        $stmt->bind_param("ss", $PID, $key);
        $stmt->execute();
        $stmt->close();

    } else {
        $stmt = $conn->prepare("
            DELETE FROM project_selected_stages 
            WHERE project_ref = ? AND stage_key = ?
        ");
        $stmt->bind_param("ss", $PID, $key);
        $stmt->execute();
        $stmt->close();
    }

    out(['ok'=>true]);
}

/* CLEAR ALL SELECTIONS */
if ($action === 'clear_selections') {
    $stmt = $conn->prepare("
        DELETE FROM project_selected_stages 
        WHERE project_ref = ?
    ");
    $stmt->bind_param("s", $PID);
    $stmt->execute();
    $stmt->close();
    out(['ok'=>true]);
}

/* NEW: SAVE SORT ORDER (drag-drop) */
if ($action === 'save_sort_order') {

    $orderJson = $_POST['order'] ?? '[]';
    $list = json_decode($orderJson, true);

    if (!is_array($list)) out(['ok'=>false,'msg'=>'Invalid order payload']);

    $sort = 1;

    $stmt = $conn->prepare("
        UPDATE project_selected_stages
        SET sort_order = ?
        WHERE project_ref = ? AND stage_key = ?
    ");

    foreach ($list as $stageKey) {
        $stmt->bind_param("iss", $sort, $PID, $stageKey);
        $stmt->execute();
        $sort++;
    }

    $stmt->close();
    out(['ok'=>true]);
}


/* FETCH STATE */
if ($action === 'fetch_state') {

    $labels = [];
    $selections = [];

    // labels
    $q1 = $conn->prepare("
      SELECT stage_key, label_text 
      FROM project_stage_labels 
      WHERE project_ref = ?
    ");
    $q1->bind_param("s", $PID);
    $q1->execute();
    $result = $q1->get_result();
    while ($row = $result->fetch_assoc()) {
        $labels[$row['stage_key']] = $row['label_text'];
    }
    $q1->close();

    // selections ordered by sort_order
    $q2 = $conn->prepare("
      SELECT stage_key 
      FROM project_selected_stages 
      WHERE project_ref = ?
      ORDER BY sort_order ASC, id ASC
    ");
    $q2->bind_param("s", $PID);
    $q2->execute();
    $result2 = $q2->get_result();
    while ($row = $result2->fetch_assoc()) {
        $selections[] = $row['stage_key'];
    }
    $q2->close();

    out([
        'ok' => true,
        'labels' => $labels,
        'selections' => $selections
    ]);
}

/* DEFAULT */
out(['ok'=>false,'msg'=>'Unknown action']);
