<?php
ob_start();
include 'db.php';
include 'layout.php';
include 'financial_helpers.php';

$store_id = $_SESSION['store_id'] ?? 1;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'post_entry':
                $journal_entry_id = $_POST['journal_entry_id'];
                if (postJournalEntry($conn, $journal_entry_id)) {
                    $success_message = "Journal entry posted successfully!";
                } else {
                    $error_message = "Error posting journal entry. Please check the entry for balance.";
                }
                break;
                
            case 'void_entry':
                $journal_entry_id = $_POST['journal_entry_id'];
                $reason = $_POST['void_reason'];
                if (voidJournalEntry($conn, $journal_entry_id, $reason)) {
                    $success_message = "Journal entry voided successfully!";
                } else {
                    $error_message = "Error voiding journal entry.";
                }
                break;
        }
    }
}

// Get journal entries for display
$stmt = $conn->prepare("
    SELECT 
        je.*,
        COUNT(jel.id) as line_count,
        SUM(jel.debit_amount) as total_debits,
        SUM(jel.credit_amount) as total_credits
    FROM journal_entries je
    LEFT JOIN journal_entry_lines jel ON je.id = jel.journal_entry_id
    WHERE je.store_id = ?
    GROUP BY je.id
    ORDER BY je.created_at DESC
");
$stmt->bind_param("i", $store_id);
$stmt->execute();
$journal_entries = $stmt->get_result();
?>

<div class="page-wrapper">
    <div class="content">
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fa fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fa fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <div class="page-header">
            <div class="page-title">
                <h4>Journal Entries</h4>
                <h6>View and manage journal entries</h6>
            </div>
            <div class="page-btn">
                <button class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addJournalEntryModal">
                    <i class="fa fa-plus"></i> Add Journal Entry
                </button>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table datatable">
                        <thead>
                            <tr>
                                <th>Entry #</th>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Source</th>
                                <th>Reference</th>
                                <th>Lines</th>
                                <th>Total Debits</th>
                                <th>Total Credits</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($entry = $journal_entries->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($entry['entry_number']); ?></strong>
                                    </td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($entry['created_at'])); ?></td>
                                    <td>
                                        <?php echo htmlspecialchars($entry['description']); ?>
                                        <?php if ($entry['status'] === 'void'): ?>
                                            <br><small class="text-danger">VOID: <?php echo htmlspecialchars($entry['description']); ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-info">
                                            <?php echo ucfirst($entry['source_type']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo $entry['reference_id'] ? htmlspecialchars($entry['reference_id']) : '-'; ?></td>
                                    <td><?php echo $entry['line_count']; ?></td>
                                    <td>
                                        <span class="text-success">
                                            <?php echo number_format($entry['total_debits'], 2); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="text-danger">
                                            <?php echo number_format($entry['total_credits'], 2); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($entry['status'] === 'void'): ?>
                                            <span class="badge bg-danger">Void</span>
                                        <?php elseif ($entry['status'] === 'posted'): ?>
                                            <span class="badge bg-success">Posted</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning">Draft</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button class="btn btn-sm btn-outline-info" onclick="viewEntry(<?php echo $entry['id']; ?>)">
                                                <i class="fa fa-eye"></i>
                                            </button>
                                            <?php if ($entry['status'] === 'draft'): ?>
                                                <button class="btn btn-sm btn-outline-success" onclick="postEntry(<?php echo $entry['id']; ?>)">
                                                    <i class="fa fa-check"></i>
                                                </button>
                                                <button class="btn btn-sm btn-outline-danger" onclick="voidEntry(<?php echo $entry['id']; ?>)">
                                                    <i class="fa fa-times"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Journal Entry Modal -->
<div class="modal fade" id="addJournalEntryModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Journal Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="journalEntryForm">
                <input type="hidden" name="action" value="add_journal_entry">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="description" class="form-label">Description *</label>
                                <input type="text" class="form-control" id="description" name="description" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="source_type" class="form-label">Source Type</label>
                                <select class="form-select" id="source_type" name="source_type">
                                    <option value="manual">Manual Entry</option>
                                    <option value="sale">Sale</option>
                                    <option value="purchase">Purchase</option>
                                    <option value="expense">Expense</option>
                                    <option value="payment">Payment</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="reference_id" class="form-label">Reference ID</label>
                                <input type="text" class="form-control" id="reference_id" name="reference_id">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="entry_date" class="form-label">Entry Date</label>
                                <input type="date" class="form-control" id="entry_date" name="entry_date" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    <h6>Journal Lines</h6>
                    <div id="journalLines">
                        <div class="journal-line row mb-2">
                            <div class="col-md-4">
                                <select class="form-select account-select" name="lines[0][account_id]" required>
                                    <option value="">Select Account</option>
                                    <?php
                                    $accounts = $conn->query("SELECT id, account_code, account_name FROM chart_of_accounts WHERE is_active = 1 ORDER BY account_code");
                                    while ($account = $accounts->fetch_assoc()):
                                    ?>
                                        <option value="<?php echo $account['id']; ?>">
                                            <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <input type="number" class="form-control" name="lines[0][debit_amount]" placeholder="Debit Amount" step="0.01" min="0">
                            </div>
                            <div class="col-md-3">
                                <input type="number" class="form-control" name="lines[0][credit_amount]" placeholder="Credit Amount" step="0.01" min="0">
                            </div>
                            <div class="col-md-2">
                                <button type="button" class="btn btn-sm btn-outline-danger remove-line" style="display: none;">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addJournalLine()">
                        <i class="fa fa-plus"></i> Add Line
                    </button>
                    
                    <div class="mt-3">
                        <strong>Total Debits: <span id="totalDebits">0.00</span></strong> | 
                        <strong>Total Credits: <span id="totalCredits">0.00</span></strong> | 
                        <strong>Difference: <span id="difference">0.00</span></strong>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Journal Entry</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Entry Modal -->
<div class="modal fade" id="viewEntryModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Journal Entry Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="entryDetails">
                <!-- Content will be loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

<!-- Void Entry Modal -->
<div class="modal fade" id="voidEntryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Void Journal Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="void_entry">
                <input type="hidden" name="journal_entry_id" id="void_entry_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="void_reason" class="form-label">Void Reason *</label>
                        <textarea class="form-control" id="void_reason" name="void_reason" rows="3" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Void Entry</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let lineCounter = 1;

function addJournalLine() {
    const template = `
        <div class="journal-line row mb-2">
            <div class="col-md-4">
                <select class="form-select account-select" name="lines[${lineCounter}][account_id]" required>
                    <option value="">Select Account</option>
                    <?php
                    $accounts = $conn->query("SELECT id, account_code, account_name FROM chart_of_accounts WHERE is_active = 1 ORDER BY account_code");
                    while ($account = $accounts->fetch_assoc()):
                    ?>
                        <option value="<?php echo $account['id']; ?>">
                            <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-3">
                <input type="number" class="form-control debit-amount" name="lines[${lineCounter}][debit_amount]" placeholder="Debit Amount" step="0.01" min="0">
            </div>
            <div class="col-md-3">
                <input type="number" class="form-control credit-amount" name="lines[${lineCounter}][credit_amount]" placeholder="Credit Amount" step="0.01" min="0">
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-sm btn-outline-danger remove-line">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        </div>
    `;
    
    document.getElementById('journalLines').insertAdjacentHTML('beforeend', template);
    lineCounter++;
    
    // Show remove buttons for all lines except the first
    document.querySelectorAll('.remove-line').forEach(btn => {
        btn.style.display = 'inline-block';
    });
}

// Remove journal line
document.addEventListener('click', function(e) {
    if (e.target.closest('.remove-line')) {
        e.target.closest('.journal-line').remove();
        updateTotals();
    }
});

// Update totals when amounts change
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('debit-amount') || e.target.classList.contains('credit-amount')) {
        updateTotals();
    }
});

