<?php

namespace Admin\Controllers;

use Admin\Controllers\AdminController;

class AdminBranchWalletController extends AdminController
{
    /**
     * List all branches with wallet balance
     */
    public function index()
    {
        requireAdmin();

        $stmt = $this->db->prepare("
            SELECT b.id, b.name, b.city, b.wallet_balance, b.branch_code
            FROM branches b
            ORDER BY b.name ASC
        ");
        $stmt->execute();
        $branches = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        return $this->adminView('branch-wallets/index', [
            'branches' => $branches
        ]);
    }

    /**
     * Show wallet transactions for a specific branch
     */
    public function show($params)
    {
        requireAdmin();

        $branchId = (int) ($params['id'] ?? 0);

        // Fetch branch details
        $stmt = $this->db->prepare("
            SELECT b.id, b.name, b.city, b.wallet_balance, b.branch_code
            FROM branches b
            WHERE b.id = :id
        ");
        $stmt->execute(['id' => $branchId]);
        $branch = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        // Fetch wallet transactions
        $stmt = $this->db->prepare("
            SELECT bwt.*
            FROM branch_wallet_transactions bwt
            WHERE bwt.branch_id = :branch_id
            ORDER BY bwt.created_at DESC
        ");
        $stmt->execute(['branch_id' => $branchId]);
        $transactions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        return $this->adminView('branch-wallets/show', [
            'branch'       => $branch,
            'transactions' => $transactions
        ]);
    }

    /**
     * Show form to add funds to a branch wallet
     */
    public function addFunds($params)
    {
        requireAdmin();

        $branchId = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("
            SELECT b.id, b.name, b.city, b.wallet_balance, b.branch_code
            FROM branches b
            WHERE b.id = :id
        ");
        $stmt->execute(['id' => $branchId]);
        $branch = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        return $this->adminView('branch-wallets/add-funds', [
            'branch' => $branch
        ]);
    }

    /**
     * Process adding funds to a branch wallet
     */
    public function processAddFunds($params)
    {
        requireAdmin();

        $this->validateCsrf();

        $branchId = (int) ($params['id'] ?? 0);
        $amount   = (float) ($_POST['amount'] ?? 0);
        $description = sanitize($_POST['description'] ?? 'Admin fund addition');

        if ($amount <= 0) {
            flash('error', 'Amount must be greater than ₹0.');
            redirect(BASE_PATH . '/admin/branch-wallets/add-funds/' . $branchId);
            return;
        }

        // Verify branch exists
        $stmt = $this->db->prepare("SELECT id, wallet_balance FROM branches WHERE id = :id");
        $stmt->execute(['id' => $branchId]);
        $branch = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        $this->db->beginTransaction();

        try {
            // Insert wallet transaction (credit)
            $stmt = $this->db->prepare("
                INSERT INTO branch_wallet_transactions (branch_id, type, amount, balance_after, description, created_at)
                VALUES (:branch_id, 'credit', :amount, :balance_after, :description, NOW())
            ");
            $stmt->execute([
                'branch_id'     => $branchId,
                'amount'        => $amount,
                'balance_after' => $branch['wallet_balance'] + $amount,
                'description'   => $description
            ]);

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

            $this->db->commit();

            flash('success', '₹' . number_format($amount, 2) . ' added to branch wallet successfully.');
        } catch (\Exception $e) {
            $this->db->rollBack();
            flash('error', 'Failed to add funds: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/admin/branch-wallets/show/' . $branchId);
    }

    /**
     * Process deducting funds from a branch wallet
     */
    public function deductFunds($params)
    {
        requireAdmin();

        $this->validateCsrf();

        $branchId = (int) ($params['id'] ?? 0);
        $amount   = (float) ($_POST['amount'] ?? 0);
        $description = sanitize($_POST['description'] ?? 'Admin fund deduction');

        if ($amount <= 0) {
            flash('error', 'Amount must be greater than ₹0.');
            redirect(BASE_PATH . '/admin/branch-wallets/show/' . $branchId);
            return;
        }

        // Verify branch exists and has sufficient balance
        $stmt = $this->db->prepare("SELECT id, wallet_balance FROM branches WHERE id = :id");
        $stmt->execute(['id' => $branchId]);
        $branch = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        if ($branch['wallet_balance'] < $amount) {
            flash('error', 'Insufficient wallet balance. Current balance: ₹' . number_format($branch['wallet_balance'], 2));
            redirect(BASE_PATH . '/admin/branch-wallets/show/' . $branchId);
            return;
        }

        $this->db->beginTransaction();

        try {
            // Insert wallet transaction (debit)
            $stmt = $this->db->prepare("
                INSERT INTO branch_wallet_transactions (branch_id, type, amount, balance_after, description, created_at)
                VALUES (:branch_id, 'debit', :amount, :balance_after, :description, NOW())
            ");
            $stmt->execute([
                'branch_id'     => $branchId,
                'amount'        => $amount,
                'balance_after' => $branch['wallet_balance'] - $amount,
                'description'   => $description
            ]);

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

            $this->db->commit();

            flash('success', '₹' . number_format($amount, 2) . ' deducted from branch wallet successfully.');
        } catch (\Exception $e) {
            $this->db->rollBack();
            flash('error', 'Failed to deduct funds: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/admin/branch-wallets/show/' . $branchId);
    }
}
