<?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'];
$fullName = trim((string) ($_POST['full_name'] ?? ''));
$phone = preg_replace('/\D+/', '', (string) ($_POST['phone'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$stmt = $conn->prepare("SELECT id FROM parent_accounts WHERE phone = ? AND id != ? LIMIT 1");
$stmt->bind_param('si', $phone, $parentId);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
    $stmt->close();
    echo json_encode(['success'=>false, 'message'=>'Phone number is already in use']); exit;
}
$stmt->close();
if ($email !== '') {
    $emailStmt = $conn->prepare("SELECT id FROM parent_accounts WHERE email = ? AND id != ? LIMIT 1");
    $emailStmt->bind_param('si', $email, $parentId);
    $emailStmt->execute();
    if ($emailStmt->get_result()->num_rows > 0) {
        $emailStmt->close();
        echo json_encode(['success'=>false, 'message'=>'Email is already in use']); exit;
    }
    $emailStmt->close();
}
$update = $conn->prepare("UPDATE parent_accounts SET full_name = ?, phone = ?, email = ? WHERE id = ?");
$update->bind_param('sssi', $fullName, $phone, $email, $parentId);
$update->execute();
$update->close();
$_SESSION['parent_name'] = $fullName;
$_SESSION['parent_phone'] = $phone;
echo json_encode(['success'=>true, 'message'=>'Profile updated successfully']);
