<?php
/**
 * Lands API Endpoint
 * RESTful API for land management
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/polygon_functions.php';

initSecureSession();

$response = ['success' => false, 'message' => '', 'data' => null];

// Authenticate request
$user = authenticateRequest($conn);
if (!$user) {
    $response['message'] = 'Authentication required';
    http_response_code(401);
    echo json_encode($response);
    exit;
}

// Get request method and ID
$method = $_SERVER['REQUEST_METHOD'];
$land_id = isset($_GET['id']) ? intval($_GET['id']) : null;

switch ($method) {
    case 'GET':
        if ($land_id) {
            getLand($conn, $land_id, $user, $response);
        } else {
            getLands($conn, $user, $response);
        }
        break;

    case 'POST':
        createLand($conn, $user, $response);
        break;

    case 'PUT':
        if (!$land_id) {
            $response['message'] = 'Land ID required';
            http_response_code(400);
        } else {
            updateLand($conn, $land_id, $user, $response);
        }
        break;

    case 'DELETE':
        if (!$land_id) {
            $response['message'] = 'Land ID required';
            http_response_code(400);
        } else {
            deleteLand($conn, $land_id, $user, $response);
        }
        break;

    default:
        $response['message'] = 'Method not allowed';
        http_response_code(405);
}

echo json_encode($response);
exit;

/**
 * Authenticate API request
 */
function authenticateRequest($conn) {
    // Try JWT token
    $headers = getallheaders();
    $auth_header = $headers['Authorization'] ?? $headers['authorization'] ?? '';

    if (preg_match('/Bearer\s+(.*)$/i', $auth_header, $matches)) {
        $payload = verifyJWT($matches[1]);
        if ($payload) {
            $result = mysqli_query($conn, "SELECT * FROM users WHERE id = {$payload['user_id']} AND status = 'approved'");
            if ($user = mysqli_fetch_assoc($result)) {
                return $user;
            }
        }
    }

    // Try session
    if (isAuthenticated() && validateSession()) {
        $result = mysqli_query($conn, "SELECT * FROM users WHERE id = {$_SESSION['user_id']} AND status = 'approved'");
        if ($user = mysqli_fetch_assoc($result)) {
            return $user;
        }
    }

    return null;
}

/**
 * Get all lands for user
 */
function getLands($conn, $user, &$response) {
    $user_id = $user['id'];
    $role = $user['role'];

    // Filter parameters
    $client_id = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;
    $status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
    $limit = isset($_GET['limit']) ? min(100, intval($_GET['limit'])) : 50;
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

    // Build query based on role
    if ($role === 'admin') {
        $where = "1=1";
    } elseif ($role === 'broker') {
        $where = "(l.user_id = $user_id OR l.client_id IN (SELECT id FROM clients WHERE broker_id = $user_id))";
    } else {
        $where = "l.user_id = $user_id";
    }

    if ($client_id > 0) {
        $where .= " AND l.client_id = $client_id";
    }
    if ($status) {
        $where .= " AND l.status = '$status'";
    }

    $sql = "SELECT l.*, c.full_name as client_name, u.full_name as owner_name,
                   (SELECT COUNT(*) FROM beacon_points WHERE land_id = l.id) as point_count,
                   r.name as region_name, d.name as district_name
            FROM lands l
            LEFT JOIN clients c ON l.client_id = c.id
            LEFT JOIN users u ON l.user_id = u.id
            LEFT JOIN regions r ON l.region_id = r.id
            LEFT JOIN districts d ON l.district_id = d.id
            WHERE $where
            ORDER BY l.created_at DESC
            LIMIT $limit OFFSET $offset";

    $result = mysqli_query($conn, $sql);
    $lands = [];

    while ($land = mysqli_fetch_assoc($result)) {
        // Get beacon points
        $points_result = mysqli_query($conn, "SELECT * FROM beacon_points WHERE land_id = {$land['id']} ORDER BY point_order");
        $land['beacon_points'] = [];
        while ($point = mysqli_fetch_assoc($points_result)) {
            $land['beacon_points'][] = $point;
        }

        $lands[] = $land;
    }

    // Get total count
    $count_sql = "SELECT COUNT(*) as total FROM lands l WHERE $where";
    $total = mysqli_fetch_assoc(mysqli_query($conn, $count_sql))['total'];

    $response['success'] = true;
    $response['data'] = [
        'lands' => $lands,
        'pagination' => [
            'total' => intval($total),
            'limit' => $limit,
            'offset' => $offset,
            'has_more' => ($offset + $limit) < $total
        ]
    ];
}

