<?php
/**
 * Enterprise HRM ERP System - Petty Cash Month Closing
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

if (!hasAdminAccess()) {
    $_SESSION['error'] = 'You do not have permission to access this resource.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Close Petty Cash Month';
$currentModule = 'petty_cash';

$siteId = getCurrentSiteId();
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Check if already closed
$isLocked = isDataLocked('petty_cash', $siteId, $selectedMonth, $selectedYear);
if ($isLocked) {
    redirect(BASE_URL . '/modules/petty_cash/list.php?month=' . $selectedMonth . '&year=' . $selectedYear, 'This month is already closed.', 'error');
}

$errors = [];
$summary = [];

// Calculate summary
try {
    $db = getDB();
    
    // Get previous month closing balance
    $prevMonth = $selectedMonth - 1;
    $prevYear = $selectedYear;
    if ($prevMonth < 1) {
        $prevMonth = 12;
        $prevYear--;
    }
    
    $stmt = $db->prepare("SELECT closing_balance FROM petty_cash_closing WHERE site_id = ? AND month = ? AND year = ?");
    $stmt->execute([$siteId, $prevMonth, $prevYear]);
    $prevClosing = $stmt->fetch();
    $openingBalance = $prevClosing ? (float)$prevClosing['closing_balance'] : 0;
    
    // Calculate totals
    $stmt = $db->prepare("
        SELECT 
            SUM(CASE WHEN transaction_type = 'cash_in' THEN amount ELSE 0 END) as total_cash_in,
            SUM(CASE WHEN transaction_type = 'cash_out' THEN amount ELSE 0 END) as total_cash_out
        FROM petty_cash_transactions
        WHERE site_id = ? AND month = ? AND year = ?
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $totals = $stmt->fetch();
    
    $summary = [
        'opening_balance' => $openingBalance,
        'total_cash_in' => (float)($totals['total_cash_in'] ?? 0),
        'total_cash_out' => (float)($totals['total_cash_out'] ?? 0),
        'closing_balance' => $openingBalance + (float)($totals['total_cash_in'] ?? 0) - (float)($totals['total_cash_out'] ?? 0)
    ];
    
} catch (Exception $e) {
    error_log("Error calculating summary: " . $e->getMessage());
    $errors[] = 'Error calculating month summary.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_month'])) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // Insert closing record
        $stmt = $db->prepare("
            INSERT INTO petty_cash_closing (
                site_id, month, year,
                opening_balance, total_cash_in, total_cash_out, closing_balance,
                is_locked, locked_by
            ) VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?)
        ");
        $stmt->execute([
            $siteId,
            $selectedMonth,
            $selectedYear,
            $summary['opening_balance'],
            $summary['total_cash_in'],
            $summary['total_cash_out'],
            $summary['closing_balance'],
            getCurrentUserId()
        ]);
        
        // Lock data
        $lockResult = lockData('petty_cash', $siteId, $selectedMonth, $selectedYear, null, 'Month closed');
        
        if (!$lockResult['success']) {
            throw new Exception($lockResult['message']);
        }
        
        $db->commit();
        
        logAudit('CLOSE', 'petty_cash_closing', $db->lastInsertId());
        
        redirect(BASE_URL . '/modules/petty_cash/list.php?month=' . $selectedMonth . '&year=' . $selectedYear, 'Month closed and locked successfully.');
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log("Error closing month: " . $e->getMessage());
        $errors[] = 'An error occurred while closing the month. Please try again.';
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Close Petty Cash Month</h2>
        <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           class="btn btn-secondary">Back to Petty Cash</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <div style="margin-top: 20px;">
        <h3 style="margin-bottom: 20px;">Month Closing Summary - <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?></h3>
        
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 30px;">
            <div style="padding: 20px; background: #f9fafb; border-radius: 8px;">
                <p style="font-size: 14px; color: var(--text-secondary); margin-bottom: 10px;">Opening Balance</p>
                <p style="font-size: 24px; font-weight: 600;"><?php echo formatCurrency($summary['opening_balance']); ?></p>
            </div>
            
            <div style="padding: 20px; background: #d1fae5; border-radius: 8px;">
                <p style="font-size: 14px; color: var(--text-secondary); margin-bottom: 10px;">Total Cash In</p>
                <p style="font-size: 24px; font-weight: 600; color: #065f46;"><?php echo formatCurrency($summary['total_cash_in']); ?></p>
            </div>
            
            <div style="padding: 20px; background: #fee2e2; border-radius: 8px;">
                <p style="font-size: 14px; color: var(--text-secondary); margin-bottom: 10px;">Total Cash Out</p>
                <p style="font-size: 24px; font-weight: 600; color: #991b1b;"><?php echo formatCurrency($summary['total_cash_out']); ?></p>
            </div>
            
            <div style="padding: 20px; background: #fef3c7; border-radius: 8px;">
                <p style="font-size: 14px; color: var(--text-secondary); margin-bottom: 10px;">Closing Balance</p>
                <p style="font-size: 24px; font-weight: 600; color: #92400e;"><?php echo formatCurrency($summary['closing_balance']); ?></p>
            </div>
        </div>
        
        <div style="padding: 20px; background: #fef2f2; border-left: 4px solid #ef4444; border-radius: 6px; margin-bottom: 30px;">
            <p style="font-weight: 600; color: #991b1b; margin-bottom: 10px;">⚠️ Warning</p>
            <p style="color: #7f1d1d; line-height: 1.6;">
                Closing this month will lock all transactions for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>. 
                No further modifications will be allowed unless unlocked by an administrator.
            </p>
        </div>
        
        <form method="POST">
            <div style="text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
                <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                   class="btn btn-secondary">Cancel</a>
                <button type="submit" name="close_month" class="btn btn-primary"
                        onclick="return confirm('Are you sure you want to close this month? This action cannot be undone easily.');">
                    Close Month & Lock
                </button>
            </div>
        </form>
    </div>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

