<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Core\Database;

class BillingController extends BaseController
{
    /**
     * Get all available subscription plans
     * GET /api/plans
     */
    public function getPlans(Request $request, Response $response): void
    {
        // Don't expose the Trial plan (ID 4) as an upgrade option, only paid ones.
        $plans = Database::select("SELECT * FROM subscription_plans WHERE price > 0 ORDER BY price ASC");
        
        $response->json([
            'status' => 'success',
            'data' => $plans
        ]);
    }

    /**
     * Upgrade or submit payment for a plan
     * POST /api/billing/upgrade
     */
    public function upgrade(Request $request, Response $response): void
    {
        $companyId = $request->company_id;
        $body = $request->getBody();

        $planId = $body['plan_id'] ?? null;
        $paymentMethod = $body['payment_method'] ?? 'manual'; // 'paymob', 'cliq', 'binance', etc.
        $receiptReference = $body['receipt_reference'] ?? null;

        if (!$planId) {
            $response->status(400)->json(['error' => 'Missing plan_id']);
            return;
        }

        $plan = Database::selectOne("SELECT * FROM subscription_plans WHERE id = ?", [$planId]);
        if (!$plan) {
            $response->status(404)->json(['error' => 'Plan not found']);
            return;
        }

        try {
            if ($paymentMethod === 'paymob') {
                // Here we would integrate Paymob API to generate a payment link
                // For now, we simulate returning a checkout URL.
                $checkoutUrl = "https://paymob.com/checkout/mock_url_for_plan_{$planId}_company_{$companyId}";
                
                $response->json([
                    'status' => 'success',
                    'message' => 'Redirect to Paymob to complete payment',
                    'checkout_url' => $checkoutUrl
                ]);
            } else {
                // Manual Payment (CliQ, Binance, Bank Transfer)
                if (empty($receiptReference)) {
                    $response->status(400)->json(['error' => 'Please provide a receipt reference or transaction ID']);
                    return;
                }

                // Delete any existing pending requests for this company to avoid spam
                Database::execute("DELETE FROM company_subscriptions WHERE company_id = ? AND status = 'pending_approval'", [$companyId]);

                // Insert a pending subscription request
                Database::execute("
                    INSERT INTO company_subscriptions (company_id, plan_id, status, starts_at, ends_at, payment_method, receipt_reference)
                    VALUES (?, ?, 'pending_approval', NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY), ?, ?)
                ", [$companyId, $planId, $paymentMethod, $receiptReference]);

                $response->json([
                    'status' => 'success',
                    'message' => 'Payment receipt submitted successfully. Your account will be upgraded after admin approval.'
                ]);
            }
        } catch (\Exception $e) {
            $response->status(500)->json(['error' => 'Failed to process upgrade request: ' . $e->getMessage()]);
        }
    }
}
