<?php
/**
 * GET  /api/subscription/credits.php — رصيد الوثائق المدفوعة
 * POST /api/subscription/credits.php — خصم من رصيد الوثائق
 * WAVE E — Full Kernel Replace
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/PricingEngine.php';

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$ctx    = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u      = $ctx['user'];
$uid    = (int)$u['id'];

if ($method === 'GET') {
    try {
        $q = db()->prepare(
            "SELECT id, plan_key, remaining_sdg, total_sdg, period_month, period_year, updated_at
             FROM subscription_credits
             WHERE user_id=? AND period_month=MONTH(NOW()) AND period_year=YEAR(NOW())
             LIMIT 1"
        );
        $q->execute([$uid]);
        $credit = $q->fetch() ?: ['remaining_sdg' => 0, 'total_sdg' => 0];
        Kernel::respond(['credit' => $credit]);
    } catch (Throwable $e) {
        Logger::error('credits_fetch_failed', ['user_id' => $uid, 'error' => $e->getMessage()]);
        Kernel::fail('fetch_failed', 'تعذّر تحميل الرصيد', 500);
    }
}

if ($method === 'POST') {
    $b       = json_decode(file_get_contents('php://input'), true) ?? [];
    $costSdg = (float)($b['cost_sdg'] ?? 0);
    $service = mb_substr(trim($b['service'] ?? 'document'), 0, 50);

    if ($costSdg <= 0) Kernel::fail('invalid_cost', 'التكلفة يجب أن تكون أكبر من 0', 400);

    try {
        $check = db()->prepare(
            "SELECT id, remaining_sdg FROM subscription_credits
             WHERE user_id=? AND remaining_sdg>=?
             AND period_month=MONTH(NOW()) AND period_year=YEAR(NOW())
             LIMIT 1 FOR UPDATE"
        );
        db()->beginTransaction();
        $check->execute([$uid, $costSdg]);
        $row = $check->fetch();

        if (!$row) {
            db()->rollBack();
            Kernel::fail('insufficient_credit', 'رصيد الاشتراك غير كافٍ', 402,
                         ['cost_sdg' => $costSdg]);
        }

        db()->prepare(
            "UPDATE subscription_credits
             SET remaining_sdg = remaining_sdg - ?,
                 used_sdg = COALESCE(used_sdg,0) + ?
             WHERE id = ?"
        )->execute([$costSdg, $costSdg, $row['id']]);

        db()->commit();

        Logger::info('subscription_credit_used', [
            'user_id'   => $uid,
            'cost_sdg'  => $costSdg,
            'service'   => $service,
            'credit_id' => $row['id'],
        ]);
        Kernel::respond(['ok' => true, 'source' => 'subscription_credit', 'cost_sdg' => $costSdg]);

    } catch (Throwable $e) {
        if (db()->inTransaction()) db()->rollBack();
        Logger::error('credits_deduct_failed', ['user_id' => $uid, 'error' => $e->getMessage()]);
        Kernel::fail('deduction_failed', 'فشل خصم الرصيد', 500);
    }
}

Kernel::fail('method_not_allowed', '', 405);
