<?php
/**
 * Assign/Upgrade Subscription Plan (Super Admin only)
 * POST /api/v1/subscriptions/assign
 */

use App\Core\Database;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();

// Only Super Admin can change plans manually via this API
if ($decoded['role'] !== 'super_admin') {
    json_error('غير مصرح لك بتغيير الباقات. يرجى التواصل مع الدعم الفني.', 403);
}

$data = input();
$targetTenantId = $data['tenant_id'] ?? null;
$planId         = $data['plan_id'] ?? null;
$durationDays   = (int)($data['duration_days'] ?? 30);

if (!$targetTenantId || !$planId) {
    json_error('معرف المكتب ومعرف الباقة مطلوبان.', 422);
}

$db = Database::getInstance();

try {
    // 1. Validate Plan
    $stmt = $db->prepare("SELECT * FROM subscription_plans WHERE id = ? AND is_active = 1");
    $stmt->execute([$planId]);
    $plan = $stmt->fetch();

    if (!$plan) {
        json_error('الباقة المختارة غير صالحة أو غير نشطة.', 422);
    }

    // 2. Update or Create Subscription
    $db->beginTransaction();

    $startDate = date('Y-m-d H:i:s');
    $endDate   = date('Y-m-d H:i:s', strtotime("+{$durationDays} days"));

    $stmt = $db->prepare("
        INSERT INTO subscriptions (
            tenant_id, plan_id, max_companies, max_invoices_per_month, max_users, 
            price_jod, status, current_period_start, current_period_end, updated_at
        ) VALUES (
            :t_id, :p_id, :max_c, :max_i, :max_u, :price, 'active', :start, :end, NOW()
        )
        ON DUPLICATE KEY UPDATE
            plan_id = VALUES(plan_id),
            max_companies = VALUES(max_companies),
            max_invoices_per_month = VALUES(max_invoices_per_month),
            max_users = VALUES(max_users),
            price_jod = VALUES(price_jod),
            status = 'active',
            current_period_start = VALUES(current_period_start),
            current_period_end = VALUES(current_period_end),
            updated_at = NOW()
    ");

    $stmt->execute([
        't_id'  => $targetTenantId,
        'p_id'  => $planId,
        'max_c' => $plan['max_companies'],
        'max_i' => $plan['max_invoices_month'],
        'max_u' => $plan['max_users'],
        'price' => $plan['price_jod'],
        'start' => $startDate,
        'end'   => $endDate
    ]);

    // 3. Log the change
    $logStmt = $db->prepare("INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, details) VALUES (?, ?, 'plan_assigned', 'tenant', ?, ?)");
    $logStmt->execute([
        $targetTenantId,
        $decoded['user_id'],
        $targetTenantId,
        json_encode(['plan_id' => $planId, 'assigned_by' => $decoded['user_id']])
    ]);

    $db->commit();

    json_success([
        'tenant_id' => $targetTenantId,
        'plan_id'   => $planId,
        'period_end' => $endDate
    ], 'تم تحديث باقة الاشتراك بنجاح');

} catch (\Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    error_log("Subscription Assign Error: " . $e->getMessage());
    json_error('حدث خطأ أثناء تعيين الباقة: ' . $e->getMessage(), 500);
}
