<?php
require_once __DIR__ . '/_user_auth.php';
header('Content-Type: application/json');

$old = $_POST['old_password'] ?? '';
$new = $_POST['new_password'] ?? '';
$conf= $_POST['confirm_password'] ?? '';

if ($new !== $conf) { echo json_encode(['ok'=>false,'error'=>'Passwords do not match']); exit; }
if (strlen($new) < 8) { echo json_encode(['ok'=>false,'error'=>'Password too short']); exit; }

$student_id = (int)$_SESSION['student_id'];
$q = mysqli_query($conn, "SELECT portal_password_hash FROM students WHERE id=$student_id LIMIT 1");
$r = mysqli_fetch_assoc($q);
if (!$r || !password_verify($old, $r['portal_password_hash'])) {
  echo json_encode(['ok'=>false,'error'=>'Old password incorrect']); exit;
}

$hash = password_hash($new, PASSWORD_DEFAULT);
$u = mysqli_prepare($conn,"UPDATE students SET portal_password_hash=? WHERE id=?");
mysqli_stmt_bind_param($u,'si',$hash,$student_id);
mysqli_stmt_execute($u);
mysqli_stmt_close($u);

echo json_encode(['ok'=>true]);
