<?php

namespace App\Modules\Finance\Controllers;

use Core\Controller;
use Core\Auth;

class BillingController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireAuth();
    }

    public function index()
    {
        $isSuperAdmin = Auth::isSuperAdmin();
        $orgId = Auth::orgId();
        $where = $isSuperAdmin ? '' : 'WHERE sc.org_id = ?';
        $params = $isSuperAdmin ? [] : [$orgId];

        $charges = $this->dbQuery(
            "SELECT sc.*, o.name as org_name, c.company_name as contractor_name
             FROM subscription_charges sc
             LEFT JOIN organizations o ON sc.org_id = o.id
             LEFT JOIN contractors c ON sc.contractor_id = c.id
             {$where}
             ORDER BY sc.created_at DESC LIMIT 50",
            $params
        );

        $stats = [
            'total'   => count($charges),
            'pending' => array_sum(array_map(fn($c) => $c['status'] === 'pending' ? (float)$c['charge_amount'] : 0, $charges)),
            'paid'    => array_sum(array_map(fn($c) => $c['status'] === 'paid' ? (float)$c['charge_amount'] : 0, $charges)),
        ];

        $this->render('finance/billing/index', [
            'pageTitle' => 'Billing & Platform Fees',
            'charges'   => $charges,
            'stats'     => $stats,
            'breadcrumb' => [['label' => 'Finance'], ['label' => 'Billing']],
        ]);
    }

    public function recordPayment(int $chargeId)
    {
        $this->requireAuth();
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token.');
            $this->redirect(APP_URL . '/finance/billing');
        }

        if (Auth::isSuperAdmin()) {
            $charge = $this->dbQueryOne("SELECT id FROM subscription_charges WHERE id = ?", [$chargeId]);
        } else {
            $charge = $this->dbQueryOne("SELECT id FROM subscription_charges WHERE id = ? AND org_id = ?", [$chargeId, Auth::orgId()]);
        }
        if (!$charge) {
            $this->setFlash('error', 'Charge not found.');
            $this->redirect(APP_URL . '/finance/billing');
        }

        $amount    = (float) $this->getPost('amount', 0);
        $method    = $this->getPost('payment_method', 'bank_transfer');
        $reference = $this->getPost('payment_reference', '');

        $this->dbExecute(
            "INSERT INTO subscription_payments (charge_id, amount, payment_method, payment_reference, payment_date, created_by, created_at) VALUES (?, ?, ?, ?, CURDATE(), ?, NOW())",
            [$chargeId, $amount, $method, $reference, Auth::id()]
        );

        $this->dbExecute(
            "UPDATE subscription_charges SET status = 'paid', paid_at = NOW() WHERE id = ?",
            [$chargeId]
        );

        $this->setFlash('success', 'Payment recorded successfully.');
        $this->redirect(APP_URL . '/finance/billing');
    }
}
