<?php
/**
 * TechStackBase – PayFast Init
 * Version: v1.0.0
 * Purpose: Securely initiate PayFast payment for subscription
 *
 * Security:
 * - Server-authoritative pricing
 * - Subscription-safe (no duplicate active plans)
 * - PayFast signature correct (RFC3986)
 * - Audit logged
 * - Android & Web compatible
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/response.php';
require_once __DIR__ . '/../../config/payfast.php';
require_once __DIR__ . '/../../core/AuthMiddleware.php';
require_once __DIR__ . '/../../core/SubscriptionMiddleware.php';
require_once __DIR__ . '/../../core/PermissionMiddleware.php';
require_once __DIR__ . '/../../core/AuditLogger.php';

/* ============================================================
   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');
}

/* ============================================================
   PREVENT DUPLICATE 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');
}

/* ============================================================
   LOAD PLAN (SERVER AUTHORITATIVE)
   ============================================================ */

$stmt = $db->prepare(
    "SELECT code, name, price, billing_cycle
     FROM subscription_plans
     WHERE code = ?
     AND active = 1
     LIMIT 1"
);
$stmt->execute([$planCode]);
$plan = $stmt->fetch();

if (!$plan) {
    notFound('Subscription plan not found');
}

/* ============================================================
   CREATE PENDING SUBSCRIPTION
   ============================================================ */

$db->beginTransaction();

try {

    /* --------------------------------------------------------
       Create subscription record (pending)
       -------------------------------------------------------- */

    $stmt = $db->prepare(
        "INSERT INTO company_subscriptions
         (company_id, plan_code, status, started_at, expires_at)
         VALUES (?, ?, 'pending', NOW(), DATE_ADD(NOW(), INTERVAL 1 DAY))"
    );

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

    $subscriptionId = (int) $db->lastInsertId();

    /* --------------------------------------------------------
       Create payment record (pending)
       -------------------------------------------------------- */

    $reference = 'TSB-' . strtoupper(bin2hex(random_bytes(6)));

    $stmt = $db->prepare(
        "INSERT INTO payments
         (company_id, subscription_id, reference, plan_code, amount, currency, gateway, status)
         VALUES (?, ?, ?, ?, ?, 'ZAR', 'payfast', 'pending')"
    );

    $stmt->execute([
        $user['company_id'],
        $subscriptionId,
        $reference,
        $plan['code'],
        $plan['price']
    ]);

    $db->commit();

} catch (Throwable $e) {

    $db->rollBack();
    serverError('Failed to initialise payment');
}

/* ============================================================
   PAYFAST PAYLOAD (STRICT)
   ============================================================ */

$data = [
    // Merchant
    'merchant_id'    => PAYFAST_MERCHANT_ID,
    'merchant_key'   => PAYFAST_MERCHANT_KEY,

    // Buyer
    'email_address'  => $user['user_id'] . '@techstackbase.local',

    // Transaction
    'm_payment_id'   => $reference,
    'amount'         => number_format($plan['price'], 2, '.', ''),
    'item_name'      => $plan['name'],
    'item_description' => 'TechStackBase subscription – ' . $plan['billing_cycle'],

    // URLs
    'return_url'     => PAYFAST_RETURN_URL,
    'cancel_url'     => PAYFAST_CANCEL_URL,
    'notify_url'     => PAYFAST_NOTIFY_URL
];

/* ============================================================
   SIGNATURE
   ============================================================ */

$data['signature'] = payfastGenerateSignature($data);

/* ============================================================
   AUDIT LOG
   ============================================================ */

auditLog(
    $user['user_id'],
    $user['company_id'],
    'billing',
    'payfast_init',
    [
        'plan'        => $plan['code'],
        'reference'   => $reference,
        'amount'      => $plan['price']
    ]
);

/* ============================================================
   RESPONSE
   ============================================================ */

jsonResponse(
    true,
    'Payment initialised',
    [
        'endpoint' => PAYFAST_ENDPOINT,
        'payload'  => $data
    ]
);
