<?php

use App\Http\Controllers\ActivityLogController;
use App\Http\Controllers\PointController;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;

use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\Api\UserController;
use App\Http\Controllers\Api\NotificationController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\SenManagerController;
use App\Http\Controllers\ManagerController;
use App\Http\Controllers\OperatorController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\PermissionController;
use App\Http\Controllers\RequestController;
use App\Http\Controllers\RequestPlanSignatureController;
use App\Http\Controllers\PointPlanController;
use App\Http\Controllers\DistrictController;
use App\Http\Controllers\RegionController;
use App\Http\Controllers\CounterController;
use App\Http\Controllers\PlanFileController;
use App\Http\Controllers\PlanStatsController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\RefController;

/**
 * Public Auth & Registration
 */
Route::prefix('auth')->group(function () {
    Route::post('sign-in', [AuthenticatedSessionController::class, 'signIn']);
    Route::middleware('auth:sanctum')->group(function () {
        Route::post('sign-out', [AuthenticatedSessionController::class, 'destroy'])->name('logout');
        Route::post('register', [RegisteredUserController::class, 'store'])->name('register');
    });
});

/**
 * Password Management
 */
Route::middleware('auth:sanctum')->group(function () {
    Route::patch('user/change-password', [UserController::class, 'changePassword'])->name('changePassword');
});

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/counters', [CounterController::class, 'index']);
    Route::post('/counters', [CounterController::class, 'store']);
    Route::put('/counters/{counter}', [CounterController::class, 'update']);
    Route::delete('/counters/{counter}', [CounterController::class, 'destroy']);
});


/**
 * Admin Endpoints (Auth protected)
 */
Route::middleware('auth:sanctum')->group(function () {
    // Backward compatibility
    Route::get('point-list-for-map', [AdminController::class, 'getPointsForMap']);
    Route::get('point-list', [AdminController::class, 'getPointList']);

    // Users CRUD
    Route::prefix('users')->group(function () {
        Route::get('/', [AdminController::class, 'getUsers']);
        Route::get('{id}', [AdminController::class, 'getUserInfo']);
        Route::patch('{id}', [AdminController::class, 'editUser']);
        Route::delete('{id}', [AdminController::class, 'delUser']);
    });

    // Logs

    Route::get('/points/names', [PointController::class, 'names']);

    Route::apiResource('points', PointController::class);

    // Список регионов с вложенными районами
    Route::get('regions', [RegionController::class, 'index'])->name('regions.index');

    // Senior manager assignment
    Route::get('get-regions-and-sen-managers', [AdminController::class, 'getRegionsAndSenManagers']);
    Route::match(['post','patch'], 'purpose-sen-manager', [AdminController::class, 'proposeSenManagerToRegion']);

    // Generate plans
    Route::post('generate-point-plans', [AdminController::class, 'generatePointPlans']);

    // Points management

    Route::prefix('points')->group(function () {
        Route::get('/', [AdminController::class, 'getPointList']);
        Route::get('{id}', [AdminController::class, 'getInfoPointForEdit']);
        Route::post('/', [AdminController::class, 'createPoint']);
        Route::patch('{id}', [AdminController::class, 'editPoint']);
    });
});

/**
 * Notifications
 */
Route::middleware('auth:sanctum')->prefix('notifications')->group(function () {
    Route::get('/', [NotificationController::class, 'index']);
    Route::post('{id}/read', [NotificationController::class, 'markAsRead']);
});

/**
 * Roles & Permissions
 */
Route::middleware('auth:sanctum')->group(function () {
    Route::get('roles', [RoleController::class, 'index']);
    Route::apiResource('permissions', PermissionController::class)->except(['create','edit']);
    Route::post('roles/{role}/permissions/{perm}', [RoleController::class, 'attachPermission']);
    Route::delete('roles/{role}/permissions/{perm}', [RoleController::class, 'detachPermission']);
});

/**
 * Requests & Signatures
 */
Route::middleware('auth:sanctum')->prefix('requests')->group(function () {
    Route::get('/', [RequestController::class, 'index']);
    Route::post('/', [RequestController::class, 'store']);
    Route::patch('{id}', [RequestController::class, 'update']);
    Route::get('{id}/points', [RequestController::class, 'getPointsByRequest']);
    Route::post('{id}/add-points', [RequestController::class, 'addPointsToRequest']);
    Route::get('{id}/photos', [RequestController::class, 'photos']);
    Route::post('{requestModel}/plan-signature', [RequestPlanSignatureController::class, 'store']);
    Route::post('{id}/lock', [RequestController::class, 'lock']);
    Route::post('{id}/import-by-name', [RequestController::class, 'importPointsByName']);
    Route::post('{id}/sync-points',       [RequestController::class, 'syncPointsAndDeactivatePlans']);
    Route::get('{id}/date-range', [AdminController::class, 'getRequestPlansDateRange']);
    Route::get('{id}/district-date-ranges', [AdminController::class, 'getRequestDistrictRanges']);
});

/**
 * Senior Manager Routes
 */
