<?php
/**
 * Withdrawal Request Management
 * Disesuaikan dengan struktur tabel yang sudah ada
 */
class Withdrawal {
    /**
     * Create withdrawal request
     */
    public static function create($branchId, $amount, $bankName, $accountNumber, $accountHolder, $requestedBy, $notes = null) {
        try {
            $db = db();
            
            // Cek saldo cukup
            $balance = BranchBalance::getBalance($branchId);
            if ($balance['balance'] < $amount) {
                return ['success' => false, 'error' => 'Saldo tidak mencukupi. Saldo tersedia: Rp ' . number_format($balance['balance'])];
            }
            
            if ($amount < 50000) {
                return ['success' => false, 'error' => 'Minimum penarikan Rp 50.000'];
            }
            
            $stmt = $db->prepare("
                INSERT INTO withdrawal_requests 
                (branch_id, amount, bank_name, account_number, account_holder, notes, requested_by, requested_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            $stmt->execute([$branchId, $amount, $bankName, $accountNumber, $accountHolder, $notes, $requestedBy]);
            
            return [
                'success' => true,
                'id' => $db->lastInsertId()
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Approve withdrawal (oleh admin)
     */
    public static function approve($withdrawalId, $approvedBy) {
        try {
            $db = db();
            $db->beginTransaction();
            
            $stmt = $db->prepare("SELECT * FROM withdrawal_requests WHERE id = ? AND status = 'pending'");
            $stmt->execute([$withdrawalId]);
            $withdrawal = $stmt->fetch();
            
            if (!$withdrawal) {
                return ['success' => false, 'error' => 'Request tidak ditemukan atau sudah diproses'];
            }
            
            // Kurangi saldo cabang
            $result = BranchBalance::addWithdrawal(
                $withdrawal['branch_id'],
                $withdrawal['amount'],
                'withdrawal',
                $withdrawalId,
                "Penarikan ke {$withdrawal['bank_name']} - {$withdrawal['account_number']}"
            );
            
            if (!$result['success']) {
                $db->rollBack();
                return $result;
            }
            
            // Update status (gunakan kolom yang sesuai dengan tabel Anda)
            $stmt = $db->prepare("
                UPDATE withdrawal_requests 
                SET status = 'approved', 
                    processed_by = ?, 
                    processed_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$approvedBy, $withdrawalId]);
            
            $db->commit();
            return ['success' => true];
            
        } catch (Exception $e) {
            $db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Reject withdrawal (oleh admin)
     */
    public static function reject($withdrawalId, $approvedBy, $reason = null) {
        try {
            $db = db();
            
            // Gunakan kolom rejection_reason yang terpisah
            $stmt = $db->prepare("
                UPDATE withdrawal_requests 
                SET status = 'rejected', 
                    processed_by = ?, 
                    processed_at = NOW(),
                    rejection_reason = ?
                WHERE id = ? AND status = 'pending'
            ");
            $stmt->execute([$approvedBy, $reason, $withdrawalId]);
            
            return ['success' => true];
            
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get withdrawal by ID
     */
    public static function find($id) {
        $db = db();
        $stmt = $db->prepare("
            SELECT w.*, b.name as branch_name, u.username as requested_by_name
            FROM withdrawal_requests w
            LEFT JOIN branches b ON w.branch_id = b.id
            LEFT JOIN users u ON w.requested_by = u.id
            WHERE w.id = ?
        ");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }
    
    /**
     * Get all withdrawals (untuk admin)
     */
    public static function getAll($status = '', $branchId = null) {
        $db = db();
        
        $sql = "
            SELECT w.*, b.name as branch_name, b.code as branch_code, 
                   u.username as requested_by_name
            FROM withdrawal_requests w
            LEFT JOIN branches b ON w.branch_id = b.id
            LEFT JOIN users u ON w.requested_by = u.id
        ";
        
        $where = [];
        $params = [];
        
        if ($status) {
            $where[] = "w.status = ?";
            $params[] = $status;
        }
        
        if ($branchId) {
            $where[] = "w.branch_id = ?";
            $params[] = $branchId;
        }
        
        if (!empty($where)) {
            $sql .= " WHERE " . implode(' AND ', $where);
        }
        
        $sql .= " ORDER BY w.requested_at DESC LIMIT 100";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
    
    /**
     * Get withdrawals by branch (untuk cabang)
     */
    public static function getByBranch($branchId, $limit = 50) {
        $db = db();
        $stmt = $db->prepare("
            SELECT w.*, u.username as requested_by_name
            FROM withdrawal_requests w
            LEFT JOIN users u ON w.requested_by = u.id
            WHERE w.branch_id = ?
            ORDER BY w.requested_at DESC
            LIMIT ?
        ");
        $stmt->execute([$branchId, $limit]);
        return $stmt->fetchAll();
    }
}