<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\AuthController;
use App\Http\Controllers\Admin\System\StoreController;
use App\Http\Controllers\Admin\System\DepartmentController;
use App\Http\Controllers\Admin\System\PositionController;
use App\Http\Controllers\Admin\System\UserController;
use App\Http\Controllers\Admin\System\RoleController;
use App\Http\Controllers\Admin\System\MenuController;
use App\Http\Controllers\Admin\System\PermissionController;
use App\Http\Controllers\Admin\System\DictionaryController;
use App\Http\Controllers\Admin\System\OperationLogController;
use App\Http\Controllers\Admin\Crm\ChannelController;
use App\Http\Controllers\Admin\Crm\LeadController;
use App\Http\Controllers\Admin\Crm\CustomerController;
use App\Http\Controllers\Admin\Crm\ContractController;
use App\Http\Controllers\Admin\Crm\QuestionnaireController;
use App\Http\Controllers\Admin\Crm\ComplaintController;
use App\Http\Controllers\Admin\Room\RoomTypeController;
use App\Http\Controllers\Admin\Room\RoomController;
use App\Http\Controllers\Admin\Room\ReservationController;
use App\Http\Controllers\Admin\Room\CustomerOutingController;
use App\Http\Controllers\Admin\Room\CallRecordController;
use App\Http\Controllers\Admin\Care\CareProfileController;
use App\Http\Controllers\Admin\Care\CarePlanController;
use App\Http\Controllers\Admin\Care\CareRecordController;
use App\Http\Controllers\Admin\Care\CareExceptionController;
use App\Http\Controllers\Admin\Care\HealthMetricController;
use App\Http\Controllers\Admin\Meal\DishController;
use App\Http\Controllers\Admin\Meal\MealPlanTemplateController;
use App\Http\Controllers\Admin\Meal\DailyMealPlanController;
use App\Http\Controllers\Admin\Meal\MealReviewController;
use App\Http\Controllers\Admin\Service\ServiceItemController;
use App\Http\Controllers\Admin\Service\ServicePackageController;
use App\Http\Controllers\Admin\Service\ServiceOrderController;
use App\Http\Controllers\Admin\Service\ServiceExecutionController;
use App\Http\Controllers\Admin\Nanny\NannyController;
use App\Http\Controllers\Admin\Nanny\NannyOrderController;
use App\Http\Controllers\Admin\Nanny\NannyScheduleController;
use App\Http\Controllers\Admin\Inventory\WarehouseController;
use App\Http\Controllers\Admin\Inventory\SupplierController;
use App\Http\Controllers\Admin\Inventory\MaterialController;
use App\Http\Controllers\Admin\Inventory\PurchaseOrderController;
use App\Http\Controllers\Admin\Inventory\StockMovementController;
use App\Http\Controllers\Admin\Inventory\InventoryController;
use App\Http\Controllers\Admin\Inventory\StockController;
use App\Http\Controllers\Admin\Inventory\TransferOrderController;
use App\Http\Controllers\Admin\Inventory\InventoryCheckController;
use App\Http\Controllers\Admin\Finance\FinanceCategoryController;
use App\Http\Controllers\Admin\Finance\FinanceRecordController;
use App\Http\Controllers\Admin\Finance\CustomerAccountController;
use App\Http\Controllers\Admin\Finance\AccountTransactionController;
use App\Http\Controllers\Admin\Finance\PrepaidCardController;
use App\Http\Controllers\Admin\Finance\InvoiceController;
use App\Http\Controllers\Admin\Hr\EmployeeProfileController;
use App\Http\Controllers\Admin\Hr\ScheduleController;
use App\Http\Controllers\Admin\Hr\AttendanceRecordController;
use App\Http\Controllers\Admin\Hr\LeaveRequestController;
use App\Http\Controllers\Admin\Hr\SalaryRecordController;
use App\Http\Controllers\Admin\Office\ApprovalTemplateController;
use App\Http\Controllers\Admin\Office\ApprovalController;
use App\Http\Controllers\Admin\Office\AnnouncementController;
use App\Http\Controllers\Admin\Office\HandoverController;
use App\Http\Controllers\Admin\Office\NotificationController;
use App\Http\Controllers\Admin\Report\ReportController;
use App\Http\Controllers\Admin\Report\ReportExportController;
use App\Http\Controllers\Admin\Kb\KbCategoryController;
use App\Http\Controllers\Admin\Kb\KbArticleController;
use App\Http\Controllers\Admin\System\RegistrationPackageController;

/*
|--------------------------------------------------------------------------
| 后台管理 API 路由
|--------------------------------------------------------------------------
| 前缀: /api/v1/ (在 bootstrap/app.php 中配置)
*/

