<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
require_once '../helpers.php';
header('Content-Type: application/json');
if (!isset($_SESSION['parent_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
portalCsrfVerify();
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false, 'message'=>'Database connection failed']); exit; }
$parentId = (int) $_SESSION['parent_id'];
$currentPassword = (string) ($_POST['current_password'] ?? '');
$newPassword = (string) ($_POST['new_password'] ?? '');
$confirmPassword = (string) ($_POST['confirm_password'] ?? '');
if ($newPassword === '' || $newPassword !== $confirmPassword) {
    echo json_encode(['success'=>false, 'message'=>'New passwords do not match']); exit;
}
$stmt = $conn->prepare("SELECT password_hash FROM parent_accounts WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $parentId);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$row || !password_verify($currentPassword, (string) $row['password_hash'])) {
    echo json_encode(['success'=>false, 'message'=>'Current password is incorrect']); exit;
}
$hash = password_hash($newPassword, PASSWORD_BCRYPT);
$update = $conn->prepare("UPDATE parent_accounts SET password_hash = ? WHERE id = ?");
$update->bind_param('si', $hash, $parentId);
$update->execute();
$update->close();
echo json_encode(['success'=>true, 'message'=>'Password changed successfully']);
