<?php
// /edenrms/ajax/save_checklist.php
ini_set('display_errors','1'); error_reporting(E_ALL);
header('Content-Type: application/json; charset=utf-8');

// ---- DB connection (use app connection if available) ----
$mysqli = null;
@include_once __DIR__ . '/../includes/db.php';
if (isset($conn) && $conn instanceof mysqli) {
  $mysqli = $conn;
} else {
  $mysqli = @new mysqli("localhost","root","","edencamp_edencampus");
}
if (!$mysqli || $mysqli->connect_error) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>'DB connect failed']); exit;
}
$mysqli->set_charset('utf8mb4');

// PHP 7.x compatibility
if (!function_exists('array_is_list')) {
  function array_is_list(array $arr): bool {
    $i = 0; foreach ($arr as $k => $_) { if ($k !== $i++) return false; } return true;
  }
}

// ---- Input ----
$student_id = (int)($_POST['student_id'] ?? 0);
$items_raw  = (string)($_POST['items'] ?? '');

if ($student_id <= 0) { echo json_encode(['ok'=>false,'error'=>'Invalid student_id']); exit; }
if ($items_raw === '') { echo json_encode(['ok'=>false,'error'=>'No items']); exit; }

$decoded = json_decode($items_raw, true);
if (!is_array($decoded)) { echo json_encode(['ok'=>false,'error'=>'Bad JSON']); exit; }

// Normalise to key=>0/1  (accept array of objects or map)
$flat = [];
if (array_is_list($decoded)) {
  foreach ($decoded as $row) {
    if (!is_array($row) || !isset($row['key'])) continue;
    $k = (string)$row['key'];
    $flat[$k] = (int)($row['done'] ?? $row['is_done'] ?? 0) ? 1 : 0;
  }
} else {
  foreach ($decoded as $k=>$v) { $flat[(string)$k] = ((int)$v) ? 1 : 0; }
}
if (!$flat) { echo json_encode(['ok'=>false,'error'=>'Empty checklist']); exit; }

// ---- Upsert items ----
// This expects a UNIQUE KEY on (student_id,item_key). If you don’t have it yet, see note below.
$u = $mysqli->prepare(
  "INSERT INTO student_checklist (student_id,item_key,is_done)
   VALUES (?,?,?)
   ON DUPLICATE KEY UPDATE is_done=VALUES(is_done)"
);
if (!$u) { echo json_encode(['ok'=>false,'error'=>'Prepare failed']); exit; }

foreach ($flat as $k=>$v) {
  $u->bind_param("isi", $student_id, $k, $v);
  if (!$u->execute()) { echo json_encode(['ok'=>false,'error'=>'Execute failed']); exit; }
}
$u->close();

// ---- Recount ----
$total = 6; // keep in sync with UI
$st = $mysqli->prepare("SELECT COUNT(*) AS c FROM student_checklist WHERE student_id=? AND is_done=1");
$st->bind_param("i",$student_id); $st->execute();
$res = $st->get_result(); $row = $res ? $res->fetch_assoc() : null;
$completed = (int)($row['c'] ?? 0);
$st->close();

echo json_encode(['ok'=>true,'completed'=>$completed,'total'=>$total]);
