<?php
// Include database connection
require_once 'db_connect.php';

// Set header to return JSON
header('Content-Type: application/json');

// Initialize response array
$response = [
    'status' => 'error',
    'error' => null,
    'units' => [],
    'floor_plan_image_path' => null
];

// Check if required parameters are set
if (!isset($_GET['mall_id']) || empty($_GET['mall_id'])) {
    $response['error'] = 'Mall ID is required';
    echo json_encode($response);
    exit;
}

if (!isset($_GET['level']) || empty($_GET['level'])) {
    $response['error'] = 'Level is required';
    echo json_encode($response);
    exit;
}

// Get and sanitize parameters
$mall_id = intval($_GET['mall_id']);
$level = $conn->real_escape_string($_GET['level']);

// Fetch mall slug for image path construction
$mall_slug = '';
$sql_mall = "SELECT slug FROM malls WHERE id = ?";
if ($stmt_mall = $conn->prepare($sql_mall)) {
    $stmt_mall->bind_param("i", $mall_id);
    if ($stmt_mall->execute()) {
        $stmt_mall->bind_result($mall_slug);
        $stmt_mall->fetch();
    }
    $stmt_mall->close();
}

// Construct floor plan image path
// Adjust this path based on your actual directory structure
$floor_plan_path = "images/malls/{$mall_slug}/level-{$level}.png";

// Check if the floor plan image exists
if (file_exists("../" . $floor_plan_path)) {
    $response['floor_plan_image_path'] = $floor_plan_path;
} else {
    // Try alternate naming formats if the first format doesn't exist
    $alternate_floor_plan_path = "images/malls/{$mall_slug}/level{$level}.png";
    if (file_exists("../" . $alternate_floor_plan_path)) {
        $response['floor_plan_image_path'] = $alternate_floor_plan_path;
    }
    // You could add more alternate formats if needed
}

// Fetch units for the selected mall and level
$units = [];
$sql_units = "SELECT * FROM units WHERE mall_id = ? AND level = ? ORDER BY unit_id_display";
if ($stmt_units = $conn->prepare($sql_units)) {
    $stmt_units->bind_param("is", $mall_id, $level);
    if ($stmt_units->execute()) {
        $result = $stmt_units->get_result();
        while ($row = $result->fetch_assoc()) {
            $units[] = $row;
        }
    } else {
        $response['error'] = 'Error executing query: ' . $stmt_units->error;
        echo json_encode($response);
        exit;
    }
    $stmt_units->close();
} else {
    $response['error'] = 'Error preparing query: ' . $conn->error;
    echo json_encode($response);
    exit;
}

// Update response with success status and data
$response['status'] = 'success';
$response['units'] = $units;

// Return the JSON response
echo json_encode($response);

// Close connection
$conn->close();