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

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

require_once 'config.php';

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

$uniqueId                  = $_POST['uniqueId'] ?? '';
$emergencyContactName      = $_POST['emergencyContactName'] ?? '';
$emergencyRelation         = $_POST['emergencyRelation'] ?? '';
$emergencyMobile           = $_POST['emergencyMobile'] ?? '';
$emergencyAlternateNumber  = $_POST['emergencyAlternateNumber'] ?? '';

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

$sql = "UPDATE students 
        SET emergency_contact_name = ?, emergency_relation = ?, emergency_mobile = ?, emergency_alternate_number = ?
        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("sssss", $emergencyContactName, $emergencyRelation, $emergencyMobile, $emergencyAlternateNumber, $uniqueId);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Emergency contact 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();