Route::middleware('auth:sanctum')->prefix('sen-manager')->group(function () {
    Route::get('districts-for-assignment', [SenManagerController::class, 'getRegionsAndManagers']);
    Route::post('purpose-manager', [SenManagerController::class, 'proposeManagerToDistrict']);

    Route::get('schedule-plan-list', [SenManagerController::class, 'getSchedulePlanList']);
    Route::post('create-schedule-plan', [SenManagerController::class, 'createSchedulePlan']);
    Route::post('create-signature-schedule/{id}', [SenManagerController::class, 'createSignatureSchedule']);

    Route::get('point-plan-info/{id}', [SenManagerController::class, 'schedulePlanInfo']);
    Route::post('create-point-plan', [SenManagerController::class, 'createPointPlan']);
    Route::get('point-plans-list', [SenManagerController::class, 'getPointPlansList']);
    Route::get('point-plan/{id}', [SenManagerController::class, 'getPointPlanInfo']);
    Route::patch('point-plan/{id}', [SenManagerController::class, 'updatePointPlan']);
    Route::delete('point-plan/{id}', [SenManagerController::class, 'delPointPlan']);
    Route::post('sign-request-plan', [SenManagerController::class, 'signRequestPlan']);

    Route::prefix('calendar')->group(function () {
        Route::get('view/{id}', [SenManagerController::class, 'calendarView']);
        Route::get('view/{id}/signed-periods', [SenManagerController::class, 'calendarViewByRequest']);
        Route::get('schedule-plan/{id}/meta', [SenManagerController::class, 'getCalendarMeta']);
        Route::get('schedule-plan/{id}/points', [SenManagerController::class, 'getFilteredPoints']);
    });
});

/**
 * Manager Routes
 */
Route::middleware('auth:sanctum')->prefix('manager')->group(function () {
    Route::get('points-and-operators/{id}', [ManagerController::class, 'getPointsAndOperators']);
    Route::match(['post','patch'], 'purpose-operator', [ManagerController::class, 'proposeOperatorToPointPlan']);
    Route::get('nearest-point-plans/{id}', [ManagerController::class, 'getNearestPointPlans']);
});

/**
 * Operator Routes
 */
Route::middleware('auth:sanctum')->prefix('operator')->group(function () {
    Route::get('points-plans', [OperatorController::class, 'getPoints']);
    Route::get('point-plan/{id}', [OperatorController::class, 'getPointPlanInfo']);
    Route::post('upload-file', [OperatorController::class, 'uploadFile']);
    Route::post('signature-point-plan/{id}', [OperatorController::class, 'createSignaturePointPlan']);
});

/**
 * Geographic & Reference Data
 */
Route::middleware('auth:sanctum')->group(function () {
    Route::prefix('ref')->group(function () {
        Route::get('managers', [RefController::class, 'managers']);
        Route::get('districts', [RefController::class, 'districts']);
        Route::get('regions-for-assignment', [RegionController::class, 'forGroupAssignment']);
        Route::post('regions/assign-group-manager', [RegionController::class, 'assignGroupManager']);
        Route::get('districts/group-assignment', [DistrictController::class, 'forGroupAssignment']);
        Route::get('districts/subgroup-assignment', [DistrictController::class, 'forSubgroupAssignment']);
    });
    Route::get('districts/subgroup-managers', [AdminController::class, 'getDistrictsAndSubgroupManagers']);
    Route::post('districts/assign-group-manager', [DistrictController::class, 'assignGroupManager']);
    Route::post('districts/assign-subgroup-manager', [DistrictController::class, 'assignSubgroupManager']);
});

/**
 * Plan Entities, Files & Stats
 */
Route::get('point-plans/summary', [PointPlanController::class, 'summary'])->middleware('auth:sanctum');
Route::middleware('auth:sanctum')->group(function () {

    Route::prefix('logs')->group(function () {
        Route::get('/', [ActivityLogController::class, 'index']);
        Route::get('/objects', [ActivityLogController::class, 'objects']);
    });

    Route::apiResource('point-plans', PointPlanController::class)->except(['create','edit']);
    Route::apiResource('districts', DistrictController::class)->except(['create','edit']);
    Route::apiResource('regions', RegionController::class)->except(['create','edit']);

    Route::apiResource('admins', AdminController::class)->except(['create','edit']);

    Route::prefix('plan-files')->group(function () {
        Route::post('upload', [PlanFileController::class, 'upload']);
        Route::get('{plan}', [PlanFileController::class, 'list']);
        Route::delete('{id}', [PlanFileController::class, 'destroy']);
    });

    Route::prefix('reports')->group(function () {
        Route::prefix('traffic')->group(function () {
            Route::get('detailed', [ReportController::class, 'trafficDetailedJson']);
            Route::get('detailed/export', [ReportController::class, 'exportDetailed']);
        });
        Route::get('schedules/{id}/export-excel', [ReportController::class, 'exportScheduleExcel']);
        Route::get('ks2/download', [ReportController::class, 'downloadks2']);
        Route::post('photos', [ReportController::class, 'startPhotoReport']);
        Route::get('photos/status/{jobId}', [ReportController::class, 'photoReportStatus']);
        // routes/api.php
        Route::get('photos', [ReportController::class, 'listPhotoReports']);


    });
    // Plan Entities, Files & Stats
    Route::get('vehicle-categories', [PlanStatsController::class, 'categories']);
    Route::get('plan-stats/previous', [PlanStatsController::class, 'getPreviousStats']);
    Route::get('plan-stats/{plan}',    [PlanStatsController::class, 'show']);
    Route::post('plan-stats/{plan}', [PlanStatsController::class, 'store']);


});