// ===== 公开路由（无需认证） =====
Route::post('/auth/login', [AuthController::class, 'login']);
Route::post('/auth/register', [AuthController::class, 'register']);
Route::get('/auth/register/packages', [AuthController::class, 'registrationPackages']);
Route::get('/auth/register/departments', [AuthController::class, 'departments']);
Route::get('/auth/stores', [\App\Http\Controllers\Admin\System\StoreController::class, 'publicList']);

// ===== 需要认证的路由 =====
Route::middleware(['auth:sanctum', 'store', 'oplog'])->group(function () {

    // --- 认证 ---
    Route::post('/auth/logout', [AuthController::class, 'logout']);
    Route::get('/auth/me', [AuthController::class, 'me']);

    // --- 系统设置模块 ---
    Route::prefix('system')->group(function () {

        // 门店管理
        Route::apiResource('stores', StoreController::class);

        // 部门管理
        Route::apiResource('departments', DepartmentController::class)->except(['show']);

        // 职务管理
        Route::apiResource('positions', PositionController::class)->except(['show']);

        // 用户管理
        Route::apiResource('users', UserController::class);
        Route::put('users/{user}/status', [UserController::class, 'updateStatus']);
        Route::put('users/{user}/password', [UserController::class, 'resetPassword']);
        Route::put('users/{user}/approve', [UserController::class, 'approve']);
        Route::put('users/{user}/reject', [UserController::class, 'reject']);

        // 注册套餐管理
        Route::apiResource('registration-packages', RegistrationPackageController::class);

        // 角色管理
        Route::apiResource('roles', RoleController::class);
        Route::put('roles/{role}/permissions', [RoleController::class, 'assignPermissions']);

        // 菜单管理
        Route::apiResource('menus', MenuController::class)->except(['show']);

        // 权限管理
        Route::apiResource('permissions', PermissionController::class)->except(['show']);

        // 数据字典
        Route::apiResource('dictionaries', DictionaryController::class)->except(['show', 'update']);
        Route::get('dictionaries/{dictionary}/items', [DictionaryController::class, 'items']);
        Route::post('dictionaries/{dictionary}/items', [DictionaryController::class, 'storeItem']);
        Route::put('dictionary-items/{item}', [DictionaryController::class, 'updateItem']);
        Route::delete('dictionary-items/{item}', [DictionaryController::class, 'destroyItem']);

        // 操作日志
        Route::get('operation-logs', [OperationLogController::class, 'index']);
    });

    // --- CRM 客户关系模块 ---
    Route::prefix('crm')->group(function () {
        // 渠道管理
        Route::apiResource('channels', ChannelController::class);

        // 线索管理
        Route::apiResource('leads', LeadController::class);
        Route::post('leads/{lead}/follow', [LeadController::class, 'follow']);
        Route::put('leads/{lead}/assign', [LeadController::class, 'assign']);

        // 客户管理
        Route::apiResource('customers', CustomerController::class);

        // 合同管理
        Route::apiResource('contracts', ContractController::class);
        Route::put('contracts/{contract}/audit', [ContractController::class, 'audit']);

        // 问卷管理
        Route::apiResource('questionnaires', QuestionnaireController::class);
        Route::post('questionnaire-answers', [QuestionnaireController::class, 'submitAnswer']);
        Route::get('questionnaire-answers', [QuestionnaireController::class, 'answers']);

        // 投诉管理
        Route::apiResource('complaints', ComplaintController::class);
        Route::put('complaints/{complaint}/handle', [ComplaintController::class, 'handle']);
    });

    // --- 房务管理模块 ---
    Route::prefix('room')->group(function () {
        // 房型管理
        Route::apiResource('room-types', RoomTypeController::class);

        // 房间管理
        Route::apiResource('rooms', RoomController::class);
        Route::put('rooms/{room}/status', [RoomController::class, 'updateStatus']);

        // 预定管理
        Route::apiResource('reservations', ReservationController::class);
        Route::put('reservations/{reservation}/check-in', [ReservationController::class, 'checkIn']);
        Route::put('reservations/{reservation}/check-out', [ReservationController::class, 'checkOut']);
        Route::put('reservations/{reservation}/cancel', [ReservationController::class, 'cancel']);

        // 外出记录
        Route::apiResource('customer-outings', CustomerOutingController::class)->only(['index', 'store', 'show']);
        Route::put('customer-outings/{customerOuting}/back', [CustomerOutingController::class, 'recordBack']);

        // 呼叫记录
        Route::get('call-records', [CallRecordController::class, 'index']);
        Route::post('call-records', [CallRecordController::class, 'store']);
        Route::put('call-records/{callRecord}/handle', [CallRecordController::class, 'handle']);
    });

    // --- 护理管理模块 ---
    Route::prefix('care')->group(function () {
        // 护理档案
        Route::apiResource('profiles', CareProfileController::class)->names('care.profiles');

        // 护理计划
        Route::apiResource('plans', CarePlanController::class)->names('care.plans');

        // 护理记录
        Route::apiResource('records', CareRecordController::class)->names('care.records');

        // 护理异常
        Route::apiResource('exceptions', CareExceptionController::class)->except(['destroy'])->names('care.exceptions');
        Route::put('exceptions/{careException}/handle', [CareExceptionController::class, 'handle']);

        // 健康指标
        Route::get('health-metrics', [HealthMetricController::class, 'index']);
        Route::post('health-metrics', [HealthMetricController::class, 'store']);
    });

    // --- 月子餐模块 ---
    Route::prefix('meal')->group(function () {
        // 菜品库
        Route::apiResource('dishes', DishController::class);

        // 排餐模板
        Route::apiResource('templates', MealPlanTemplateController::class);

        // 每日排餐
        Route::apiResource('daily-plans', DailyMealPlanController::class);
        Route::put('daily-plans/{dailyMealPlan}/deliver', [DailyMealPlanController::class, 'deliver']);
        Route::put('daily-plans/{dailyMealPlan}/status', [DailyMealPlanController::class, 'updateStatus']);

        // 膳食评价
        Route::get('reviews', [MealReviewController::class, 'index']);
        Route::post('reviews', [MealReviewController::class, 'store']);
    });

    // --- 服务产康模块 ---
    Route::prefix('service')->group(function () {
        // 服务项目
        Route::apiResource('items', ServiceItemController::class);

        // 服务套餐
        Route::apiResource('packages', ServicePackageController::class);

        // 服务订单
        Route::apiResource('orders', ServiceOrderController::class)->names('service.orders');
        Route::put('orders/{serviceOrder}/pay', [ServiceOrderController::class, 'pay']);
        Route::put('orders/{serviceOrder}/complete', [ServiceOrderController::class, 'complete']);

        // 服务执行
        Route::get('executions', [ServiceExecutionController::class, 'index']);
        Route::post('executions', [ServiceExecutionController::class, 'store']);
        Route::put('executions/{serviceExecution}/start', [ServiceExecutionController::class, 'start']);
        Route::put('executions/{serviceExecution}/finish', [ServiceExecutionController::class, 'finish']);
    });

    // --- 月嫂管理模块 ---
    Route::prefix('nanny')->group(function () {
        // 月嫂信息
        Route::apiResource('nannies', NannyController::class);

        // 月嫂订单
        Route::apiResource('orders', NannyOrderController::class)->names('nanny.orders');

        // 月嫂排班
        Route::get('schedules', [NannyScheduleController::class, 'index']);
        Route::post('schedules', [NannyScheduleController::class, 'store']);
    });

    // --- 进销存模块 ---
    Route::prefix('inventory')->group(function () {
        // 仓库管理
        Route::apiResource('warehouses', WarehouseController::class);

        // 供应商管理
        Route::apiResource('suppliers', SupplierController::class);

        // 物料管理
        Route::apiResource('materials', MaterialController::class);

        // 采购管理
        Route::apiResource('purchase-orders', PurchaseOrderController::class);
        Route::put('purchase-orders/{purchaseOrder}/audit', [PurchaseOrderController::class, 'audit']);

        // 出入库流水
        Route::get('stock-movements', [StockMovementController::class, 'index']);
        Route::post('stock-movements', [StockMovementController::class, 'store']);
        Route::get('stock-movements/{stockMovement}', [StockMovementController::class, 'show']);
        Route::put('stock-movements/{stockMovement}/confirm', [StockMovementController::class, 'confirm']);

        // 库存查询（按物料/仓库汇总）
        Route::get('inventories', [InventoryController::class, 'index']);

        // 库存台账
        Route::get('stock', [StockController::class, 'index']);
        Route::get('stock/export', [StockController::class, 'export']);

        // 调拨管理
        Route::get('transfers', [TransferOrderController::class, 'index']);
        Route::post('transfers', [TransferOrderController::class, 'store']);
        Route::get('transfers/{transferOrder}', [TransferOrderController::class, 'show']);
        Route::put('transfers/{transferOrder}/confirm', [TransferOrderController::class, 'confirm']);
        Route::put('transfers/{transferOrder}/cancel', [TransferOrderController::class, 'cancel']);

        // 盘点管理
        Route::get('checks', [InventoryCheckController::class, 'index']);
        Route::post('checks', [InventoryCheckController::class, 'store']);
        Route::get('checks/{inventoryCheck}', [InventoryCheckController::class, 'show']);
        Route::put('checks/{inventoryCheck}/complete', [InventoryCheckController::class, 'complete']);
    });

    // --- 财务管理模块 ---
    Route::prefix('finance')->group(function () {
        // 收支分类
        Route::apiResource('categories', FinanceCategoryController::class)->names('finance.categories');

        // 收支记录
        Route::apiResource('records', FinanceRecordController::class)->names('finance.records');
        Route::put('records/{financeRecord}/audit', [FinanceRecordController::class, 'audit']);

        // 客户账户
        Route::get('accounts', [CustomerAccountController::class, 'index']);
        Route::get('accounts/{customerAccount}', [CustomerAccountController::class, 'show']);
        Route::post('accounts/recharge', [CustomerAccountController::class, 'recharge']);

        // 账户流水
        Route::get('transactions', [AccountTransactionController::class, 'index']);

        // 储值卡
        Route::apiResource('prepaid-cards', PrepaidCardController::class);

        // 发票管理
        Route::apiResource('invoices', InvoiceController::class);
        Route::put('invoices/{invoice}/issue', [InvoiceController::class, 'issue']);
    });

    // --- 人事薪资模块 ---
    Route::prefix('hr')->group(function () {
        // 员工档案
        Route::apiResource('profiles', EmployeeProfileController::class)->names('hr.profiles');

        // 排班管理
        Route::get('schedules', [ScheduleController::class, 'index']);
        Route::post('schedules', [ScheduleController::class, 'store']);

        // 考勤管理
        Route::get('attendances', [AttendanceRecordController::class, 'index']);
        Route::post('attendances', [AttendanceRecordController::class, 'store']);
        Route::post('attendances/clock-in', [AttendanceRecordController::class, 'clockIn']);
        Route::post('attendances/clock-out', [AttendanceRecordController::class, 'clockOut']);

        // 请假管理
        Route::apiResource('leaves', LeaveRequestController::class);
        Route::put('leaves/{leaveRequest}/audit', [LeaveRequestController::class, 'audit']);

        // 工资管理
        Route::apiResource('salaries', SalaryRecordController::class);
        Route::put('salaries/{salaryRecord}/confirm', [SalaryRecordController::class, 'confirm']);
        Route::put('salaries/{salaryRecord}/pay', [SalaryRecordController::class, 'pay']);
    });

    // --- 办公协同模块 ---
    Route::prefix('office')->group(function () {
        // 审批模板
        Route::apiResource('approval-templates', ApprovalTemplateController::class);

        // 审批管理
        Route::apiResource('approvals', ApprovalController::class)->except(['update']);
        Route::put('approvals/{approval}/approve', [ApprovalController::class, 'approve']);
        Route::put('approvals/{approval}/reject', [ApprovalController::class, 'reject']);
        Route::put('approvals/{approval}/withdraw', [ApprovalController::class, 'withdraw']);

        // 公告管理
        Route::apiResource('announcements', AnnouncementController::class);
        Route::put('announcements/{announcement}/publish', [AnnouncementController::class, 'publish']);

        // 交接班
        Route::get('handovers', [HandoverController::class, 'index']);
        Route::post('handovers', [HandoverController::class, 'store']);
        Route::get('handovers/{handover}', [HandoverController::class, 'show']);
        Route::put('handovers/{handover}/confirm', [HandoverController::class, 'confirm']);

        // 消息通知
        Route::get('notifications', [NotificationController::class, 'index']);
        Route::put('notifications/{notification}/read', [NotificationController::class, 'markRead']);
        Route::put('notifications/read-all', [NotificationController::class, 'markAllRead']);
    });

    // --- 统计报表模块 ---
    Route::prefix('report')->group(function () {
        // 聚合报表
        Route::get('overview', [ReportController::class, 'overview']);
        Route::get('revenue', [ReportController::class, 'revenue']);
        Route::get('occupancy', [ReportController::class, 'occupancy']);
        Route::get('crm-conversion', [ReportController::class, 'crmConversion']);

        // 导出记录
        Route::get('exports', [ReportExportController::class, 'index']);
        Route::post('exports', [ReportExportController::class, 'store']);
    });

    // --- 知识库模块 ---
    Route::prefix('kb')->group(function () {
        // 知识分类
        Route::apiResource('categories', KbCategoryController::class)->names('kb.categories');

        // 知识文章
        Route::apiResource('articles', KbArticleController::class);
        Route::put('articles/{kbArticle}/publish', [KbArticleController::class, 'publish']);
        Route::put('articles/{kbArticle}/offline', [KbArticleController::class, 'offline']);
    });
});
