<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    // Validate and sanitize input data
    $hostelId       = filter_var($data['hostel_id'] ?? '', FILTER_SANITIZE_NUMBER_INT);
    $hostelName     = filter_var($data['hostelName'] ?? '', FILTER_SANITIZE_STRING);
    $contactPerson  = filter_var($data['contactPerson'] ?? '', FILTER_SANITIZE_STRING);
    $contactNumber  = filter_var($data['contactNumber'] ?? '', FILTER_SANITIZE_STRING);
    $email          = filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $address        = filter_var($data['address'] ?? '', FILTER_SANITIZE_STRING);
    $city           = filter_var($data['city'] ?? '', FILTER_SANITIZE_STRING);
    $state          = filter_var($data['state'] ?? '', FILTER_SANITIZE_STRING);
    $pincode        = filter_var($data['pincode'] ?? '', FILTER_SANITIZE_STRING);
    $status         = strtolower($data['hostelStatus'] ?? 'inactive');

    // Validation
    if (
        empty($hostelId) || empty($hostelName) || empty($contactPerson) ||
        empty($contactNumber) || empty($address) || empty($city) ||
        empty($state) || empty($pincode) || empty($status)
    ) {
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => 'All required fields must be filled.']);
        exit;
    }

    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => 'Invalid email format.']);
        exit;
    }

    // ✅ FIXED: Use correct column name `name`
    $sql = "UPDATE hostels SET
                name = :hostel_name,
                contact_person = :contact_person,
                contact_number = :contact_number,
                email = :email,
                address = :address,
                city = :city,
                state = :state,
                pincode = :pincode,
                status = :status
            WHERE hostel_id = :hostel_id";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':hostel_name', $hostelName);
        $stmt->bindParam(':contact_person', $contactPerson);
        $stmt->bindParam(':contact_number', $contactNumber);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':address', $address);
        $stmt->bindParam(':city', $city);
        $stmt->bindParam(':state', $state);
        $stmt->bindParam(':pincode', $pincode);
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':hostel_id', $hostelId, PDO::PARAM_INT);

        if ($stmt->execute()) {
            ob_end_clean();
            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Hostel updated successfully!']);
            } else {
                echo json_encode(['success' => false, 'message' => 'No changes made or hostel not found.']);
            }
        } else {
            ob_end_clean();
            echo json_encode(['success' => false, 'message' => 'Failed to update hostel.']);
        }
    } catch (PDOException $e) {
        ob_end_clean();
        if ($e->getCode() == 23000) {
            echo json_encode(['success' => false, 'message' => 'Hostel name already exists. Please choose a different name.']);
        } else {
            error_log("Database error updating hostel: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'A database error occurred. Please try again later.']);
        }
    }
} else {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
