<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Authorization, Content-Type");

// Include configuration
require_once 'config.php';

$conn = getDbConnection();
if (!$conn) {
    error_log("Database connection failed: " . mysqli_connect_error());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection failed"]);
    exit();
}

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

// Validate Authorization header
$headers = apache_request_headers();
$authHeader = $headers['Authorization'] ?? null;
if (!$authHeader || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Unauthorized: Missing or invalid token"]);
    exit();
}

$token = $matches[1];
$stmt = $conn->prepare("SELECT user_id FROM users WHERE token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
if (!$user) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Unauthorized: Invalid token"]);
    exit();
}

$userId = $user['user_id'];

// Validate house_id and file
$houseId = $_POST['house_id'] ?? null;
if (!$houseId || !is_numeric($houseId)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Invalid or missing house ID"]);
    exit();
}

if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "File upload error"]);
    exit();
}

// Validate file type
$file = $_FILES['image'];
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($file['type'], $allowedTypes)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Invalid file type"]);
    exit();
}

// Set up directories
$baseUploadDir = $config['UPLOAD_DIR'] ?? (__DIR__ . '/../uploads/');
if (!is_dir($baseUploadDir) && !mkdir($baseUploadDir, 0755, true)) {
    error_log("Failed to create base directory: $baseUploadDir");
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to create base upload directory"]);
    exit();
}

$uploadDir = $baseUploadDir . "house_$houseId/";
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
    error_log("Failed to create house directory: $uploadDir");
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to create upload directory"]);
    exit();
}

// Save file
$fileName = uniqid() . "_" . basename($file['name']);
$filePath = $uploadDir . $fileName;

if (!move_uploaded_file($file['tmp_name'], $filePath)) {
    error_log("Failed to save file: $filePath");
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to save file"]);
    exit();
}

// Save metadata
$description = htmlspecialchars($_POST['description'] ?? '', ENT_QUOTES, 'UTF-8');
$stmt = $conn->prepare("INSERT INTO visitorimages (user_id, house_id, file_name, description) VALUES (?, ?, ?, ?)");
$stmt->bind_param("iiss", $userId, $houseId, $fileName, $description);
if (!$stmt->execute()) {
    error_log("Failed to save metadata: " . $stmt->error);
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to save metadata"]);
    exit();
}

// Set up base URL
$baseUrl = $config['BASE_URL'] ?? (
    isset($_SERVER['HTTPS']) ? 'https://' : 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/'
);

$fileUrl = $baseUrl . "house_$houseId/$fileName";

http_response_code(200);
echo json_encode([
    "status" => "success",
    "imageUrl" => $fileUrl,
    "message" => "Image uploaded successfully"
]);
?>