/**
 * Get single land by ID
 */
function getLand($conn, $land_id, $user, &$response) {
    $user_id = $user['id'];
    $role = $user['role'];

    // Check access
    require_once '../includes/client_access.php';
    $access = canAccessLand($conn, $land_id, $user_id, $role);

    if (!$access['can_access']) {
        $response['message'] = $access['reason'];
        http_response_code(403);
        return;
    }

    $sql = "SELECT l.*, c.full_name as client_name, c.phone as client_phone,
                   u.full_name as owner_name, r.name as region_name, d.name as district_name
            FROM lands l
            LEFT JOIN clients c ON l.client_id = c.id
            LEFT JOIN users u ON l.user_id = u.id
            LEFT JOIN regions r ON l.region_id = r.id
            LEFT JOIN districts d ON l.district_id = d.id
            WHERE l.id = $land_id";

    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) === 0) {
        $response['message'] = 'Land not found';
        http_response_code(404);
        return;
    }

    $land = mysqli_fetch_assoc($result);

    // Get beacon points
    $points_result = mysqli_query($conn, "SELECT * FROM beacon_points WHERE land_id = $land_id ORDER BY point_order");
    $land['beacon_points'] = [];
    while ($point = mysqli_fetch_assoc($points_result)) {
        $land['beacon_points'][] = $point;
    }

    // Get landmarks
    $landmarks_result = mysqli_query($conn, "SELECT * FROM beacon_landmarks WHERE land_id = $land_id");
    $land['landmarks'] = [];
    while ($lm = mysqli_fetch_assoc($landmarks_result)) {
        $land['landmarks'][] = $lm;
    }

    // Get overlap alerts
    $alerts_result = mysqli_query($conn, "SELECT * FROM overlap_alerts WHERE (land_id_1 = $land_id OR land_id_2 = $land_id) AND is_resolved = 0");
    $land['overlap_alerts'] = [];
    while ($alert = mysqli_fetch_assoc($alerts_result)) {
        $land['overlap_alerts'][] = $alert;
    }

    // Include client status if applicable
    if ($access['client_status']) {
        $land['client_status'] = $access['client_status'];
    }

    $response['success'] = true;
    $response['data'] = $land;
}

/**
 * Create new land
 */
