<?php
/**
 * Branch Wallet Controller — NEW
 * 
 * Shows branch wallet balance, recharge history, and certificate generation history.
 */

namespace BranchAdmin\Controllers;

use BranchAdmin\Controllers\BranchBaseController;

class BranchWalletController extends BranchBaseController
{
    /**
     * Wallet Dashboard — Balance + Recent Activity
     */
    public function index(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        // 1. Get Wallet Balance
        $stmt = $this->db->prepare("SELECT wallet_balance FROM branches WHERE id = :bid LIMIT 1");
        $stmt->execute([':bid' => $branchId]);
        $walletBalance = (float)($stmt->fetchColumn() ?: 0);

        // 2. Get Stats (Total Recharged, Total Spent)
        $stmt = $this->db->prepare("SELECT 
            SUM(CASE WHEN type='credit' THEN amount ELSE 0 END) as total_recharged,
            SUM(CASE WHEN type='debit' THEN amount ELSE 0 END) as total_spent
            FROM branch_wallet_transactions WHERE branch_id = :bid");
        $stmt->execute([':bid' => $branchId]);
        $stats = $stmt->fetch() ?: ['total_recharged' => 0, 'total_spent' => 0];

        // 3. Recent Transactions (10)
        $stmt = $this->db->prepare(
            "SELECT t.*, c.certificate_no, c.student_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 LIMIT 10"
        );
        $stmt->execute([':bid' => $branchId]);
        $recentTxns = $stmt->fetchAll() ?: [];

        $this->branchAdminView('wallet/index', [
            'title'          => 'My Wallet',
            'currentPage'    => 'wallet',
            'walletBalance'  => $walletBalance,
            'totalRecharged' => (float)($stats['total_recharged'] ?? 0),
            'totalSpent'     => (float)($stats['total_spent'] ?? 0),
            'recentTxns'     => $recentTxns,
            'csrfToken'      => $this->csrfToken ?? '',
        ]);
    }

    /**
     * Full Transaction History (Date-wise, with filters)
     */
    public function history(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        // Filters
        $dateFrom = trim($_GET['date_from'] ?? '');
        $dateTo = trim($_GET['date_to'] ?? '');
        $typeFilter = trim($_GET['type'] ?? '');

        $sql = "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";
        $params = [':bid' => $branchId];

        if (!empty($dateFrom)) {
            $sql .= " AND DATE(t.created_at) >= :df";
            $params[':df'] = $dateFrom;
        }
        if (!empty($dateTo)) {
            $sql .= " AND DATE(t.created_at) <= :dt";
            $params[':dt'] = $dateTo;
        }
        if (!empty($typeFilter) && in_array($typeFilter, ['credit', 'debit'])) {
            $sql .= " AND t.type = :ty";
            $params[':ty'] = $typeFilter;
        }

        $sql .= " ORDER BY t.created_at DESC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $transactions = $stmt->fetchAll() ?: [];

        $this->branchAdminView('wallet/history', [
            'title'        => 'Wallet History',
            'currentPage'  => 'wallet',
            'transactions' => $transactions,
            'dateFrom'     => $dateFrom,
            'dateTo'       => $dateTo,
            'typeFilter'   => $typeFilter,
            'csrfToken'    => $this->csrfToken ?? '',
        ]);
    }
}
