<?php
/**
 * TechStackBase – Subscribe
 * Version: v1.0.0
 * Purpose: Initiate subscription purchase workflow
 *
 * Flow:
 * - Authenticated user requests subscription
 * - Server validates plan & company state
 * - Redirects into PayFast init (authoritative)
 *
 * Security:
 * - Auth required
 * - Permission enforced (billing:write)
 * - Duplicate active subscriptions blocked
 * - Server-authoritative pricing
 * - Audit logged
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/response.php';
require_once __DIR__ . '/../../core/AuthMiddleware.php';
require_once __DIR__ . '/../../core/PermissionMiddleware.php';
require_once __DIR__ . '/../../core/AuditLogger.php';
require_once __DIR__ . '/../system/guard.php';
require_once __DIR__ . '/../system/permissions.php';

requirePermission('users.view');
requireAuth();

/* ============================================================
   AUTHENTICATION
   ============================================================ */

$user = requireAuth();
$db   = Database::connect();

/* ============================================================
   PERMISSION CHECK
   ============================================================ */

requirePermission(
    'billing',
    'write',
    $user['role'],
    $user['user_id'],
    $user['company_id']
);

/* ============================================================
   INPUT
   ============================================================ */

$input = json_decode(file_get_contents('php://input'), true);
$planCode = trim($input['plan_code'] ?? '');

if (!$planCode) {
    validationError('plan_code is required');
}

/* ============================================================
   CHECK FOR ACTIVE SUBSCRIPTION
   ============================================================ */

$stmt = $db->prepare(
    "SELECT id
     FROM company_subscriptions
     WHERE company_id = ?
       AND status = 'active'
       AND expires_at > NOW()
     LIMIT 1"
);

$stmt->execute([$user['company_id']]);

if ($stmt->fetch()) {
    conflict('Company already has an active subscription');
}

/* ============================================================
   VALIDATE PLAN (READ-ONLY)
   ============================================================ */

$stmt = $db->prepare(
    "SELECT code, active
     FROM subscription_plans
     WHERE code = ?
     LIMIT 1"
);

$stmt->execute([$planCode]);
$plan = $stmt->fetch();

if (!$plan || (int)$plan['active'] !== 1) {
    notFound('Subscription plan not available');
}

/* ============================================================
   AUDIT LOG (INTENT)
   ============================================================ */

auditLog(
    $user['user_id'],
    $user['company_id'],
    'billing',
    'subscription_initiated',
    [
        'plan_code' => $planCode
    ]
);

/* ============================================================
   DELEGATE TO PAYFAST INIT
   ============================================================ */

/**
 * IMPORTANT:
 * This endpoint does NOT create payments directly.
 * It forwards intent to payfast_init.php
 */

require_once __DIR__ . '/payfast_init.php';

/* payfast_init.php exits with JSON response */