function updateTotals() {
    let totalDebits = 0;
    let totalCredits = 0;
    
    document.querySelectorAll('.debit-amount').forEach(input => {
        totalDebits += parseFloat(input.value) || 0;
    });
    
    document.querySelectorAll('.credit-amount').forEach(input => {
        totalCredits += parseFloat(input.value) || 0;
    });
    
    document.getElementById('totalDebits').textContent = totalDebits.toFixed(2);
    document.getElementById('totalCredits').textContent = totalCredits.toFixed(2);
    document.getElementById('difference').textContent = (totalDebits - totalCredits).toFixed(2);
}

function viewEntry(entryId) {
    fetch('ajax/get_journal_entry_details.php?id=' + entryId)
        .then(response => response.text())
        .then(html => {
            document.getElementById('entryDetails').innerHTML = html;
            new bootstrap.Modal(document.getElementById('viewEntryModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading entry details');
        });
}

function postEntry(entryId) {
    if (confirm('Are you sure you want to post this journal entry?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="post_entry">
            <input type="hidden" name="journal_entry_id" value="${entryId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

function voidEntry(entryId) {
    document.getElementById('void_entry_id').value = entryId;
    new bootstrap.Modal(document.getElementById('voidEntryModal')).show();
}


</script>

</body>
</html>
