<?php
/**
 * Walk Around GPS Tracking API
 * Handles saving and managing walk-around GPS tracking sessions
 */

define('APP_RUNNING', true);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../db_connect.php';

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check authentication
$user_id = $_SESSION['user_id'] ?? 0;
if (!$user_id) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_GET['action'] ?? '';

// Ensure tables exist
ensureTablesExist($conn);

switch ($action) {
    case 'save_session':
        saveSession($conn, $input, $user_id);
        break;

    case 'save_point':
        savePoint($conn, $input, $user_id);
        break;

    case 'delete_session':
        deleteSession($conn, $input, $user_id);
        break;

    case 'get_sessions':
        getSessions($conn, $input, $user_id);
        break;

    case 'get_points':
        getPoints($conn, $input, $user_id);
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
}

function ensureTablesExist($conn) {
    // Create walk_around_sessions table if not exists
    $conn->query("
        CREATE TABLE IF NOT EXISTS `walk_around_sessions` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `session_id` VARCHAR(50) NOT NULL,
            `land_id` INT(11) NOT NULL,
            `user_id` INT(11) NOT NULL,
            `total_points` INT(11) DEFAULT 0,
            `total_distance` DECIMAL(12,4) DEFAULT 0,
            `avg_accuracy` DECIMAL(10,2) DEFAULT NULL,
            `calculated_area` DECIMAL(15,4) DEFAULT NULL,
            `area_unit` VARCHAR(20) DEFAULT 'sqm',
            `started_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            `completed_at` TIMESTAMP NULL,
            `status` ENUM('recording', 'completed', 'cancelled') DEFAULT 'recording',
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_session` (`session_id`),
            KEY `land_id` (`land_id`),
            KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    // Create walk_around_points table if not exists
    $conn->query("
        CREATE TABLE IF NOT EXISTS `walk_around_points` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `land_id` INT(11) NOT NULL,
            `session_id` VARCHAR(50) NOT NULL,
            `latitude` DECIMAL(12,8) NOT NULL,
            `longitude` DECIMAL(12,8) NOT NULL,
            `accuracy` DECIMAL(10,2) DEFAULT NULL,
            `altitude` DECIMAL(10,2) DEFAULT NULL,
            `point_order` INT(11) NOT NULL DEFAULT 0,
            `recorded_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `land_id` (`land_id`),
            KEY `session_id` (`session_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

function saveSession($conn, $input, $user_id) {
    $session_id = $conn->real_escape_string($input['session_id'] ?? '');
    $land_id = intval($input['land_id'] ?? 0);
    $status = $conn->real_escape_string($input['status'] ?? 'recording');
    $total_points = intval($input['total_points'] ?? 0);
    $total_distance = floatval($input['total_distance'] ?? 0);
    $avg_accuracy = floatval($input['avg_accuracy'] ?? 0);
    $calculated_area = floatval($input['calculated_area'] ?? 0);

    if (empty($session_id) || $land_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Missing required fields']);
        return;
    }

    // Verify user owns the land
    $landCheck = $conn->query("SELECT id FROM lands WHERE id = $land_id AND user_id = $user_id");
    if ($landCheck->num_rows == 0) {
        echo json_encode(['success' => false, 'error' => 'Land not found or access denied']);
        return;
    }

    // Check if session exists
    $existing = $conn->query("SELECT id FROM walk_around_sessions WHERE session_id = '$session_id'");

    if ($existing->num_rows > 0) {
        // Update existing session
        $completed_at = $status == 'completed' ? "NOW()" : "NULL";
        $sql = "UPDATE walk_around_sessions SET
                status = '$status',
                total_points = $total_points,
                total_distance = $total_distance,
                avg_accuracy = $avg_accuracy,
                calculated_area = $calculated_area,
                completed_at = $completed_at
                WHERE session_id = '$session_id'";
    } else {
        // Insert new session
        $sql = "INSERT INTO walk_around_sessions
                (session_id, land_id, user_id, status, total_points, total_distance, avg_accuracy, calculated_area)
                VALUES ('$session_id', $land_id, $user_id, '$status', $total_points, $total_distance, $avg_accuracy, $calculated_area)";
    }

    if ($conn->query($sql)) {
        echo json_encode(['success' => true, 'message' => 'Session saved']);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $conn->error]);
    }
}

function savePoint($conn, $input, $user_id) {
    $session_id = $conn->real_escape_string($input['session_id'] ?? '');
    $land_id = intval($input['land_id'] ?? 0);
    $latitude = floatval($input['latitude'] ?? 0);
    $longitude = floatval($input['longitude'] ?? 0);
    $accuracy = floatval($input['accuracy'] ?? 0);
    $altitude = isset($input['altitude']) ? floatval($input['altitude']) : 'NULL';
    $point_order = intval($input['point_order'] ?? 0);

    if (empty($session_id) || $land_id <= 0 || $latitude == 0 || $longitude == 0) {
        echo json_encode(['success' => false, 'error' => 'Missing required fields']);
        return;
    }

    // Verify user owns the land
    $landCheck = $conn->query("SELECT id FROM lands WHERE id = $land_id AND user_id = $user_id");
    if ($landCheck->num_rows == 0) {
        echo json_encode(['success' => false, 'error' => 'Land not found or access denied']);
        return;
    }

    $altitude_sql = is_numeric($altitude) ? $altitude : 'NULL';

    $sql = "INSERT INTO walk_around_points
            (land_id, session_id, latitude, longitude, accuracy, altitude, point_order)
            VALUES ($land_id, '$session_id', $latitude, $longitude, $accuracy, $altitude_sql, $point_order)";

    if ($conn->query($sql)) {
        echo json_encode(['success' => true, 'point_id' => $conn->insert_id]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $conn->error]);
    }
}

