<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| TechStackBase – Admin Module Subscriptions
|--------------------------------------------------------------------------
| Purpose:
| - Assign / list / disable modules per company
| - NO billing
| - NO plans
|
| Methods:
| - GET    ?company_id=ID
| - POST   { company_id, module_id }
| - DELETE { id }
*/

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';

header('Content-Type: application/json');

try {

    /* =========================
       AUTH
       ========================= */
    $actor = require_auth($pdo);
    $role  = $actor['role_key'];

    if (!in_array($role, ['super_admin', 'platform_admin', 'rsp_admin', 'company_admin'], true)) {
        error_forbidden('Forbidden');
    }

    $method = $_SERVER['REQUEST_METHOD'];

    /* ======================================================
       GET — LIST MODULES FOR COMPANY
       ====================================================== */
    if ($method === 'GET') {

        $companyId = (int)($_GET['company_id'] ?? 0);
        if ($companyId <= 0) {
            error_bad_request('company_id is required');
        }

        // Company admin → own company only
        if ($role === 'company_admin' && (int)$actor['company_id'] !== $companyId) {
            error_forbidden('Forbidden');
        }

        // RSP admin → companies under their RSP
        if ($role === 'rsp_admin') {
            $stmt = $pdo->prepare("
                SELECT id
                FROM companies
                WHERE id = ?
                  AND rsp_id = ?
                  AND deleted_at IS NULL
                LIMIT 1
            ");
            $stmt->execute([$companyId, (int)$actor['company_id']]);
            if (!$stmt->fetch()) {
                error_forbidden('Forbidden');
            }
        }

        $stmt = $pdo->prepare("
            SELECT
                cm.id,
                m.name AS module_name,
                cm.status,
                cm.activated_at AS start_date,
                cm.deactivated_at AS end_date
            FROM company_modules cm
            JOIN modules m ON m.id = cm.module_id
            WHERE cm.company_id = ?
            ORDER BY m.name
        ");
        $stmt->execute([$companyId]);

        success('Subscriptions loaded', [
            'subscriptions' => $stmt->fetchAll(PDO::FETCH_ASSOC)
        ]);
    }

    /* ======================================================
       POST — ASSIGN MODULE
       ====================================================== */
    if ($method === 'POST') {

        $input = json_decode(file_get_contents('php://input'), true);
        if (!is_array($input)) {
            error_bad_request('Invalid JSON');
        }

        $companyId = (int)($input['company_id'] ?? 0);
        $moduleId  = (int)($input['module_id'] ?? 0);

        if ($companyId <= 0 || $moduleId <= 0) {
            error_bad_request('company_id and module_id required');
        }

        if ($role === 'company_admin' && (int)$actor['company_id'] !== $companyId) {
            error_forbidden('Forbidden');
        }

        /* =========================
          CHECK EXISTING ASSIGNMENT
        ========================= */
    $stmt = $pdo->prepare("
        SELECT id, status
        FROM company_modules
        WHERE company_id = ?
          AND module_id = ?
        LIMIT 1
    ");
    $stmt->execute([$companyId, $moduleId]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing) {

    // Already active → conflict
    if ($existing['status'] === 'active') {
        error_conflict('Module already assigned');
    }

    // Reactivate disabled module
    $pdo->prepare("
        UPDATE company_modules
        SET status = 'active',
            activated_at = NOW(),
            deactivated_at = NULL
        WHERE id = ?
    ")->execute([(int)$existing['id']]);

    try {
        auditLog(
            (int)$actor['id'],
            (int)$companyId,
            'subscriptions',
            'module_reactivated',
            ['module_id' => $moduleId]
        );
    } catch (Throwable $e) {
        error_log('SUBSCRIPTIONS AUDIT FAILED: ' . $e->getMessage());
    }

    json_response([
        'status'  => 'success',
        'message' => 'Module reactivated'
    ]);
    exit;
}

        $stmt = $pdo->prepare("
            INSERT INTO company_modules (
                company_id,
                module_id,
                status,
                activated_at
            ) VALUES (
                :company_id,
                :module_id,
                'active',
                NOW()
            )
        ");
        $stmt->execute([
            'company_id' => $companyId,
            'module_id'  => $moduleId
        ]);

        // 🔒 Audit must NEVER break response
        try {
            auditLog(
                (int)$actor['id'],
                (int)$companyId,
                'subscriptions',
                'module_assigned',
                ['module_id' => $moduleId]
            );
        } catch (Throwable $e) {
            error_log('SUBSCRIPTIONS AUDIT FAILED: ' . $e->getMessage());
        }

        json_response([
            'status'  => 'success',
            'message' => 'Module assigned'
        ]);
        exit;
    }

    /* ======================================================
       DELETE — DISABLE MODULE
       ====================================================== */
    if ($method === 'DELETE') {

        $input = json_decode(file_get_contents('php://input'), true);
        $id = (int)($input['id'] ?? 0);

        if ($id <= 0) {
            error_bad_request('id required');
        }

        $stmt = $pdo->prepare("
            SELECT id, company_id, module_id
            FROM company_modules
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            error_not_found('Subscription not found');
        }

        if ($role === 'company_admin' && (int)$actor['company_id'] !== (int)$row['company_id']) {
            error_forbidden('Forbidden');
        }

        $pdo->prepare("
            UPDATE company_modules
            SET status = 'disabled',
                deactivated_at = NOW()
            WHERE id = ?
        ")->execute([$id]);

        try {
            auditLog(
                (int)$actor['id'],
                (int)$row['company_id'],
                'subscriptions',
                'module_disabled',
                ['module_id' => (int)$row['module_id']]
            );
        } catch (Throwable $e) {
            error_log('SUBSCRIPTIONS AUDIT FAILED: ' . $e->getMessage());
        }

        json_response([
            'status'  => 'success',
            'message' => 'Module disabled'
        ]);
        exit;
    }

    error_bad_request('Unsupported method');

} catch (Throwable $e) {
    error_log('SUBSCRIPTIONS ADMIN ERROR: ' . $e->getMessage());
    error_server('Subscription operation failed');
}
