<?php
/**
 * Application Bootstrap
 * Initializes all dependencies
 */

use App\Database\Connection;
use App\Database\Migration;
use App\Repositories\ConfigRepository;
use App\Repositories\UserRepository;
use App\Repositories\PersonRepository;
use App\Repositories\DealRepository;
use App\Repositories\ActivityRepository;
use App\Repositories\VirtualStageRepository;
use App\Repositories\SatisfactionRepository;
use App\Repositories\NotificationRepository;
use App\Repositories\ActivityReminderRepository;
use App\Repositories\ProductRepository;
use App\Repositories\AuditLogRepository;
use App\Repositories\LookupRepository;
use App\Repositories\FieldConfigRepository;
use App\Repositories\FieldAuditLogRepository;
use App\Repositories\KpiRepository;
use App\Repositories\SupportRepository;
use App\Repositories\RbacRepository;
use App\Repositories\CommissionRuleRepository;
use App\Repositories\CommissionLedgerRepository;
use App\Repositories\DealCommissionRepository;
use App\Repositories\CommissionPayoutCycleRepository;
use App\Repositories\DealPaymentRepository;
use App\Repositories\FinanceApprovalRepository;
use App\Services\DidarApiService;
use App\Services\AuthService;
use App\Services\AuditService;
use App\Services\VirtualStageService;
use App\Services\SyncService;
use App\Services\LeadService;
use App\Services\DealService;
use App\Services\ActivityService;
use App\Services\PipelineService;
use App\Services\NotificationService;
use App\Services\ExportService;
use App\Services\FieldPermissionService;
use App\Services\KpiService;
use App\Services\KpiCacheService;
use App\Services\SupportService;
use App\Services\RbacService;
use App\Services\CommissionService;
use App\Services\PayrollIntegrationService;
use App\Middleware\AuthMiddleware;
use App\Middleware\RoleMiddleware;

// Initialize database
$db = Connection::getInstance();
$bootstrapConfigRepo = new ConfigRepository($db);

// Run migrations (CLI + setup endpoints by default; disabled for normal web requests for performance)
$migrationAction = $_GET['api'] ?? '';
$autoMigrationSetting = $bootstrapConfigRepo->getValue('auto_migration_enabled', '0');
$shouldRunMigrations = (php_sapi_name() === 'cli')
    || strpos((string)$migrationAction, 'setup_') === 0
    || ($autoMigrationSetting === '1');
if ($shouldRunMigrations) {
    $migration = new Migration($db);
    $migration->run();
}

// Initialize repositories
$configRepo = $bootstrapConfigRepo;
$userRepo = new UserRepository($db);
$personRepo = new PersonRepository($db);
$dealRepo = new DealRepository($db);
$activityRepo = new ActivityRepository($db);
$virtualStageRepo = new VirtualStageRepository($db);
$satisfactionRepo = new SatisfactionRepository($db);
$notificationRepo = new NotificationRepository($db);
$activityReminderRepo = new ActivityReminderRepository($db);
$productRepo = new ProductRepository($db);
$auditLogRepo = new AuditLogRepository($db);
$lookupRepo = new LookupRepository($db);
$fieldConfigRepo = new FieldConfigRepository($db);
$fieldAuditLogRepo = new FieldAuditLogRepository($db);
$kpiRepo = new KpiRepository($db);
$supportRepo = new SupportRepository($db);
$rbacRepo = new RbacRepository($db);
$commissionRuleRepo = new CommissionRuleRepository($db);
$commissionLedgerRepo = new CommissionLedgerRepository($db);
$dealCommissionRepo = new DealCommissionRepository($db);
$commissionPayoutCycleRepo = new CommissionPayoutCycleRepository($db);
$dealPaymentRepo = new DealPaymentRepository($db);
$financeApprovalRepo = new FinanceApprovalRepository($db);

// Initialize services
$didarApiService = new DidarApiService($configRepo);
$authService = new AuthService($userRepo, $configRepo);
$virtualStageService = new VirtualStageService($virtualStageRepo, $activityRepo, $dealRepo, $personRepo);
$notificationService = new NotificationService($notificationRepo, $activityReminderRepo);
$auditService = new AuditService($auditLogRepo, $fieldAuditLogRepo);
$syncService = new SyncService($didarApiService, $userRepo, $personRepo, $dealRepo, $activityRepo, $configRepo, $virtualStageService, $db);
$commissionService = new CommissionService($commissionRuleRepo, $commissionLedgerRepo);
$payrollIntegrationService = new PayrollIntegrationService($commissionPayoutCycleRepo, $userRepo);
$leadService = new LeadService($personRepo, $virtualStageRepo, $dealRepo, $virtualStageService, $didarApiService, $configRepo, $notificationService, null, $commissionService);
$dealService = new DealService($dealRepo, $personRepo, $didarApiService, $productRepo, $db, $lookupRepo, $auditService, $commissionService);
$activityService = new ActivityService($activityRepo, $personRepo, $didarApiService, $configRepo, $virtualStageService, $notificationService);
$pipelineService = new PipelineService($didarApiService, $configRepo, $db);
$exportService = new ExportService($db);
$fieldPermService = new FieldPermissionService($fieldConfigRepo, $lookupRepo);
$kpiCacheService = new KpiCacheService();
$kpiService = new KpiService($kpiRepo, $userRepo, $kpiCacheService);
$supportService = new SupportService($supportRepo);
$rbacService = new RbacService($rbacRepo);

// Initialize middleware
$authMiddleware = new AuthMiddleware($authService);
$roleMiddleware = new RoleMiddleware($authService);

// Return container-like object
return (object)[
    'db' => $db,
    'repositories' => (object)[
        'config' => $configRepo,
        'user' => $userRepo,
        'person' => $personRepo,
        'deal' => $dealRepo,
        'activity' => $activityRepo,
        'virtualStage' => $virtualStageRepo,
        'satisfaction' => $satisfactionRepo,
        'notification' => $notificationRepo,
        'activityReminder' => $activityReminderRepo,
        'product' => $productRepo,
        'auditLog' => $auditLogRepo,
        'lookup' => $lookupRepo,
        'fieldConfig' => $fieldConfigRepo,
        'fieldAuditLog' => $fieldAuditLogRepo,
        'kpi' => $kpiRepo,
        'support' => $supportRepo,
        'rbac' => $rbacRepo,
        'commissionRule' => $commissionRuleRepo,
        'commissionLedger' => $commissionLedgerRepo,
        'dealCommission' => $dealCommissionRepo,
        'commissionPayoutCycle' => $commissionPayoutCycleRepo,
        'dealPayment' => $dealPaymentRepo,
        'financeApproval' => $financeApprovalRepo,
    ],
    'services' => (object)[
        'didarApi' => $didarApiService,
        'auth' => $authService,
        'virtualStage' => $virtualStageService,
        'sync' => $syncService,
        'lead' => $leadService,
        'deal' => $dealService,
        'activity' => $activityService,
        'pipeline' => $pipelineService,
        'notification' => $notificationService,
        'audit' => $auditService,
        'export' => $exportService,
        'fieldPermission' => $fieldPermService,
        'kpi' => $kpiService,
        'kpiCache' => $kpiCacheService,
        'support' => $supportService,
        'rbac' => $rbacService,
        'commission' => $commissionService,
        'payrollIntegration' => $payrollIntegrationService,
    ],
    'middleware' => (object)[
        'auth' => $authMiddleware,
        'role' => $roleMiddleware,
    ],
];
