<?php
/**
 * Branch Balance Management
 * Mengelola saldo dan transaksi keuangan per cabang
 */
class BranchBalance {
    /**
     * Get saldo cabang
     */
    public static function getBalance($branchId) {
        $db = db();
        $stmt = $db->prepare("SELECT * FROM branch_balances WHERE branch_id = ?");
        $stmt->execute([$branchId]);
        $balance = $stmt->fetch();
        
        if (!$balance) {
            // Create default balance record
            $stmt = $db->prepare("
                INSERT INTO branch_balances (branch_id, balance, total_income, total_withdrawn)
                VALUES (?, 0.00, 0.00, 0.00)
            ");
            $stmt->execute([$branchId]);
            
            return [
                'branch_id' => $branchId,
                'balance' => 0.00,
                'total_income' => 0.00,
                'total_withdrawn' => 0.00
            ];
        }
        
        return $balance;
    }
    
    /**
     * Tambah saldo (saat ada pembayaran)
     */
    public static function addIncome($branchId, $amount, $referenceType = null, $referenceId = null, $description = null) {
        try {
            $db = db();
            $db->beginTransaction();
            
            // 1. Update balance
            $stmt = $db->prepare("
                UPDATE branch_balances 
                SET balance = balance + ?, 
                    total_income = total_income + ?,
                    updated_at = NOW()
                WHERE branch_id = ?
            ");
            $stmt->execute([$amount, $amount, $branchId]);
            
            // 2. Log transaction
            $stmt = $db->prepare("
                INSERT INTO balance_transactions (branch_id, type, amount, reference_type, reference_id, description)
                VALUES (?, 'income', ?, ?, ?, ?)
            ");
            $stmt->execute([
                $branchId,
                $amount,
                $referenceType,
                $referenceId,
                $description ?? "Pembayaran tagihan"
            ]);
            
            $db->commit();
            return ['success' => true];
            
        } catch (Exception $e) {
            $db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Kurangi saldo (saat penarikan disetujui)
     */
    public static function addWithdrawal($branchId, $amount, $referenceType = null, $referenceId = null, $description = null) {
        try {
            $db = db();
            
            // Cek saldo cukup
            $balance = self::getBalance($branchId);
            if ($balance['balance'] < $amount) {
                return ['success' => false, 'error' => 'Saldo tidak mencukupi'];
            }
            
            $db->beginTransaction();
            
            // 1. Update balance
            $stmt = $db->prepare("
                UPDATE branch_balances 
                SET balance = balance - ?, 
                    total_withdrawn = total_withdrawn + ?,
                    updated_at = NOW()
                WHERE branch_id = ?
            ");
            $stmt->execute([$amount, $amount, $branchId]);
            
            // 2. Log transaction
            $stmt = $db->prepare("
                INSERT INTO balance_transactions (branch_id, type, amount, reference_type, reference_id, description)
                VALUES (?, 'withdrawal', ?, ?, ?, ?)
            ");
            $stmt->execute([
                $branchId,
                $amount,
                $referenceType,
                $referenceId,
                $description ?? "Penarikan saldo"
            ]);
            
            $db->commit();
            return ['success' => true];
            
        } catch (Exception $e) {
            $db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get transaksi saldo cabang
     */
    public static function getTransactions($branchId, $limit = 50) {
        $db = db();
        $stmt = $db->prepare("
            SELECT * FROM balance_transactions 
            WHERE branch_id = ?
            ORDER BY created_at DESC
            LIMIT ?
        ");
        $stmt->execute([$branchId, $limit]);
        return $stmt->fetchAll();
    }
    
    /**
     * Get semua saldo cabang (untuk admin)
     */
    public static function getAllBalances() {
        $db = db();
        $stmt = $db->query("
            SELECT bb.*, b.name as branch_name, b.code as branch_code
            FROM branch_balances bb
            LEFT JOIN branches b ON bb.branch_id = b.id
            ORDER BY b.name ASC
        ");
        return $stmt->fetchAll();
    }
}