<?php
/**
 * 问诊有道健康管理SaaS - 入口文件 & 路由分发
 */

// 加载配置和核心类
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/response.php';
require_once __DIR__ . '/includes/helpers.php';

// 设置CORS
foreach (CORS_ORIGINS as $origin) {
    if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] === $origin) {
        header("Access-Control-Allow-Origin: $origin");
        break;
    }
}
header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

// OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// ========== 路由解析 ==========

$uri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($uri, PHP_URL_PATH);

// 去掉 /health/ 前缀，得到相对路径
$path = preg_replace('#^/health/#', '', $path);
$path = trim($path, '/');

// API路由
if (strpos($path, 'api/') === 0) {
    $apiPath = substr($path, 4); // 去掉 'api/'
    routeApi($apiPath);
    exit;
}

// 页面路由
routePage($path);

/**
 * API路由分发
 */
function routeApi($apiPath) {
    $method = $_SERVER['REQUEST_METHOD'];
    $parts = explode('/', trim($apiPath, '/'));
    $module = $parts[0] ?? '';
    $action = $parts[1] ?? '';
    $id = $parts[2] ?? null;
    $extra = $parts[3] ?? null;
    
    // 将action注入GET参数，供getParam()读取（不覆盖query string中已有的action）
    if ($action && !isset($_GET['action'])) {
        $_GET['action'] = $action;
    } elseif (!$action && isset($_GET['action'])) {
        $action = $_GET['action'];
    }
    if ($id && !isset($_GET['id'])) $_GET['id'] = $id;
    if ($extra && !isset($_GET['extra'])) $_GET['extra'] = $extra;

    switch ($module) {
        case 'auth':
            require_once __DIR__ . '/api/auth.php';
            switch ($action) {
                case 'login':
                    handleLogin();
                    break;
                case 'register':
                    handleRegister();
                    break;
                case 'me':
                    handleMe();
                    break;
                case 'logout':
                    handleLogout();
                    break;
                default:
                    Response::error('未知接口', 404);
            }
            break;

        case 'orgs':
            require_once __DIR__ . '/api/orgs.php';
            if ($action && is_numeric($action)) {
                // /api/orgs/{id}
                handleOrgDetail(intval($action));
            } else {
                handleOrgs();
            }
            break;

        case 'packages':
            require_once __DIR__ . '/api/packages.php';
            if ($action && is_numeric($action)) {
                handlePackageDetail(intval($action));
            } else {
                handlePackages();
            }
            break;

        case 'contracts':
            require_once __DIR__ . '/api/contracts.php';
            if ($action && is_numeric($action)) {
                handleContractDetail(intval($action));
            } else {
                handleContracts();
            }
            break;

        case 'profiles':
            require_once __DIR__ . '/api/profiles.php';
            if ($action && is_numeric($action)) {
                getProfile(intval($action));
            } else {
                handleProfiles();
            }
            break;

        case 'records':
            require_once __DIR__ . '/api/records.php';
            if ($action === 'trend') {
                handleRecordsTrend();
            } else {
                handleRecords();
            }
            break;

        case 'followups':
            require_once __DIR__ . '/api/followups.php';
            if ($action && is_numeric($action)) {
                getFollowup(intval($action));
            } else {
                handleFollowups();
            }
            break;

        case 'reports':
            require_once __DIR__ . '/api/reports.php';
            if ($action && is_numeric($action)) {
                handleHealthReport(intval($action));
            } else {
                Response::error('请指定用户ID', 400);
            }
            break;

        case 'health_plan':
            require_once __DIR__ . '/api/portal.php';  // 需要parseRecordData等函数
            require_once __DIR__ . '/api/health_plan.php';
            handleHealthPlan();
            break;

        case 'portal':
            require_once __DIR__ . '/api/portal.php';
            handlePortal();
            break;

        // ========== Phase 5 Week 3 ==========
        case 'onboarding':
            require_once __DIR__ . '/api/onboarding.php';
            handleOnboarding();
            break;
        case 'discounts':
            require_once __DIR__ . '/api/discounts.php';
            handleDiscounts();
            break;
        case 'general_plan':
            require_once __DIR__ . '/api/general_plan.php';
            handleGeneralPlan();
            break;
        case 'my_services':
            require_once __DIR__ . '/api/my_services.php';
            handleMyServices();
            break;

        case 'dashboard':
            require_once __DIR__ . '/api/dashboard.php';
            handleDashboard();
            break;

        // ========== Phase 1 新增路由 ==========

        case 'lifestyle_plans':
            require_once __DIR__ . '/api/lifestyle_plans.php';
            handleLifestylePlans();
            break;

        case 'lifestyle_checkin':
            require_once __DIR__ . '/api/lifestyle_checkin.php';
            handleLifestyleCheckin();
            break;

        case 'wallet':
            require_once __DIR__ . '/api/wallet.php';
            handleWallet();
            break;

        case 'invite':
            require_once __DIR__ . '/api/invite.php';
            handleInvite();
            break;

        case 'health_snapshots':
            require_once __DIR__ . '/api/health_snapshots.php';
            handleHealthSnapshots();
            break;

        case 'activities':
            require_once __DIR__ . '/api/activities.php';
            handleActivities();
            break;

        // ========== Phase 2 新增路由 ==========

        case 'partners':
            require_once __DIR__ . '/api/partners.php';
            handlePartners();
            break;

        case 'referrals':
            require_once __DIR__ . '/api/referrals.php';
            handleReferrals();
            break;

        case 'crm':
            require_once __DIR__ . '/api/crm.php';
            handleCrm();
            break;

        case 'work':
            require_once __DIR__ . '/api/work.php';
            handleWork();
            break;

        // ========== Phase 3 新增路由 ==========

        case 'weekly_report':
            require_once __DIR__ . '/api/weekly_report.php';
            handleWeeklyReport();
            break;

        case 'doctor_dashboard':
            require_once __DIR__ . '/api/doctor_dashboard.php';
            // 支持 /api/doctor_dashboard/patients 和 /api/doctor_dashboard/patient/{id}
            if ($action === 'patient' && $id) {
                getPatientDetail(intval($id));
            } else {
                handleDoctorDashboard();
            }
            break;

        // ========== Phase 4 新增路由 ==========

        case 'rbac':
            require_once __DIR__ . '/api/rbac.php';
            handleRbac();
            break;

        case 'doctors':
            require_once __DIR__ . '/api/doctors.php';
            handleDoctors();
            break;

        case 'departments':
            require_once __DIR__ . '/api/departments.php';
            handleDepartments();
            break;

        case 'settings':
            require_once __DIR__ . '/api/settings.php';
            handleSettings();
            break;

        // ========== Phase 4 Week 2 新增路由 ==========

        case 'quality':
            require_once __DIR__ . '/api/quality.php';
            handleQuality();
            break;

        case 'consultations':
            require_once __DIR__ . '/api/consultations.php';
            handleConsultations();
            break;

        case 'verification':
            require_once __DIR__ . '/api/verification.php';
            handleVerification();
            break;

        case 'service_usage':
            require_once __DIR__ . '/api/service_usage.php';
            handleServiceUsage();
            break;

        // ========== 社区化管理 & 派单 ==========
        case 'communities':
            require_once __DIR__ . '/api/communities.php';
            handleCommunities();
            break;

        // ========== Phase 6A 数据闭环 ==========
        case 'alerts':
            require_once __DIR__ . '/api/alerts.php';
            handleAlerts();
            break;

        case 'reminders':
            require_once __DIR__ . '/api/reminders.php';
            handleReminders();
            break;

        case 'documents':
            require_once __DIR__ . '/api/documents.php';
            handleDocuments();
            break;

        // ========== Phase 7 慢病深水区 ==========
        case 'disease_mgmt':
            require_once __DIR__ . '/api/disease_mgmt.php';
            handleDiseaseMgmt();
            break;

        case 'medication_adherence':
            require_once __DIR__ . '/api/medication_adherence.php';
            handleMedicationAdherence();
            break;

        case 'lab_screening':
            require_once __DIR__ . '/api/lab_screening.php';
            handleLabScreening();
            break;

        case 'chronic_engine':
            require_once __DIR__ . '/api/chronic_engine.php';
            if ($action === 'cron') handleChronicCron();
            else getChronicDashboard();
            break;

        case 'health_analytics':
            require_once __DIR__ . '/api/health_analytics.php';
            handleHealthAnalytics();
            break;

        case 'disease_hub':
            require_once __DIR__ . '/api/disease_hub.php';
            handleDiseaseHub();
            break;



        case 'doctor_signing':
            require_once __DIR__ . '/api/doctor_signing.php';
            handleDoctorSigning();
            break;

        // ========== Phase 9 医护管理 ==========
        case 'staff_management':
            require_once __DIR__ . '/api/staff_management.php';
            handleStaffManagement();
            break;

        case "survey":
            require_once __DIR__ . "/api/survey.php";
            handleSurvey();
            break;

        case "risk":
            require_once __DIR__ . "/api/risk_engine.php";
            handleRiskEngine();
            break;

        case 'admin':
            require_once __DIR__ . '/api/admin.php';
            handleAdmin();
            break;

        // ========== 重要异常结果闭环 & 体检报告引擎 ==========
        case 'critical':
            require_once __DIR__ . '/api/critical_results.php';
            handleCriticalResults();
            break;

        case 'report':
            require_once __DIR__ . '/api/exam_report.php';
            handleExamReport();
            break;

        // ========== 药店工作台 ==========
        case 'pharmacy':
            require_once __DIR__ . '/api/pharmacy.php';
            handlePharmacy();
            break;

        // ========== 养老机构管理 ==========
        case 'institution':
            require_once __DIR__ . '/api/institution.php';
            handleInstitution();
            break;

        case 'institution_review':
            require_once __DIR__ . '/api/institution_review.php';
            handleInstitutionReview();
            break;

        case 'institution_agent':
            require_once __DIR__ . '/api/institution_agent.php';
            break;


        // ========== Channel Cooperation ==========
        case 'channellead':
            require_once __DIR__ . '/api/lead.php';
            handleLead();
            break;

        case 'agent_dashboard':
            require_once __DIR__ . '/api/agent_dashboard.php';
            break;

        // ========== Agent (Tenant) Routes ==========
        case 'agent':
            require_once __DIR__ . '/api/agent_register.php';
            break;

        case 'agent_admin':
            require_once __DIR__ . '/api/agent_admin.php';
            break;

        // ========== 代理入驻在线支付（Native扫码 + 自动开通） ==========
        case 'agent_pay':
            require_once __DIR__ . '/api/agent_pay.php';
            break;

        // ========== 多租户平台 API ==========
        case 'tenant_portal':
            require_once __DIR__ . '/api/tenant_portal.php';
            break;
        case 'my_tenant':
            require_once __DIR__ . '/api/my_tenant.php';
            break;

        case 'agent_qrcode':
            require_once __DIR__ . '/api/agent_qrcode.php';
            break;

        case 'admin_services':
            require_once __DIR__ . '/api/admin_services.php';
            handleAdminServices();
            break;
        case 'admin_service_orders':
            require_once __DIR__ . '/api/admin_service_orders.php';
            break;

        case 'admin_payments':
            require_once __DIR__ . '/api/admin_payments.php';
            break;

        // ========== 患者用户中心（C端） ==========
        case 'patient_center':
            require_once __DIR__ . '/api/patient_center.php';
            break;

        case 'channel':
            require_once __DIR__ . '/api/channel.php';
            handleChannel();
            break;

        // ========== 健康资讯（渠道 H5 共享内容池） ==========
        // ========== 微信支付V3 ==========
        case 'wechat_auth':
            require_once __DIR__ . '/api/wechat_auth.php';
            handleWechatAuth();
            break;
        case 'wechat_pay':
            require_once __DIR__ . '/api/wechat_pay.php';
            handleWechatPay();
            break;
        case 'articles':
            require_once __DIR__ . '/api/articles.php';
            handleArticles();
            break;

        case 'mp_pay':
            require_once __DIR__ . '/api/mp_pay.php';
            mp_pay_handle();
            break;
        case 'mp_auth':
            require_once __DIR__ . '/api/mp_auth.php';
            mp_auth_handle();
            break;
        // ========== 分佣规则配置 ==========
        case 'commission_rules':
            require_once __DIR__ . '/api/commission_rules.php';
            handleCommissionRules();
            break;

        // ========== 服务交付跟踪 ==========
        case 'service_delivery':
            require_once __DIR__ . '/api/service_delivery.php';
            handleServiceDelivery();
            break;

        case 'mp_qrcode':
            require_once __DIR__ . '/api/mp_qrcode.php';
            break;
        default:
            Response::error('接口不存在', 404);
    }
}