function deleteSession($conn, $input, $user_id) {
    $session_id = $conn->real_escape_string($input['session_id'] ?? '');
    $land_id = intval($input['land_id'] ?? 0);

    if (empty($session_id) || $land_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Missing required fields']);
        return;
    }

    // Verify user owns the land
    $landCheck = $conn->query("SELECT id FROM lands WHERE id = $land_id AND user_id = $user_id");
    if ($landCheck->num_rows == 0) {
        echo json_encode(['success' => false, 'error' => 'Land not found or access denied']);
        return;
    }

    // Delete points first
    $conn->query("DELETE FROM walk_around_points WHERE session_id = '$session_id' AND land_id = $land_id");

    // Delete session
    $conn->query("DELETE FROM walk_around_sessions WHERE session_id = '$session_id' AND land_id = $land_id");

    echo json_encode(['success' => true, 'message' => 'Session deleted']);
}

function getSessions($conn, $input, $user_id) {
    $land_id = intval($input['land_id'] ?? $_GET['land_id'] ?? 0);

    if ($land_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Missing land_id']);
        return;
    }

    // Verify user owns the land
    $landCheck = $conn->query("SELECT id FROM lands WHERE id = $land_id AND user_id = $user_id");
    if ($landCheck->num_rows == 0) {
        echo json_encode(['success' => false, 'error' => 'Land not found or access denied']);
        return;
    }

    $result = $conn->query("SELECT * FROM walk_around_sessions WHERE land_id = $land_id ORDER BY started_at DESC");
    $sessions = [];
    while ($row = $result->fetch_assoc()) {
        $sessions[] = $row;
    }

    echo json_encode(['success' => true, 'sessions' => $sessions]);
}

function getPoints($conn, $input, $user_id) {
    $session_id = $conn->real_escape_string($input['session_id'] ?? $_GET['session_id'] ?? '');
    $land_id = intval($input['land_id'] ?? $_GET['land_id'] ?? 0);

    if (empty($session_id) || $land_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Missing required fields']);
        return;
    }

    // Verify user owns the land
    $landCheck = $conn->query("SELECT id FROM lands WHERE id = $land_id AND user_id = $user_id");
    if ($landCheck->num_rows == 0) {
        echo json_encode(['success' => false, 'error' => 'Land not found or access denied']);
        return;
    }

    $result = $conn->query("SELECT * FROM walk_around_points WHERE session_id = '$session_id' ORDER BY point_order");
    $points = [];
    while ($row = $result->fetch_assoc()) {
        $points[] = [
            'lat' => floatval($row['latitude']),
            'lng' => floatval($row['longitude']),
            'accuracy' => floatval($row['accuracy']),
            'altitude' => $row['altitude'] ? floatval($row['altitude']) : null,
            'order' => intval($row['point_order'])
        ];
    }

    echo json_encode(['success' => true, 'points' => $points]);
}
?>
