<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$errors = [];
$success_message = '';

// Fetch active accounts for dropdowns
$accounts_sql = "SELECT account_id, account_code, account_name, account_type, normal_balance 
                 FROM chart_of_accounts 
                 WHERE is_active = 1 AND is_header = 0
                 ORDER BY account_code";
$accounts_result = $conn->query($accounts_sql);

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entry_date = $_POST['entry_date'] ?? date('Y-m-d');
    $description = trim($_POST['description'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $line_count = intval($_POST['line_count'] ?? 0);
    
    // Validation
    if (empty($description)) {
        $errors[] = "Description is required";
    }
    
    if ($line_count < 2) {
        $errors[] = "At least 2 journal entry lines are required";
    }
    
    // Collect and validate journal lines
    $journal_lines = [];
    $total_debit = 0;
    $total_credit = 0;
    
    for ($i = 1; $i <= $line_count; $i++) {
        $account_id = $_POST["account_id_$i"] ?? null;
        $line_description = trim($_POST["line_description_$i"] ?? '');
        $debit = floatval($_POST["debit_$i"] ?? 0);
        $credit = floatval($_POST["credit_$i"] ?? 0);
        
        if ($account_id && ($debit > 0 || $credit > 0)) {
            if ($debit > 0 && $credit > 0) {
                $errors[] = "Line $i: Cannot have both debit and credit amounts";
            } else {
                $journal_lines[] = [
                    'account_id' => $account_id,
                    'description' => $line_description,
                    'debit' => $debit,
                    'credit' => $credit
                ];
                $total_debit += $debit;
                $total_credit += $credit;
            }
        }
    }
    
    if (count($journal_lines) < 2) {
        $errors[] = "At least 2 valid journal entry lines are required";
    }
    
    // Check if debits equal credits
    if (abs($total_debit - $total_credit) > 0.01) {
        $errors[] = "Total debits (KES " . number_format($total_debit, 2) . ") must equal total credits (KES " . number_format($total_credit, 2) . ")";
    }
    
    // If no errors, create the journal entry
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            // Generate journal number
            $journal_number_sql = "SELECT GenerateJournalNumber() as journal_number";
            $journal_number_result = $conn->query($journal_number_sql);
            $journal_number = $journal_number_result->fetch_assoc()['journal_number'];
            
            // Get fiscal period
            $fiscal_year = date('Y', strtotime($entry_date));
            $fiscal_period = date('n', strtotime($entry_date));
            
            // Insert journal entry header
            $journal_sql = "INSERT INTO journal_entries (
                            journal_number, entry_date, entry_type, description,
                            total_debit, total_credit, status, fiscal_year, fiscal_period,
                            notes, created_by, created_at
                           ) VALUES (?, ?, 'MANUAL', ?, ?, ?, 'DRAFT', ?, ?, ?, ?, NOW())";
            
            $stmt = $conn->prepare($journal_sql);
            $stmt->bind_param("sssddiisi", 
                $journal_number, $entry_date, $description,
                $total_debit, $total_credit, $fiscal_year, $fiscal_period,
                $notes, $user_id
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create journal entry: " . $stmt->error);
            }
            
            $journal_id = $conn->insert_id;
            
            // Insert journal entry lines
            $line_number = 1;
            $line_sql = "INSERT INTO journal_entry_lines (
                         journal_id, line_number, account_id, debit_amount, credit_amount, description
                        ) VALUES (?, ?, ?, ?, ?, ?)";
            
            $line_stmt = $conn->prepare($line_sql);
            
            foreach ($journal_lines as $line) {
                $line_stmt->bind_param("iiidds",
                    $journal_id, $line_number, $line['account_id'],
                    $line['debit'], $line['credit'], $line['description']
                );
                
                if (!$line_stmt->execute()) {
                    throw new Exception("Failed to create journal line: " . $line_stmt->error);
                }
                
                $line_number++;
            }
            
            // Post the journal entry to general ledger
            $post_sql = "CALL PostJournalToLedger(?)";
            $post_stmt = $conn->prepare($post_sql);
            $post_stmt->bind_param("i", $journal_id);
            
            if (!$post_stmt->execute()) {
                throw new Exception("Failed to post journal to ledger: " . $post_stmt->error);
            }
            
            // Close statement and clear results
            $post_stmt->close();
            while ($conn->more_results()) {
                $conn->next_result();
                if ($res = $conn->store_result()) {
                    $res->free();
                }
            }
            
            // Log the activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                           new_values, ip_address, logged_at) 
                           VALUES (?, 'CREATE', 'ACCOUNTING', ?, 'JOURNAL_ENTRY', ?, ?, NOW())";
            
            $activity_values = json_encode([
                'journal_number' => $journal_number,
                'entry_date' => $entry_date,
                'description' => $description,
                'total_debit' => $total_debit,
                'total_credit' => $total_credit,
                'line_count' => count($journal_lines)
            ]);
            
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            $stmt = $conn->prepare($activity_sql);
            $stmt->bind_param("iiss", $user_id, $journal_id, $activity_values, $ip_address);
            $stmt->execute();
            
            $conn->commit();
            
            $success_message = "Journal entry created and posted successfully!<br>
                              <strong>Journal Number:</strong> " . htmlspecialchars($journal_number) . "<br>
                              <strong>Entry Date:</strong> " . date('d M Y', strtotime($entry_date)) . "<br>
                              <strong>Total Amount:</strong> KES " . number_format($total_debit, 2);
            
            // Clear form
            $_POST = array();
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Failed to create journal entry: " . $e->getMessage();
            error_log("Journal Entry Creation Error: " . $e->getMessage());
        }
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Journal Entry')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .journal-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .journal-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
        
        .journal-body {
            padding: 1.5rem;
        }
        
        .section-title {
            font-size: 1rem;
            font-weight: 600;
            color: #475569;
            margin: 1.5rem 0 1rem 0;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .journal-line-row {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            position: relative;
        }
        
        .line-number {
            position: absolute;
            top: 0.5rem;
            left: 0.5rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .remove-line-btn {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            background: #fee2e2;
            color: #dc2626;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
        }
        
        .remove-line-btn:hover {
            background: #dc2626;
            color: white;
        }
        
        .add-line-btn {
            width: 100%;
            padding: 1rem;
            border: 2px dashed #cbd5e1;
            background: #f8fafc;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            color: #64748b;
            font-weight: 500;
        }
        
        .add-line-btn:hover {
            border-color: #667eea;
            background: #eff6ff;
            color: #667eea;
        }
        
        .balance-summary {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border: 2px solid #86efac;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1.5rem;
        }
        
        .balance-summary.unbalanced {
            background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
            border-color: #fca5a5;
        }
        
        .balance-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            font-size: 1.1rem;
        }
        
        .balance-row.total {
            border-top: 2px solid #86efac;
            padding-top: 1rem;
            margin-top: 0.5rem;
            font-weight: 700;
            font-size: 1.25rem;
        }
        
        .balance-summary.unbalanced .balance-row.total {
            border-top-color: #fca5a5;
        }
        
        .balance-label {
            color: #166534;
        }
        
        .balance-summary.unbalanced .balance-label {
            color: #991b1b;
        }
        
        .balance-amount {
            font-weight: 700;
            color: #15803d;
        }
        
        .balance-summary.unbalanced .balance-amount {
            color: #dc2626;
        }
        
        .form-label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .required {
            color: #ef4444;
        }
        
        .info-box {
            background: #eff6ff;
            border: 1px solid #bfdbfe;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .info-box i {
            color: #3b82f6;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Create Journal Entry</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="journal_entries.php">Journal Entries</a></li>
                                        <li class="breadcrumb-item active">Create Entry</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong><i class="ri-error-warning-line me-2"></i>Error!</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong><i class="ri-checkbox-circle-line me-2"></i>Success!</strong>
                        <div class="mt-2"><?php echo $success_message; ?></div>
                        <div class="mt-3">
                            <a href="journal_entries.php" class="btn btn-sm btn-primary">
                                <i class="ri-file-list-line me-1"></i> View All Journal Entries
                            </a>
                            <a href="general_ledger.php" class="btn btn-sm btn-success">
                                <i class="ri-book-line me-1"></i> View General Ledger
                            </a>
                            <a href="create_journal_entry.php" class="btn btn-sm btn-secondary">
                                <i class="ri-add-line me-1"></i> Create Another Entry
                            </a>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="info-box">
                        <i class="ri-information-line me-2"></i>
                        <strong>Manual Journal Entry:</strong> Create accounting entries for adjustments, corrections, or transactions not automatically generated by the system. Ensure debits equal credits before posting.
                    </div>

                    <form id="journalEntryForm" method="POST">
                        <!-- Entry Header -->
                        <div class="journal-card">
                            <div class="journal-header">
                                <h5 class="mb-0">
                                    <i class="ri-file-text-line me-2"></i>Journal Entry Details
                                </h5>
                            </div>
                            <div class="journal-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Entry Date <span class="required">*</span></label>
                                        <input type="date" class="form-control" name="entry_date" 
                                               value="<?php echo $_POST['entry_date'] ?? date('Y-m-d'); ?>" 
                                               max="<?php echo date('Y-m-d'); ?>" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Fiscal Period</label>
                                        <input type="text" class="form-control" id="fiscalPeriod" readonly 
                                               value="<?php echo date('F Y'); ?>">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">Description <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="description" 
                                               value="<?php echo htmlspecialchars($_POST['description'] ?? ''); ?>"
                                               placeholder="Brief description of this journal entry" required>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="notes" rows="2" 
                                                  placeholder="Additional notes or explanation (optional)"><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Journal Lines -->
                        <div class="journal-card">
                            <div class="journal-header">
                                <h5 class="mb-0">
                                    <i class="ri-list-check me-2"></i>Journal Entry Lines
                                </h5>
                            </div>
                            <div class="journal-body">
                                <div id="journalLinesContainer">
                                    <!-- Line 1 -->
                                    <div class="journal-line-row" data-line="1">
                                        <div class="line-number">1</div>
                                        <div class="row" style="margin-top: 2rem;">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Account <span class="required">*</span></label>
                                                <select class="form-select account-select" name="account_id_1" required>
                                                    <option value="">Select Account</option>
                                                    <?php 
                                                    $accounts_result->data_seek(0);
                                                    while ($account = $accounts_result->fetch_assoc()): 
                                                    ?>
                                                        <option value="<?php echo $account['account_id']; ?>" 
                                                                data-normal="<?php echo $account['normal_balance']; ?>">
                                                            <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Debit</label>
                                                <input type="number" class="form-control debit-input" name="debit_1" 
                                                       step="0.01" min="0" placeholder="0.00">
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Credit</label>
                                                <input type="number" class="form-control credit-input" name="credit_1" 
                                                       step="0.01" min="0" placeholder="0.00">
                                            </div>
                                            <div class="col-md-2 mb-3">
                                                <label class="form-label">Normal</label>
                                                <input type="text" class="form-control normal-balance-display" readonly placeholder="-">
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-12 mb-3">
                                                <label class="form-label">Line Description</label>
                                                <input type="text" class="form-control" name="line_description_1" 
                                                       placeholder="Optional description for this line">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Line 2 -->
                                    <div class="journal-line-row" data-line="2">
                                        <div class="line-number">2</div>
                                        <div class="row" style="margin-top: 2rem;">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Account <span class="required">*</span></label>
                                                <select class="form-select account-select" name="account_id_2" required>
                                                    <option value="">Select Account</option>
                                                    <?php 
                                                    $accounts_result->data_seek(0);
                                                    while ($account = $accounts_result->fetch_assoc()): 
                                                    ?>
                                                        <option value="<?php echo $account['account_id']; ?>" 
                                                                data-normal="<?php echo $account['normal_balance']; ?>">
                                                            <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Debit</label>
                                                <input type="number" class="form-control debit-input" name="debit_2" 
                                                       step="0.01" min="0" placeholder="0.00">
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Credit</label>
                                                <input type="number" class="form-control credit-input" name="credit_2" 
                                                       step="0.01" min="0" placeholder="0.00">
                                            </div>
                                            <div class="col-md-2 mb-3">
                                                <label class="form-label">Normal</label>
                                                <input type="text" class="form-control normal-balance-display" readonly placeholder="-">
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-12 mb-3">
                                                <label class="form-label">Line Description</label>
                                                <input type="text" class="form-control" name="line_description_2" 
                                                       placeholder="Optional description for this line">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <button type="button" class="add-line-btn" id="addLineBtn">
                                    <i class="ri-add-line me-2"></i>Add Another Line
                                </button>
                                
                                <!-- Balance Summary -->
                                <div class="balance-summary" id="balanceSummary">
                                    <h6 class="balance-label mb-3">
                                        <i class="ri-calculator-line me-2"></i>Entry Summary
                                    </h6>
                                    <div class="balance-row">
                                        <span class="balance-label">Total Debits:</span>
                                        <span class="balance-amount" id="totalDebits">KES 0.00</span>
                                    </div>
                                    <div class="balance-row">
                                        <span class="balance-label">Total Credits:</span>
                                        <span class="balance-amount" id="totalCredits">KES 0.00</span>
                                    </div>
                                    <div class="balance-row total">
                                        <span class="balance-label">Difference:</span>
                                        <span class="balance-amount" id="difference">KES 0.00</span>
                                    </div>
                                    <div class="mt-2 text-center">
                                        <span class="badge bg-success" id="balanceStatus" style="display: none; font-size: 1rem; padding: 0.5rem 1rem;">
                                            <i class="ri-checkbox-circle-line me-1"></i>BALANCED
                                        </span>
                                        <span class="badge bg-danger" id="unbalancedStatus" style="display: none; font-size: 1rem; padding: 0.5rem 1rem;">
                                            <i class="ri-close-circle-line me-1"></i>UNBALANCED
                                        </span>
                                    </div>
                                </div>
                                
                                <input type="hidden" name="line_count" id="lineCount" value="2">
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="journal-card">
                            <div class="journal-body">
                                <div class="d-flex justify-content-between">
                                    <a href="journal_entries.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back
                                    </a>
                                    <div>
                                        <button type="button" class="btn btn-secondary me-2" onclick="resetForm()">
                                            <i class="ri-refresh-line me-1"></i> Reset
                                        </button>
                                        <button type="submit" class="btn btn-primary" id="submitBtn">
                                            <i class="ri-save-line me-1"></i> Create & Post Entry
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    let lineCounter = 2;
    
    // Account options HTML for cloning
    const accountOptionsHTML = `
        <option value="">Select Account</option>
        <?php 
        $accounts_result->data_seek(0);
        while ($account = $accounts_result->fetch_assoc()): 
        ?>
            <option value="<?php echo $account['account_id']; ?>" 
                    data-normal="<?php echo $account['normal_balance']; ?>">
                <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name']); ?>
            </option>
        <?php endwhile; ?>
    `;
    
    document.addEventListener('DOMContentLoaded', function() {
        // Update fiscal period when date changes
        document.querySelector('input[name="entry_date"]').addEventListener('change', function() {
            const date = new Date(this.value);
            const months = ['January', 'February', 'March', 'April', 'May', 'June', 
                          'July', 'August', 'September', 'October', 'November', 'December'];
            const fiscalPeriod = months[date.getMonth()] + ' ' + date.getFullYear();
            document.getElementById('fiscalPeriod').value = fiscalPeriod;
        });
        
        // Add line button
        document.getElementById('addLineBtn').addEventListener('click', function() {
            lineCounter++;
            addJournalLine(lineCounter);
            updateBalances();
        });
        
        // Calculate balances on input
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('debit-input') || e.target.classList.contains('credit-input')) {
                updateBalances();
            }
        });
        
        // Show normal balance when account selected
        document.addEventListener('change', function(e) {
            if (e.target.classList.contains('account-select')) {
                const selectedOption = e.target.options[e.target.selectedIndex];
                const normalBalance = selectedOption.getAttribute('data-normal');
                const lineRow = e.target.closest('.journal-line-row');
                const normalDisplay = lineRow.querySelector('.normal-balance-display');
                
                if (normalBalance) {
                    normalDisplay.value = normalBalance;
                    normalDisplay.style.background = normalBalance === 'DEBIT' ? '#d1fae5' : '#fee2e2';
                    normalDisplay.style.color = normalBalance === 'DEBIT' ? '#065f46' : '#991b1b';
                    normalDisplay.style.fontWeight = '600';
                } else {
                    normalDisplay.value = '';
                    normalDisplay.style.background = '';
                    normalDisplay.style.color = '';
                }
            }
        });
        
        // Prevent both debit and credit on same line
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('debit-input')) {
                const lineRow = e.target.closest('.journal-line-row');
                const creditInput = lineRow.querySelector('.credit-input');
                if (parseFloat(e.target.value) > 0) {
                    creditInput.value = '';
                    creditInput.disabled = true;
                } else {
                    creditInput.disabled = false;
                }
            }
            
            if (e.target.classList.contains('credit-input')) {
                const lineRow = e.target.closest('.journal-line-row');
                const debitInput = lineRow.querySelector('.debit-input');
                if (parseFloat(e.target.value) > 0) {
                    debitInput.value = '';
                    debitInput.disabled = true;
                } else {
                    debitInput.disabled = false;
                }
            }
        });
        
        // Form submission validation
        document.getElementById('journalEntryForm').addEventListener('submit', function(e) {
            const totalDebits = calculateTotalDebits();
            const totalCredits = calculateTotalCredits();
            const difference = Math.abs(totalDebits - totalCredits);
            
            if (difference > 0.01) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Entry Not Balanced',
                    html: `Total debits (KES ${formatNumber(totalDebits)}) must equal total credits (KES ${formatNumber(totalCredits)}).<br><br>
                           <strong>Difference: KES ${formatNumber(difference)}</strong>`,
                    confirmButtonColor: '#667eea'
                });
                return false;
            }
            
            if (totalDebits === 0 && totalCredits === 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'No Amounts Entered',
                    text: 'Please enter debit and credit amounts for your journal entry.',
                    confirmButtonColor: '#667eea'
                });
                return false;
            }
            
            // Show loading
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.innerHTML = '<i class="ri-loader-2-line spinner-border spinner-border-sm me-1"></i> Creating & Posting...';
            submitBtn.disabled = true;
        });
        
        // Initial balance calculation
        updateBalances();
    });
    
    function addJournalLine(lineNumber) {
        const container = document.getElementById('journalLinesContainer');
        
        const lineHTML = `
            <div class="journal-line-row" data-line="${lineNumber}">
                <div class="line-number">${lineNumber}</div>
                <button type="button" class="remove-line-btn" onclick="removeLine(${lineNumber})">
                    <i class="ri-close-line"></i>
                </button>
                <div class="row" style="margin-top: 2rem;">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Account <span class="required">*</span></label>
                        <select class="form-select account-select" name="account_id_${lineNumber}" required>
                            ${accountOptionsHTML}
                        </select>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Debit</label>
                        <input type="number" class="form-control debit-input" name="debit_${lineNumber}" 
                               step="0.01" min="0" placeholder="0.00">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Credit</label>
                        <input type="number" class="form-control credit-input" name="credit_${lineNumber}" 
                               step="0.01" min="0" placeholder="0.00">
                    </div>
                    <div class="col-md-2 mb-3">
                        <label class="form-label">Normal</label>
                        <input type="text" class="form-control normal-balance-display" readonly placeholder="-">
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 mb-3">
                        <label class="form-label">Line Description</label>
                        <input type="text" class="form-control" name="line_description_${lineNumber}" 
                               placeholder="Optional description for this line">
                    </div>
                </div>
            </div>
        `;
        
        container.insertAdjacentHTML('beforeend', lineHTML);
        document.getElementById('lineCount').value = lineNumber;
    }
    
    function removeLine(lineNumber) {
        const lineRows = document.querySelectorAll('.journal-line-row');
        
        if (lineRows.length <= 2) {
            Swal.fire({
                icon: 'warning',
                title: 'Cannot Remove',
                text: 'At least 2 journal lines are required.',
                confirmButtonColor: '#667eea'
            });
            return;
        }
        
        Swal.fire({
            title: 'Remove Line?',
            text: 'Are you sure you want to remove this journal line?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#667eea',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, remove it'
        }).then((result) => {
            if (result.isConfirmed) {
                const lineRow = document.querySelector(`[data-line="${lineNumber}"]`);
                lineRow.remove();
                
                // Renumber remaining lines
                const remainingLines = document.querySelectorAll('.journal-line-row');
                remainingLines.forEach((line, index) => {
                    const newNumber = index + 1;
                    line.setAttribute('data-line', newNumber);
                    line.querySelector('.line-number').textContent = newNumber;
                    
                    // Update input names
                    line.querySelector('.account-select').name = `account_id_${newNumber}`;
                    line.querySelector('.debit-input').name = `debit_${newNumber}`;
                    line.querySelector('.credit-input').name = `credit_${newNumber}`;
                    line.querySelector(`input[name^="line_description"]`).name = `line_description_${newNumber}`;
                    
                    // Update remove button
                    const removeBtn = line.querySelector('.remove-line-btn');
                    if (removeBtn) {
                        removeBtn.setAttribute('onclick', `removeLine(${newNumber})`);
                    }
                });
                
                lineCounter = remainingLines.length;
                document.getElementById('lineCount').value = lineCounter;
                updateBalances();
            }
        });
    }
    
    function calculateTotalDebits() {
        let total = 0;
        document.querySelectorAll('.debit-input').forEach(input => {
            total += parseFloat(input.value) || 0;
        });
        return total;
    }
    
    function calculateTotalCredits() {
        let total = 0;
        document.querySelectorAll('.credit-input').forEach(input => {
            total += parseFloat(input.value) || 0;
        });
        return total;
    }
    
    function updateBalances() {
        const totalDebits = calculateTotalDebits();
        const totalCredits = calculateTotalCredits();
        const difference = Math.abs(totalDebits - totalCredits);
        
        document.getElementById('totalDebits').textContent = 'KES ' + formatNumber(totalDebits);
        document.getElementById('totalCredits').textContent = 'KES ' + formatNumber(totalCredits);
        document.getElementById('difference').textContent = 'KES ' + formatNumber(difference);
        
        const balanceSummary = document.getElementById('balanceSummary');
        const balanceStatus = document.getElementById('balanceStatus');
        const unbalancedStatus = document.getElementById('unbalancedStatus');
        const submitBtn = document.getElementById('submitBtn');
        
        if (difference < 0.01 && totalDebits > 0) {
            balanceSummary.classList.remove('unbalanced');
            balanceStatus.style.display = 'inline-block';
            unbalancedStatus.style.display = 'none';
            submitBtn.disabled = false;
        } else {
            balanceSummary.classList.add('unbalanced');
            balanceStatus.style.display = 'none';
            unbalancedStatus.style.display = 'inline-block';
            submitBtn.disabled = totalDebits === 0 && totalCredits === 0 ? false : true;
        }
    }
    
    function formatNumber(num) {
        return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    function resetForm() {
        Swal.fire({
            title: 'Reset Form?',
            text: 'This will clear all entered data.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#667eea',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, reset it'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('journalEntryForm').reset();
                
                // Remove extra lines
                const lineRows = document.querySelectorAll('.journal-line-row');
                lineRows.forEach((line, index) => {
                    if (index > 1) {
                        line.remove();
                    }
                });
                
                lineCounter = 2;
                document.getElementById('lineCount').value = 2;
                
                // Reset normal balance displays
                document.querySelectorAll('.normal-balance-display').forEach(display => {
                    display.value = '';
                    display.style.background = '';
                    display.style.color = '';
                });
                
                // Enable all inputs
                document.querySelectorAll('.debit-input, .credit-input').forEach(input => {
                    input.disabled = false;
                });
                
                updateBalances();
                
                Swal.fire({
                    icon: 'success',
                    title: 'Form Reset',
                    timer: 1500,
                    showConfirmButton: false
                });
            }
        });
    }
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>