/**
 * 页面路由
 */
function routePage($path) {
    // 默认首页 → 官方主页
    if ($path === '') {
        include __DIR__ . '/templates/home.php';
        return;
    }
    // 兼容旧 index 路径
    if ($path === 'index') {
        $templateFile = __DIR__ . '/templates/index.php';
        if (file_exists($templateFile)) {
            include $templateFile;
        } else {
            echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>' . APP_NAME . '</title></head><body>';
            echo '<h1>' . APP_NAME . '</h1>';
            echo '<p>系统已部署，API服务正常运行。</p>';
            echo '<p>版本: ' . APP_VERSION . '</p>';
            echo '</body></html>';
        }
        return;
    }

    // 处理 /portal/ 前缀 → 映射到 templates/ 目录
    if (strpos($path, 'portal/') === 0) {
        $path = substr($path, 7); // 去掉 'portal/'
    }

    // 页面别名：短横线 URL 映射到下划线模板
    $pageAliases = [
        'my-services' => 'my_services',
    ];
    if (isset($pageAliases[$path])) {
        $path = $pageAliases[$path];
    }

    // 尝试加载模板文件
    $templateFile = __DIR__ . '/templates/' . str_replace(['..', '\\'], '', $path) . '.php';
    if (file_exists($templateFile)) {
        include $templateFile;
        return;
    }

    // HTML文件
    $htmlFile = __DIR__ . '/templates/' . str_replace(['..', '\\'], '', $path) . '.html';
    if (file_exists($htmlFile)) {
        readfile($htmlFile);
        return;
    }


    // ========== Channel Routes ==========
    // Channel H5 branded page: /health/c/{code}
    if (preg_match('#^c/([A-Za-z0-9]+)/poster$#', $path, $m)) {
        require_once __DIR__ . '/templates/channel_poster.php';
        return;
    }
    if (preg_match('#^c/([A-Za-z0-9]+)$#', $path, $m)) {
        require_once __DIR__ . '/includes/channel.php';
        // Set channel cookie
        $chCode = $m[1];
        $code = $chCode; // h5 模板统一使用 $code
        setChannelCookies($chCode);
        recordChannelVisit($chCode);
        require_once __DIR__ . '/templates/channel_h5.php';
        return;
    }
    // 渠道身份的文章详情：/health/c/{code}/a/{id}（保持渠道 cookie 归属）
    if (preg_match('#^c/([A-Za-z0-9]+)/a/([0-9]+)$#', $path, $m)) {
        require_once __DIR__ . '/includes/channel.php';
        $code = $m[1];
        $articleId = intval($m[2]);
        require_once __DIR__ . '/templates/channel_article.php';
        return;
    }
    // 平台通用文章链接：/health/a/{id}（无渠道身份，不显示门店信息条）
    if (preg_match('#^a/([0-9]+)$#', $path, $m)) {
        require_once __DIR__ . '/includes/channel.php';
        $code = '';
        $articleId = intval($m[1]);
        require_once __DIR__ . '/templates/channel_article.php';
        return;
    }
    // Channel self-service manage page: /health/channel/manage
    if ($path === 'channel/manage') {
        require_once __DIR__ . '/templates/channel_manage.php';
        return;
    }
    // Partner application page: /health/partner
    if ($path === 'partner') {
        require_once __DIR__ . '/templates/channel_partner.php';
        return;
    }
    // Admin channels page: /health/admin/channels
    if ($path === 'admin/channels') {
        require_once __DIR__ . '/templates/channel_admin.php';
        return;
    }

    // Agent demo page: /health/demo
    if ($path === 'demo') {
        require_once __DIR__ . '/templates/agent_demo.php';
        return;
    }

    // Agent agreement page: /health/agreement
    if ($path === 'agreement') {
        require_once __DIR__ . '/templates/agent_agreement.php';
        return;
    }
    // Agent join page: /health/join
    if ($path === 'join') {
        require_once __DIR__ . '/templates/agent_join.php';
        return;
    }
    // Agent 微信绑定页（OAuth 回调落地）: /health/agent_bindwx
    if ($path === 'agent_bindwx') {
        require_once __DIR__ . '/templates/agent_bindwx.html';
        return;
    }

    // Admin agents page: /health/admin/agents
    if ($path === 'admin/agents') {
        require_once __DIR__ . '/templates/admin_agents.php';
        return;
    }

    // Admin service orders page: /health/admin/service-orders
    if ($path === 'admin/service-orders') {
        require_once __DIR__ . '/templates/admin_service_orders.php';
        return;
    }

    // Admin payments page: /health/admin/payments
    if ($path === 'admin/payments') {
        require_once __DIR__ . '/templates/admin_payments.php';
        return;
    }

    // Admin discounts page: /health/admin/discounts
    if ($path === 'admin/discounts') {
        require_once __DIR__ . '/templates/admin_discounts.php';
        return;
    }

    // Admin services page: /health/admin/services
    if ($path === 'admin/services') {
        require_once __DIR__ . '/templates/admin_services.php';
        return;
    }

    // Admin commission rules page: /health/admin/commission-rules
    if ($path === 'admin/commission-rules') {
        require_once __DIR__ . '/templates/admin_commission_rules.php';
        return;
    }

    // Admin service delivery page: /health/admin/service-delivery
    if ($path === 'admin/service-delivery') {
        require_once __DIR__ . '/templates/admin_service_delivery.php';
        return;
    }


    // 养老机构管理后台: /health/institution/admin
    if ($path === 'institution/admin') {
        require_once __DIR__ . '/templates/institution_admin.php';
        return;
    }
    // 患者用户中心: /health/my
    if ($path === 'my') {
        require_once __DIR__ . '/templates/patient_center.php';
        return;
    }

    // Agent dashboard: /health/agent
    if ($path === 'agent' || strpos($path, 'agent/') === 0) {
        require_once __DIR__ . '/templates/agent_dashboard.php';
        return;
    }

    // 404
    http_response_code(404);
    echo '<h1>404 - 页面未找到</h1>';
}
