<?php
/**
 * Patrol Management API Handlers
 * Add these handlers for managing patrol points and settings
 */

// Add these case statements to the API router in public/api.php:
/*
    // Patrol Management API
    case 'patrol/points/list':
        handleGetPatrolPoints($_GET['post_id'] ?? null);
        break;
    case 'patrol/points/create':
        handleCreatePatrolPoint();
        break;
    case 'patrol/points/update':
        handleUpdatePatrolPoint($_GET['id'] ?? null);
        break;
    case 'patrol/points/delete':
        handleDeletePatrolPoint($_GET['id'] ?? null);
        break;
    case 'patrol/points/generate-qr':
        handleGenerateQRCode($_GET['point_id'] ?? null);
        break;
*/

function handleGetPatrolPoints($postId) {
    global $auth, $db;

    if (!$auth->isAuthenticated() || !$postId) {
        http_response_code(400);
        echo json_encode(['error' => 'Post ID required']);
        return;
    }

    if (!$auth->hasPermission('manage_patrols')) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden']);
        return;
    }

    try {
        $points = $db->fetchAll(
            "SELECT * FROM patrol_points WHERE post_id = ? ORDER BY point_name ASC",
            [$postId]
        );

        echo json_encode([
            'success' => true,
            'data' => $points,
            'count' => count($points)
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

function handleCreatePatrolPoint() {
    global $auth, $db;

    if (!$auth->isAuthenticated()) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        return;
    }

    if (!$auth->hasPermission('manage_patrols')) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden']);
        return;
    }

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

    if (empty($input['post_id']) || empty($input['point_name'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Post ID and point name required']);
        return;
    }

    try {
        // Generate unique QR code
        $qrCode = 'PATROL-' . $input['post_id'] . '-' . bin2hex(random_bytes(8));

        // Check if we have 4 patrol points already
        $count = $db->fetch(
            "SELECT COUNT(*) as cnt FROM patrol_points WHERE post_id = ?",
            [$input['post_id']]
        );

        if ($count['cnt'] >= 4) {
            http_response_code(400);
            echo json_encode(['error' => 'Maximum 4 patrol points per post']);
            return;
        }

        $db->query(
            "INSERT INTO patrol_points (post_id, point_name, qr_code, latitude, longitude, location_description, is_active)
             VALUES (?, ?, ?, ?, ?, ?, TRUE)",
            [
                $input['post_id'],
                $input['point_name'],
                $qrCode,
                $input['latitude'] ?? null,
                $input['longitude'] ?? null,
                $input['location_description'] ?? null
            ]
        );

        $pointId = $db->lastInsertId();

        echo json_encode([
            'success' => true,
            'id' => $pointId,
            'qr_code' => $qrCode,
            'message' => 'Patrol point created successfully'
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create patrol point: ' . $e->getMessage()]);
    }
}

function handleUpdatePatrolPoint($id) {
    global $auth, $db;

    if (!$auth->isAuthenticated() || !$id) {
        http_response_code(400);
        echo json_encode(['error' => 'Point ID required']);
        return;
    }

    if (!$auth->hasPermission('manage_patrols')) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden']);
        return;
    }

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

    try {
        $updates = [];
        $params = [];

        if (isset($input['point_name'])) {
            $updates[] = "point_name = ?";
            $params[] = $input['point_name'];
        }

        if (isset($input['location_description'])) {
            $updates[] = "location_description = ?";
            $params[] = $input['location_description'];
        }

        if (isset($input['latitude'])) {
            $updates[] = "latitude = ?";
            $params[] = $input['latitude'];
        }

        if (isset($input['longitude'])) {
            $updates[] = "longitude = ?";
            $params[] = $input['longitude'];
        }

        if (isset($input['is_active'])) {
            $updates[] = "is_active = ?";
            $params[] = $input['is_active'] ? 1 : 0;
        }

        if (empty($updates)) {
            echo json_encode(['error' => 'No fields to update']);
            return;
        }

        $updates[] = "updated_at = NOW()";
        $params[] = $id;

        $db->query(
            "UPDATE patrol_points SET " . implode(", ", $updates) . " WHERE id = ?",
            $params
        );

        echo json_encode(['success' => true, 'message' => 'Patrol point updated']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Update failed: ' . $e->getMessage()]);
    }
}

function handleDeletePatrolPoint($id) {
    global $auth, $db;

    if (!$auth->isAuthenticated() || !$id) {
        http_response_code(400);
        echo json_encode(['error' => 'Point ID required']);
        return;
    }

    if (!$auth->hasPermission('manage_patrols')) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden']);
        return;
    }

    try {
        $db->query("DELETE FROM patrol_points WHERE id = ?", [$id]);

        echo json_encode(['success' => true, 'message' => 'Patrol point deleted']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Delete failed: ' . $e->getMessage()]);
    }
}

function handleGenerateQRCode($pointId) {
    global $auth, $db;

    if (!$auth->isAuthenticated() || !$pointId) {
        http_response_code(400);
        echo json_encode(['error' => 'Point ID required']);
        return;
    }

    try {
        $point = $db->fetch("SELECT * FROM patrol_points WHERE id = ?", [$pointId]);

        if (!$point) {
            http_response_code(404);
            echo json_encode(['error' => 'Patrol point not found']);
            return;
        }

        // Generate QR code image (use phpqrcode library or similar)
        // For now, return the QR code value
        echo json_encode([
            'success' => true,
            'qr_code' => $point['qr_code'],
            'point_name' => $point['point_name'],
            'post_id' => $point['post_id']
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'QR generation failed: ' . $e->getMessage()]);
    }
}
