<?php
/**
 * Cron Job: Auto-release saldo cabang yang sudah lewat H+5
 * Jalankan setiap hari jam 00:05 via cron:
 * 5 0 * * * /usr/local/bin/php /home/lintasfi/public_html/cron/release_balances.php
 */

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

$logFile = __DIR__ . '/logs/release_log.txt';
$db = db();

// Pastikan folder logs ada
if (!is_dir(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0755, true);
}

try {
    // ✅ DIPERBAIKI: Query hanya ambil dari branch_transactions (tanpa JOIN yang error)
    $stmt = $db->prepare("
        SELECT bt.*
        FROM branch_transactions bt
        WHERE bt.status = 'pending' 
        AND bt.pending_until <= NOW()
        ORDER BY bt.pending_until ASC
    ");
    $stmt->execute();
    $transactions = $stmt->fetchAll();
    
    if (empty($transactions)) {
        file_put_contents($logFile, 
            date('Y-m-d H:i:s') . " - Tidak ada transaksi yang perlu di-release\n", 
            FILE_APPEND);
        exit("No transactions to release\n");
    }
    
    $releasedCount = 0;
    $releasedAmount = 0;
    
    $db->beginTransaction();
    
    foreach ($transactions as $trx) {
        // 1. Update status transaksi ke 'released'
        $stmt = $db->prepare("
            UPDATE branch_transactions 
            SET status = 'released', released_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$trx['id']]);
        
        // 2. Pindahkan dari pending_balance ke available_balance
        // ✅ DIPERBAIKI: Pastikan kolom branch_id ada di branch_balances
        $stmt = $db->prepare("
            UPDATE branch_balances 
            SET pending_balance = pending_balance - ?,
                available_balance = available_balance + ?,
                last_updated_at = NOW()
            WHERE branch_id = ?
        ");
        $stmt->execute([$trx['amount'], $trx['amount'], $trx['branch_id']]);
        
        $releasedCount++;
        $releasedAmount += $trx['amount'];
        
        file_put_contents($logFile, 
            date('Y-m-d H:i:s') . " - RELEASED: Cabang #{$trx['branch_id']} +Rp " . 
            number_format($trx['amount']) . " (Bill: {$trx['bill_number']})\n", 
            FILE_APPEND);
    }
    
    $db->commit();
    
    file_put_contents($logFile, 
        date('Y-m-d H:i:s') . " - SUMMARY: $releasedCount transaksi, total Rp " . 
        number_format($releasedAmount) . " di-release\n\n", 
        FILE_APPEND);
    
    echo "Released $releasedCount transactions, total Rp " . number_format($releasedAmount) . "\n";
    
} catch (\Throwable $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    file_put_contents($logFile, 
        date('Y-m-d H:i:s') . " - ERROR: " . $e->getMessage() . "\n", 
        FILE_APPEND);
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}