<?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'] ?? '';
$permanentAddress     = $_POST['permanentAddress'] ?? '';
$correspondenceAddress= $_POST['correspondenceAddress'] ?? '';
$district             = $_POST['district'] ?? '';
$state                = $_POST['state'] ?? '';
$pincode              = $_POST['pincode'] ?? '';

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

$sql = "UPDATE students 
        SET permanent_address = ?, correspondence_address = ?, district = ?, state = ?, pincode = ?
        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("ssssss", $permanentAddress, $correspondenceAddress, $district, $state, $pincode, $uniqueId);

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