<?php
session_start();
require_once 'db.php';
header("Content-Type: application/json; charset=UTF-8");

// Log errors to file
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_error.log');

require_once 'config.php'; // $conn must be available

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

// Collect and sanitize inputs
$uniqueId             = $_POST['uniqueId'] ?? '';
$fatherName           = $_POST['fatherName'] ?? '';
$motherName           = $_POST['motherName'] ?? '';
$guardianName         = $_POST['guardianName'] ?? '';
$relationWithStudent  = $_POST['relationWithStudent'] ?? '';
$fatherGuardianMobile = $_POST['fatherGuardianMobile'] ?? '';
$motherMobile         = $_POST['motherMobile'] ?? '';
$emailId              = $_POST['emailId'] ?? '';

// Validate required fields
if (!$uniqueId || !$fatherName || !$fatherGuardianMobile) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// Update parent details for given unique_reg_number
$sql = "UPDATE students 
        SET father_name = ?, mother_name = ?, guardian_name = ?, 
            relation_with_student = ?, father_guardian_mobile = ?, 
            mother_mobile = ?, email_id = ?
        WHERE unique_reg_number = ?";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    error_log("Prepare failed: " . $conn->error);
    echo json_encode(['status' => 'error', 'message' => 'Database error: prepare failed']);
    exit;
}

$stmt->bind_param(
    "ssssssss",
    $fatherName,
    $motherName,
    $guardianName,
    $relationWithStudent,
    $fatherGuardianMobile,
    $motherMobile,
    $emailId,
    $uniqueId
);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Parent details saved successfully', 'uniqueId' => $uniqueId]);
} else {
    error_log("Execute failed: " . $stmt->error);
    echo json_encode(['status' => 'error', 'message' => 'Database error: execute failed']);
}

$stmt->close();
$conn->close();
