<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false, 'message'=>'Database connection failed']); exit; }
$id = (int) ($_POST['id'] ?? 0);
if ((int) ($_POST['toggle_status'] ?? 0) === 1 && $id > 0) {
    $stmt = $conn->prepare("UPDATE parent_accounts SET is_active = IF(is_active = 1, 0, 1) WHERE id = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->close();
    echo json_encode(['success'=>true, 'message'=>'Parent account status updated']); exit;
}
$fullName = trim((string) ($_POST['full_name'] ?? ''));
$phone = preg_replace('/\D+/', '', (string) ($_POST['phone'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$password = (string) ($_POST['password'] ?? '');
$studentId = (int) ($_POST['student_id'] ?? 0);
if ($fullName === '' || $phone === '' || ($id === 0 && $password === '')) {
    echo json_encode(['success'=>false, 'message'=>'Name, phone and password are required']); exit;
}
if ($id > 0) {
    $stmt = $conn->prepare("UPDATE parent_accounts SET full_name = ?, phone = ?, email = ? WHERE id = ?");
    $stmt->bind_param('sssi', $fullName, $phone, $email, $id);
    $stmt->execute();
    $stmt->close();
    if ($studentId > 0) {
        $link = $conn->prepare("INSERT IGNORE INTO parent_student_link (parent_id, student_id) VALUES (?, ?)");
        $link->bind_param('ii', $id, $studentId);
        $link->execute();
        $link->close();
    }
    echo json_encode(['success'=>true, 'message'=>'Parent account updated']); exit;
}
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $conn->prepare("INSERT INTO parent_accounts (full_name, email, phone, password_hash) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $fullName, $email, $phone, $hash);
$stmt->execute();
$parentId = (int) $stmt->insert_id;
$stmt->close();
if ($studentId > 0) {
    $link = $conn->prepare("INSERT IGNORE INTO parent_student_link (parent_id, student_id) VALUES (?, ?)");
    $link->bind_param('ii', $parentId, $studentId);
    $link->execute();
    $link->close();
}
sendSMS($phone, "Welcome to EduTrack Parent Portal! Login at " . rtrim(BASE_URL, '/') . "/parent-portal/login.php Phone: {$phone} Password: {$password}");
echo json_encode(['success'=>true, 'message'=>'Parent account created successfully']);