function createLand($conn, $user, &$response) {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

    // Validate required fields
    $land_name = sanitizeInput($input['land_name'] ?? '');
    $points = $input['points'] ?? [];

    if (empty($land_name)) {
        $response['message'] = 'Land name is required';
        http_response_code(400);
        return;
    }

    if (count($points) < 3) {
        $response['message'] = 'At least 3 beacon points are required';
        http_response_code(400);
        return;
    }

    // Sanitize inputs
    $description = mysqli_real_escape_string($conn, $input['description'] ?? '');
    $location_address = mysqli_real_escape_string($conn, $input['location_address'] ?? '');
    $region_id = intval($input['region_id'] ?? 0);
    $district_id = intval($input['district_id'] ?? 0);
    $village = mysqli_real_escape_string($conn, $input['village'] ?? '');
    $area_unit = mysqli_real_escape_string($conn, $input['area_unit'] ?? 'sqm');
    $client_id = intval($input['client_id'] ?? 0);
    $landmarks = $input['landmarks'] ?? [];

    // Verify client access if specified
    if ($client_id > 0 && in_array($user['role'], ['broker', 'admin'])) {
        $check = $user['role'] === 'admin'
            ? "SELECT id FROM clients WHERE id = $client_id"
            : "SELECT id FROM clients WHERE id = $client_id AND broker_id = {$user['id']}";
        if (mysqli_num_rows(mysqli_query($conn, $check)) === 0) {
            $client_id = 0;
        }
    } else {
        $client_id = 0;
    }

    // Calculate area
    $area = calculatePolygonAreaMeters($points);
    if ($area_unit === 'acres') {
        $area = $area / 4046.86;
    } elseif ($area_unit === 'hectares') {
        $area = $area / 10000;
    }

    // Generate share token
    $share_token = bin2hex(random_bytes(32));

    // Prepare SQL values
    $user_id = $user['id'];
    $land_name = mysqli_real_escape_string($conn, $land_name);
    $region_id_sql = $region_id > 0 ? $region_id : 'NULL';
    $district_id_sql = $district_id > 0 ? $district_id : 'NULL';
    $client_id_sql = $client_id > 0 ? $client_id : 'NULL';

    $sql = "INSERT INTO lands (user_id, client_id, land_name, description, location_address, region_id, district_id, village, total_area, area_unit, share_token)
            VALUES ($user_id, $client_id_sql, '$land_name', '$description', '$location_address', $region_id_sql, $district_id_sql, '$village', $area, '$area_unit', '$share_token')";

    if (!mysqli_query($conn, $sql)) {
        $response['message'] = 'Failed to create land';
        http_response_code(500);
        return;
    }

    $land_id = mysqli_insert_id($conn);

    // Insert beacon points
    foreach ($points as $index => $point) {
        $lat = floatval($point['lat']);
        $lng = floatval($point['lng']);
        $label = mysqli_real_escape_string($conn, $point['label'] ?? 'Point ' . ($index + 1));
        $beacon_number = mysqli_real_escape_string($conn, $point['beacon_number'] ?? '');
        $additional_info = mysqli_real_escape_string($conn, $point['additional_info'] ?? '');
        $order = $index + 1;

        mysqli_query($conn, "INSERT INTO beacon_points (land_id, latitude, longitude, point_order, point_label, beacon_number, additional_info)
                            VALUES ($land_id, $lat, $lng, $order, '$label', '$beacon_number', '$additional_info')");
    }

    // Insert landmarks
    foreach ($landmarks as $lm) {
        $from = intval($lm['from']);
        $to = intval($lm['to']);
        $desc = mysqli_real_escape_string($conn, $lm['description'] ?? '');
        if (!empty($desc)) {
            mysqli_query($conn, "INSERT INTO beacon_landmarks (land_id, from_point, to_point, landmark_description)
                                VALUES ($land_id, $from, $to, '$desc')");
        }
    }

    // Check for overlaps
    $overlaps = detectLandOverlaps($conn, $land_id, $points);
    if (!empty($overlaps)) {
        saveOverlapAlerts($conn, $land_id, $overlaps);
    }

    $response['success'] = true;
    $response['message'] = 'Land created successfully';
    $response['data'] = [
        'id' => $land_id,
        'share_token' => $share_token,
        'overlaps_detected' => count($overlaps)
    ];
    http_response_code(201);
}

/**
 * Update existing land
 */
function updateLand($conn, $land_id, $user, &$response) {
    // Check access
    require_once '../includes/client_access.php';
    $access = canAccessLand($conn, $land_id, $user['id'], $user['role']);

    if (!$access['can_access']) {
        $response['message'] = 'Access denied';
        http_response_code(403);
        return;
    }

    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

    // Build update query
    $updates = [];

    if (isset($input['land_name'])) {
        $updates[] = "land_name = '" . mysqli_real_escape_string($conn, $input['land_name']) . "'";
    }
    if (isset($input['description'])) {
        $updates[] = "description = '" . mysqli_real_escape_string($conn, $input['description']) . "'";
    }
    if (isset($input['location_address'])) {
        $updates[] = "location_address = '" . mysqli_real_escape_string($conn, $input['location_address']) . "'";
    }
    if (isset($input['village'])) {
        $updates[] = "village = '" . mysqli_real_escape_string($conn, $input['village']) . "'";
    }
    if (isset($input['region_id'])) {
        $updates[] = "region_id = " . intval($input['region_id']);
    }
    if (isset($input['district_id'])) {
        $updates[] = "district_id = " . intval($input['district_id']);
    }
    if (isset($input['status']) && $user['role'] === 'admin') {
        $updates[] = "status = '" . mysqli_real_escape_string($conn, $input['status']) . "'";
    }

    if (empty($updates)) {
        $response['message'] = 'No fields to update';
        http_response_code(400);
        return;
    }

    $sql = "UPDATE lands SET " . implode(', ', $updates) . " WHERE id = $land_id";

    if (mysqli_query($conn, $sql)) {
        $response['success'] = true;
        $response['message'] = 'Land updated successfully';
    } else {
        $response['message'] = 'Failed to update land';
        http_response_code(500);
    }
}

/**
 * Delete land
 */
function deleteLand($conn, $land_id, $user, &$response) {
    // Check access
    $check_sql = $user['role'] === 'admin'
        ? "SELECT id FROM lands WHERE id = $land_id"
        : "SELECT id FROM lands WHERE id = $land_id AND user_id = {$user['id']}";

    if (mysqli_num_rows(mysqli_query($conn, $check_sql)) === 0) {
        $response['message'] = 'Land not found or access denied';
        http_response_code(403);
        return;
    }

    if (mysqli_query($conn, "DELETE FROM lands WHERE id = $land_id")) {
        $response['success'] = true;
        $response['message'] = 'Land deleted successfully';
    } else {
        $response['message'] = 'Failed to delete land';
        http_response_code(500);
    }
}
?>
