<?php
ob_start(); // Prevent unexpected output

// Show all errors during development
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);

    // Sanitize inputs
    $hostelName     = trim(filter_var($data['hostelName'] ?? '', FILTER_SANITIZE_STRING));
    $contactPerson  = trim(filter_var($data['contactPerson'] ?? '', FILTER_SANITIZE_STRING));
    $contactNumber  = trim(filter_var($data['contactNumber'] ?? '', FILTER_SANITIZE_STRING));
    $email          = trim(filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL));
    $address        = trim(filter_var($data['address'] ?? '', FILTER_SANITIZE_STRING));
    $city           = trim(filter_var($data['city'] ?? '', FILTER_SANITIZE_STRING));
    $state          = trim(filter_var($data['state'] ?? '', FILTER_SANITIZE_STRING));
    $pincode        = trim(filter_var($data['pincode'] ?? '', FILTER_SANITIZE_STRING));
    $status         = ($data['hostelStatus'] ?? 'inactive') === 'active' ? 'active' : 'inactive';

    // Required check
    if (
        empty($hostelName) || empty($contactPerson) || empty($contactNumber) ||
        empty($address) || empty($city) || empty($state) || empty($pincode)
    ) {
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => 'Please fill all required fields.']);
        exit;
    }

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

    // Insert SQL
    $sql = "INSERT INTO hostels (
                name, contact_person, contact_number, email, address, city, state, pincode, status
            ) VALUES (
                :name, :contact_person, :contact_number, :email, :address, :city, :state, :pincode, :status
            )";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':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);

        if ($stmt->execute()) {
            ob_end_clean();
            echo json_encode(['success' => true, 'message' => 'Hostel added successfully!']);
        } else {
            ob_end_clean();
            echo json_encode(['success' => false, 'message' => 'Failed to add hostel. Please try again.']);
        }
    } catch (PDOException $e) {
        ob_end_clean();
        if ($e->getCode() == 23000) {
            echo json_encode(['success' => false, 'message' => 'Hostel name already exists.']);
        } else {
            error_log("DB error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
    }
} else {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
