<?php
// admin/regen_password.php — AJAX: regenerate a student's same-day password and return JSON
session_start();
header('Content-Type: application/json');

require_once "../includes/db.php";
if (!isset($_SESSION['admin'])) { echo json_encode(['ok'=>false,'error'=>'UNAUTH']); exit; }

$sid = isset($_GET['sid']) ? (int)$_GET['sid'] : 0;
if ($sid <= 0) { echo json_encode(['ok'=>false,'error'=>'BAD_ID']); exit; }

try {
  $plain = bin2hex(random_bytes(6)); // 12 hex chars
} catch (Throwable $e) {
  $plain = substr(md5(uniqid('', true)), 0, 12);
}
$hash  = password_hash($plain, PASSWORD_DEFAULT);
$today = date('Y-m-d');

/* columns may or may not exist */
function colExists(mysqli $db, $table, $col){
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param("ss",$table,$col); $st->execute();
  $r=$st->get_result(); return ($r && $r->num_rows>0);
}
$hasPlain = colExists($conn,'students','password_plain');
$hasValid = colExists($conn,'students','password_valid_date');

if ($hasPlain && $hasValid) {
  $st = $conn->prepare("UPDATE students SET password=?, password_plain=?, password_valid_date=? WHERE id=?");
  $st->bind_param("sssi", $hash, $plain, $today, $sid);
} elseif ($hasPlain) {
  $st = $conn->prepare("UPDATE students SET password=?, password_plain=? WHERE id=?");
  $st->bind_param("ssi", $hash, $plain, $sid);
} elseif ($hasValid) {
  $st = $conn->prepare("UPDATE students SET password=?, password_valid_date=? WHERE id=?");
  $st->bind_param("ssi", $hash, $today, $sid);
} else {
  $st = $conn->prepare("UPDATE students SET password=? WHERE id=?");
  $st->bind_param("si", $hash, $sid);
}

if ($st && $st->execute()) {
  echo json_encode(['ok'=>true,'password'=>$plain,'valid'=>$today]);
} else {
  echo json_encode(['ok'=>false,'error'=>$conn->error ?: 'UPDATE_FAILED']);
}
