<?php
require_once __DIR__ . '/../includes/db.php';

class Branch {
    public static function create($data) {
        $db = db();
        $code = $data['code'] ?? strtoupper(substr(uniqid(), -4));
        $stmt = $db->prepare("INSERT INTO branches (code, name, address, phone, email) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$code, $data['name'], $data['address'] ?? null, $data['phone'] ?? null, $data['email'] ?? null]);
        return $db->lastInsertId();
    }

    public static function all() {
        return db()->query("SELECT * FROM branches ORDER BY name")->fetchAll();
    }

    public static function find($id) {
        $stmt = db()->prepare("SELECT * FROM branches WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    /**
     * Request penarikan dana cabang
     */
    public static function requestWithdrawal($branchId, $amount, $bank, $account, $holder, $notes = '') {
        $db = db();
        $branch = self::find($branchId);
        if (!$branch) return ['success' => false, 'error' => 'Cabang tidak ditemukan'];

        $available = $branch['balance'] - $branch['pending_withdrawal'];
        if ($amount > $available) return ['success' => false, 'error' => 'Saldo tidak mencukupi'];

        $minWithdrawal = (float) getSetting('min_withdrawal', 100000);
        if ($amount < $minWithdrawal) {
            return ['success' => false, 'error' => 'Minimum penarikan ' . formatRupiah($minWithdrawal)];
        }

        $waitingHours = (int) getSetting('withdrawal_waiting_hours', 24);
        $canApproveAt = date('Y-m-d H:i:s', strtotime("+$waitingHours hours"));

        $stmt = $db->prepare("INSERT INTO withdrawal_requests 
            (branch_id, amount, bank_name, account_number, account_holder, notes, can_approve_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$branchId, $amount, $bank, $account, $holder, $notes, $canApproveAt]);
        $reqId = $db->lastInsertId();

        // Tandai sebagai pending (dikurangi dari available balance)
        $db->prepare("UPDATE branches SET pending_withdrawal = pending_withdrawal + ? WHERE id = ?")
           ->execute([$amount, $branchId]);

        return ['success' => true, 'id' => $reqId, 'can_approve_at' => $canApproveAt];
    }

    /**
     * Approve penarikan (oleh super admin)
     */
    public static function approveWithdrawal($requestId, $userId) {
        $db = db();
        $stmt = $db->prepare("SELECT * FROM withdrawal_requests WHERE id = ? AND status = 'pending'");
        $stmt->execute([$requestId]);
        $req = $stmt->fetch();
        if (!$req) return false;

        // Cek waktu tunggu sudah lewat
        if (strtotime($req['can_approve_at']) > time()) {
            return false; // belum bisa di-approve
        }

        $db->beginTransaction();
        try {
            $db->prepare("UPDATE withdrawal_requests SET status = 'approved', processed_at = NOW(), processed_by = ? WHERE id = ?")
               ->execute([$userId, $requestId]);
            
            // Kurangi saldo cabang
            $db->prepare("UPDATE branches SET balance = balance - ?, pending_withdrawal = pending_withdrawal - ? WHERE id = ?")
               ->execute([$req['amount'], $req['amount'], $req['branch_id']]);
            
            $db->commit();
            return true;
        } catch (Exception $e) {
            $db->rollBack();
            return false;
        }
    }

    /**
     * Reject penarikan
     */
    public static function rejectWithdrawal($requestId, $userId, $reason = '') {
        $db = db();
        $stmt = $db->prepare("SELECT * FROM withdrawal_requests WHERE id = ? AND status = 'pending'");
        $stmt->execute([$requestId]);
        $req = $stmt->fetch();
        if (!$req) return false;

        $db->beginTransaction();
        try {
            $db->prepare("UPDATE withdrawal_requests SET status = 'rejected', processed_at = NOW(), 
                         processed_by = ?, rejection_reason = ? WHERE id = ?")
               ->execute([$userId, $reason, $requestId]);
            
            // Kembalikan ke pending_withdrawal
            $db->prepare("UPDATE branches SET pending_withdrawal = pending_withdrawal - ? WHERE id = ?")
               ->execute([$req['amount'], $req['branch_id']]);
            
            $db->commit();
            return true;
        } catch (Exception $e) {
            $db->rollBack();
            return false;
        }
    }
}