<?php
/**
 * Super Admin Wallet Controller — NEW
 * 
 * Manages branch wallet balances:
 *   - List all branches with wallet balances
 *   - Recharge (add money) to any branch
 *   - View transaction history per branch
 */

namespace SuperAdmin\Controllers;

use SuperAdmin\Controllers\SuperAdminBaseController;

class SuperAdminWalletController extends SuperAdminBaseController
{
    /**
     * List all branches with wallet balances
     */
    public function index(): void
    {
        requireSuperAdmin();

        $stmt = $this->db->query(
            "SELECT b.*, u.name AS admin_name, u.email AS admin_email,
                    (SELECT COUNT(*) FROM certificates c WHERE c.branch_id = b.id AND c.status = 'generated') AS cert_count,
                    (SELECT SUM(amount) FROM branch_wallet_transactions WHERE branch_id = b.id AND type = 'debit') AS total_spent,
                    (SELECT SUM(amount) FROM branch_wallet_transactions WHERE branch_id = b.id AND type = 'credit') AS total_recharged
             FROM branches b
             LEFT JOIN users u ON b.admin_user_id = u.id
             ORDER BY b.name ASC"
        );
        $branches = $stmt->fetchAll() ?: [];

        $this->superAdminView('wallet/index', [
            'title'       => 'Branch Wallet Management',
            'currentPage' => 'wallet',
            'branches'    => $branches,
            'csrfToken'   => $this->csrfToken ?? '',
        ]);
    }

    /**
     * Show recharge form for a specific branch
     */
    public function recharge(?int $branchId = null): void
    {
        requireSuperAdmin();

        if (!$branchId) {
            $branchId = (int)($_GET['id'] ?? 0);
        }

        if (!$branchId) {
            flash('error', 'Branch ID required.');
            redirect(BASE_PATH . '/super-admin/wallet');
        }

        $stmt = $this->db->prepare(
            "SELECT b.*, u.name AS admin_name, u.email AS admin_email
             FROM branches b
             LEFT JOIN users u ON b.admin_user_id = u.id
             WHERE b.id = :id LIMIT 1"
        );
        $stmt->execute([':id' => $branchId]);
        $branch = $stmt->fetch() ?: null;

        if (!$branch) {
            flash('error', 'Branch not found.');
            redirect(BASE_PATH . '/super-admin/wallet');
        }

        // Get recent transactions
        $stmt = $this->db->prepare(
            "SELECT * FROM branch_wallet_transactions
             WHERE branch_id = :bid
             ORDER BY created_at DESC
             LIMIT 20"
        );
        $stmt->execute([':bid' => $branchId]);
        $transactions = $stmt->fetchAll() ?: [];

        $this->superAdminView('wallet/recharge', [
            'title'        => 'Recharge Wallet: ' . ($branch['name'] ?? ''),
            'currentPage'  => 'wallet',
            'branch'       => $branch,
            'transactions' => $transactions,
            'csrfToken'    => $this->csrfToken ?? '',
        ]);
    }

    /**
     * Process wallet recharge
     */
    public function processRecharge(): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

        $branchId = (int)($_POST['branch_id'] ?? 0);
        $amount = (float)($_POST['amount'] ?? 0);
        $description = trim($_POST['description'] ?? '');
        $txnId = trim($_POST['txn_id'] ?? '');

        if (!$branchId || $amount <= 0) {
            flash('error', 'Invalid branch or amount.');
            redirect(BASE_PATH . '/super-admin/wallet');
        }

        try {
            // Update wallet balance
            $stmt = $this->db->prepare("UPDATE branches SET wallet_balance = wallet_balance + :amt WHERE id = :bid");
            $stmt->execute([':amt' => $amount, ':bid' => $branchId]);

            // Get new balance
            $stmt = $this->db->prepare("SELECT wallet_balance FROM branches WHERE id = :bid");
            $stmt->execute([':bid' => $branchId]);
            $newBalance = (float)($stmt->fetchColumn() ?: 0);

            // Record transaction
            $this->db->prepare(
                "INSERT INTO branch_wallet_transactions
                    (branch_id, type, amount, balance_after, description, category, reference_type, txn_id, created_by, created_at)
                 VALUES (:bid, 'credit', :amt, :bal, :desc, 'recharge', 'wallet', :txn, :uid, NOW())"
            )->execute([
                ':bid'  => $branchId,
                ':amt'  => $amount,
                ':bal'  => $newBalance,
                ':desc' => $description ?: "Wallet recharge by Super Admin",
                ':txn'  => $txnId ?: null,
                ':uid'  => $_SESSION['user_id'] ?? null,
            ]);

            $this->auditLog('wallet_recharge', 'branches', $branchId, "Recharged ₹{$amount} to branch #{$branchId}. New balance: ₹{$newBalance}");

            flash('success', "✅ Wallet recharged successfully! ₹{$amount} added. New balance: ₹{$newBalance}");
        } catch (\Throwable $e) {
            error_log('Wallet recharge error: ' . $e->getMessage());
            flash('error', 'Error recharging wallet: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/super-admin/wallet/recharge?id=' . $branchId);
    }

    /**
     * View full transaction history for a branch
     */
    public function history(?int $branchId = null): void
    {
        requireSuperAdmin();

        if (!$branchId) {
            $branchId = (int)($_GET['id'] ?? 0);
        }

        if (!$branchId) {
            flash('error', 'Branch ID required.');
            redirect(BASE_PATH . '/super-admin/wallet');
        }

        // Get branch info
        $stmt = $this->db->prepare("SELECT * FROM branches WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $branchId]);
        $branch = $stmt->fetch() ?: null;

        if (!$branch) {
            flash('error', 'Branch not found.');
            redirect(BASE_PATH . '/super-admin/wallet');
        }

        // Get ALL transactions
        $stmt = $this->db->prepare(
            "SELECT t.*,
                    c.certificate_no,
                    c.student_name,
                    c.course_name
             FROM branch_wallet_transactions t
             LEFT JOIN certificates c ON t.reference_id = c.id AND t.reference_type = 'certificate'
             WHERE t.branch_id = :bid
             ORDER BY t.created_at DESC"
        );
        $stmt->execute([':bid' => $branchId]);
        $transactions = $stmt->fetchAll() ?: [];

        // Calculate stats
        $totalRecharged = 0;
        $totalSpent = 0;
        foreach ($transactions as $t) {
            if ($t['type'] === 'credit') $totalRecharged += (float)$t['amount'];
            else $totalSpent += (float)$t['amount'];
        }

        $this->superAdminView('wallet/history', [
            'title'          => 'Wallet History: ' . ($branch['name'] ?? ''),
            'currentPage'    => 'wallet',
            'branch'         => $branch,
            'transactions'   => $transactions,
            'totalRecharged' => $totalRecharged,
            'totalSpent'     => $totalSpent,
            'csrfToken'      => $this->csrfToken ?? '',
        ]);
    }
}
