<?php
session_start();
require_once '../config/db.php';

function loadFromSession() {
    if (isset($_SESSION['accounting_data'])) {
        return $_SESSION['accounting_data'];
    }
    return null;
}

// Add this where you initialize your page data
$sessionData = loadFromSession();

// Check admin access
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}

// Fetch company details
$stmt = $pdo->prepare("SELECT pharmacy_name FROM settings LIMIT 1");
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name';

// Get date range
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Fetch accounting data
function fetchAccountingData($pdo, $startDate, $endDate) {
    $query = "
        SELECT 
            DATE(sale_date) as date,
            SUM(total) as revenue,
            SUM(profit) as gross_profit,
            SUM(total - profit) as cost_of_goods, -- Calculate COGS from total and profit
            SUM(discount) as discounts,
            payment_method1,
            payment_method2,
            SUM(payment_amount1) as amount1,
            SUM(payment_amount2) as amount2
        FROM sales 
        WHERE sale_date BETWEEN ? AND ?
        GROUP BY DATE(sale_date), payment_method1, payment_method2
        ORDER BY date DESC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$startDate, $endDate]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Update fetchBalanceSheetData function
function fetchBalanceSheetData($pdo) {
    $query = "
        SELECT 
            SUM(d.quantity * d.selling_price) as inventory_value,
            (SELECT SUM(payment_amount1 + COALESCE(payment_amount2, 0)) 
             FROM sales 
             WHERE payment_method1 = 'Cash' OR payment_method2 = 'Cash') as cash_on_hand,
            (SELECT SUM(amount) FROM expenses) as total_liabilities
        FROM drugs d";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Update fetchCashFlowData function
function fetchCashFlowData($pdo, $startDate, $endDate) {
    $query = "
        SELECT 
            SUM(CASE WHEN payment_method1 = 'Cash' THEN payment_amount1 ELSE 0 END +
                CASE WHEN payment_method2 = 'Cash' THEN payment_amount2 ELSE 0 END) as cash_receipts,
            (SELECT SUM(amount) FROM expenses 
             WHERE expense_date BETWEEN ? AND ?) as cash_payments
        FROM sales 
        WHERE sale_date BETWEEN ? AND ?";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$startDate, $endDate, $startDate, $endDate]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Calculate financial ratios
function calculateFinancialRatios($totalRevenue, $totalGrossProfit, $totalCogs, $balanceSheet) {
    return [
        'gross_profit_margin' => $totalRevenue > 0 ? ($totalGrossProfit / $totalRevenue) * 100 : 0,
        'inventory_turnover' => $balanceSheet['inventory_value'] > 0 ? ($totalCogs / $balanceSheet['inventory_value']) : 0,
        'operating_margin' => $totalRevenue > 0 ? (($totalGrossProfit - ($balanceSheet['total_liabilities'] ?? 0)) / $totalRevenue) * 100 : 0,
        'cash_ratio' => ($balanceSheet['total_liabilities'] ?? 1) > 0 ? ($balanceSheet['cash_on_hand'] / $balanceSheet['total_liabilities']) : 0
    ];
}

// Add after existing functions

function saveAccountingEntry($pdo, $section, $description, $amount, $type, $date) {
    try {
        $query = "INSERT INTO accounting_entries 
                  (section, description, amount, entry_type, entry_date) 
                  VALUES (?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($query);
        return $stmt->execute([$section, $description, $amount, $type, $date]);
    } catch (PDOException $e) {
        error_log("Error saving accounting entry: " . $e->getMessage());
        return false;
    }
}

function getCustomEntries($pdo, $section, $startDate, $endDate) {
    try {
        $stmt = $pdo->prepare("
            SELECT * FROM accounting_templates 
            WHERE section = ? 
            AND is_active = 1 
            ORDER BY id DESC
        ");
        $stmt->execute([$section]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Error fetching entries: " . $e->getMessage());
        return [];
    }
}

// Add this new function to get section templates
function getSectionTemplates($pdo, $section) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM accounting_templates WHERE section = ? AND is_active = 1");
        $stmt->execute([$section]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Error fetching templates: " . $e->getMessage());
        return [];
    }
}

// Fetch additional data
$accountingData = fetchAccountingData($pdo, $startDate, $endDate);

// Calculate totals from accounting data
$totalRevenue = 0;
$totalCogs = 0;
$totalDiscounts = 0;
$totalGrossProfit = 0;

foreach ($accountingData as $data) {
    $totalRevenue += $data['revenue'] ?? 0;
    $totalCogs += $data['cost_of_goods'] ?? 0;
    $totalDiscounts += $data['discounts'] ?? 0;
    $totalGrossProfit += $data['gross_profit'] ?? 0;
}

// Then fetch the rest of the data
$balanceSheetData = fetchBalanceSheetData($pdo);
$cashFlowData = fetchCashFlowData($pdo, $startDate, $endDate);
$financialRatios = calculateFinancialRatios($totalRevenue, $totalGrossProfit, $totalCogs, $balanceSheetData);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Accounting - <?= htmlspecialchars($pharmacy_name) ?></title>
    <link rel="stylesheet" href="..\libs\bootsrtap2\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <style>
        /* Add custom styling for accounting page */
        .accounting-nav {
            background: #2c3e50;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 2rem;
        }

        .accounting-nav .nav-link {
            color: #fff;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            margin: 0 0.5rem;
        }

        .accounting-nav .nav-link.active {
            background: #fff;
            color: #2c3e50;
        }

        .financial-statement {
            background: #fff;
            border-radius: 8px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .statement-header {
            text-align: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #eee;
        }

        .account-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid #eee;
        }

        .account-row:hover {
            background: #f8f9fa;
        }

        .account-group {
            margin-bottom: 2rem;
        }

        .account-total {
            font-weight: bold;
            border-top: 2px solid #000;
            margin-top: 1rem;
        }

        .ratio-card {
            background: #fff;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .ratio-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #1a237e;
        }

        /* Update existing styles */
        .main-content {
            margin-left: 230px;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }

        .main-navbar {
            background: #fff;
            padding: 1rem;
            margin-bottom: 2rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* Mobile responsive styles */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
            
            .sidebar.active + .main-content {
                margin-left: 230px;
            }
        }

        /* Print styles */
        @media print {
            .no-print, 
            .btn,
            .statement-controls,
            .accounting-nav,
            input[type="number"],
            input[type="text"] {
                display: none !important;
            }

            .print-only-value,
            .print-only-desc {
                display: inline-block !important;
            }

            .print-only-value {
                text-align: right;
                min-width: 100px;
            }

            .account-row {
                display: flex;
                justify-content: space-between;
                padding: 4px 0;
                border-bottom: 1px solid #eee;
            }

            .financial-statement {
                padding: 20px;
                margin: 0;
                box-shadow: none;
                border: none;
            }

            body {
                padding: 0;
                margin: 0;
            }

            .wrapper {
                margin: 0;
                padding: 0;
            }

            .main-content {
                margin-left: 0;
                padding: 0;
            }

            .statement-header {
                margin-bottom: 30px;
            }

            .account-total {
                margin-top: 10px;
                border-top: 2px solid #000;
                padding-top: 10px;
                font-weight: bold;
            }
        }

        .statement-controls {
            position: sticky;
            top: 0;
            background: white;
            padding: 10px;
            z-index: 100;
            border-bottom: 1px solid #eee;
        }

        .account-row {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
            transition: all 0.3s ease;
        }

        .account-row:hover {
            background: #f8f9fa;
        }

        .field-controls {
            display: flex;
            align-items: center;
            opacity: 0;
            transition: opacity 0.2s;
        }

        .account-row:hover .field-controls {
            opacity: 1;
        }

        .amount-input {
            text-align: right;
            width: 150px !important;
        }

        .processed-value {
            font-weight: 500;
            color: #2c3e50;
        }

        @media print {
            .d-print-none {
                display: none !important;
            }
            
            .account-row {
                break-inside: avoid;
            }
            
            .field-controls {
                display: none !important;
            }
        }

        /* Add to your existing styles */
        .section-title {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 1rem;
            border-bottom: 2px solid #eee;
            padding-bottom: 0.5rem;
        }

        .indent-dot {
            width: 20px;
            color: #666;
            font-size: 1.2em;
            margin-right: 8px;
        }

        .indent-total {
            margin-left: 28px;
            font-weight: 500;
            color: #2c3e50;
        }

        .account-row {
            padding: 6px 0;
            margin-left: 15px;
        }

        .account-subtotal {
            margin-left: 0;
            border-top: 1px solid #dee2e6;
            margin-top: 10px;
            padding-top: 10px;
        }

        .total-value {
            font-weight: 600;
            color: #2c3e50;
        }

        .account-subgroup {
            margin-bottom: 2rem;
            padding-left: 15px;
        }

        .account-group > h5 {
            color: #1a237e;
            border-bottom: 2px solid #1a237e;
            padding-bottom: 0.5rem;
            margin-bottom: 1.5rem;
        }
        .account-row {
    padding: 8px 0;
    position: relative;
}

.dots {
    color: #ccc;
    margin: 0 8px;
    letter-spacing: 3px;
}

.amount-input {
    width: 150px !important;
    text-align: right;
}

.amount {
    min-width: 120px;
    text-align: right;
    font-weight: 500;
}

.subtotal {
    border-top: 1px solid #dee2e6;
    margin-top: 10px;
    padding-top: 10px;
    font-weight: 500;
}

.total {
    border-top: 2px solid #000;
    margin-top: 15px;
    padding-top: 15px;
    font-weight: 600;
}

.account-subgroup {
    margin-bottom: 30px;
}

.account-subgroup h6 {
    color: #495057;
    margin-bottom: 15px;
}

@media print {
    .amount-input {
        border: none;
        background: none;
        pointer-events: none;
    }
    
    .account-row:not(.subtotal):not(.total) {
        page-break-inside: avoid;
    }
}
    </style>
</head>
<body class="bg-light">
    <?php include '../includes/side_bar.php'; ?>

    <div class="wrapper">
        <div class="main-content">
            <!-- Top Navigation -->
            <nav class="navbar navbar-expand-lg main-navbar">
                <div class="container-fluid">
                    <div class="navbar-brand">
                        <h4 class="mb-0">Accounting</h4>
                    </div>
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            <button class="btn btn-primary" onclick="window.print()">
                                <i class="fas fa-print"></i> Print Report
                            </button>
                        </li>
                    </ul>
                </div>
            </nav>

            <div class="container">
                <!-- Date Filter -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Start Date</label>
                                <input type="date" name="start_date" class="form-control" value="<?= $startDate ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">End Date</label>
                                <input type="date" name="end_date" class="form-control" value="<?= $endDate ?>">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary">Apply Filter</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Financial Statements Navigation -->
                <ul class="nav nav-pills accounting-nav mb-4">
                    <li class="nav-item">
                        <a class="nav-link active" data-bs-toggle="pill" href="#income">Income Statement</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="pill" href="#balance">Statement of Financial Position</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="pill" href="#cashflow">Cash Flow</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="pill" href="#ratios">Financial Ratios</a>
                    </li>
                </ul>

                <!-- Financial Statements Content -->
                <div class="tab-content">
                    <!-- Income Statement (Statement of Profit or Loss) -->
                    <div class="tab-pane fade show active" id="income">
                        <div class="financial-statement">
                            <div class="statement-header">
                                <h3><?= htmlspecialchars($pharmacy_name) ?></h3>
                                <h4>Statement of Profit or Loss</h4>
                                <p>For the period <?= date('F j, Y', strtotime($startDate)) ?> to <?= date('F j, Y', strtotime($endDate)) ?></p>
                            </div>

                            <!-- Add this section buttons at the top of each statement -->
                            <div class="statement-controls mb-3 d-print-none">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-primary" onclick="addNewField(currentSection)">
                                        <i class="fas fa-plus"></i> Add Field
                                    </button>
                                    <button type="button" class="btn btn-success" onclick="updateTotals()">
                                        <i class="fas fa-calculator"></i> Calculate
                                    </button>
                                    <button type="button" class="btn btn-secondary" onclick="generatePDF()">
                                        <i class="fas fa-file-pdf"></i> Save as PDF
                                    </button>
                                    <button type="button" class="btn btn-info" onclick="window.print()">
                                        <i class="fas fa-print"></i> Print
                                    </button>
                                    <button type="button" class="btn btn-primary" onclick="saveToSession()">
                                        <i class="fas fa-save"></i> Save to Session
                                    </button>
                                </div>
                            </div>

                            <!-- Revenue Section -->
                            <div class="account-group">
                                <h5 class="d-flex justify-content-between align-items-center">
                                    Revenue
                                    <button type="button" class="btn btn-primary btn-sm" onclick="addNewField('revenue-section')">
                                        <i class="fas fa-plus"></i> Add Revenue Item
                                    </button>
                                </h5>
                                <div class="row mb-3" id="revenue-section">
                                    <div class="col-md-8">
                                        <div class="account-row">
                                            <span>Sales of Goods</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="sales_revenue" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Service Revenue</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="service_revenue" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Other Operating Revenue</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="other_revenue" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row account-total">
                                            <span>Total Revenue</span>
                                            <span id="total_revenue">₦0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Cost of Sales -->
                            <div class="account-group">
                                <h5 class="d-flex justify-content-between align-items-center">
                                    Cost of Sales
                                    <button type="button" class="btn btn-primary btn-sm" onclick="addNewField('cogs-section')">
                                        <i class="fas fa-plus"></i> Add Cost Item
                                    </button>
                                </h5>
                                <div class="row mb-3" id="cogs-section">
                                    <div class="col-md-8">
                                        <div class="account-row">
                                            <span>Opening Inventory</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="opening_inventory" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Purchases</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="purchases" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Closing Inventory</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="closing_inventory" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row account-total">
                                            <span>Cost of Sales</span>
                                            <span id="total_cost_of_sales">₦0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Gross Profit -->
                            <div class="account-group">
                                <div class="account-row account-total">
                                    <span><strong>Gross Profit</strong></span>
                                    <span id="gross_profit">₦0.00</span>
                                </div>
                            </div>

                            <!-- Operating Expenses -->
                            <div class="account-group">
                                <h5 class="d-flex justify-content-between align-items-center">
                                    Operating Expenses
                                    <button type="button" class="btn btn-primary btn-sm" onclick="addNewField('opex-section')">
                                        <i class="fas fa-plus"></i> Add Expense Item
                                    </button>
                                </h5>
                                <div class="row mb-3" id="opex-section">
                                    <div class="col-md-8">
                                        <div class="account-row">
                                            <span>Employee Benefits Expense</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="employee_expense" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Depreciation and Amortisation</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="depreciation" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Rental Expense</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="rental" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Utilities</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="utilities" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row">
                                            <span>Other Operating Expenses</span>
                                            <input type="number" class="form-control form-control-sm w-25" 
                                                   name="other_expenses" onchange="updateTotals()">
                                        </div>
                                        <div class="account-row account-total">
                                            <span>Total Operating Expenses</span>
                                            <span id="total_operating_expenses">₦0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Operating Profit -->
                            <div class="account-group">
                                <div class="account-row account-total">
                                    <span><strong>Operating Profit</strong></span>
                                    <span id="operating_profit">₦0.00</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Balance Sheet -->
                    <div class="tab-pane fade" id="balance">
                        <div class="financial-statement">
                            <div class="statement-header">
                                <h3><?= htmlspecialchars($pharmacy_name) ?></h3>
                                <h4>Balance Sheet</h4>
                                <p>As of <?= date('F j, Y', strtotime($endDate)) ?></p>
                            </div>

                            <!-- Add this section buttons at the top of each statement -->
                            <div class="statement-controls mb-3 d-print-none">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-primary" onclick="addNewField(currentSection)">
                                        <i class="fas fa-plus"></i> Add Field
                                    </button>
                                    <button type="button" class="btn btn-success" onclick="processStatement()">
                                        <i class="fas fa-calculator"></i> Calculate
                                    </button>
                                    <button type="button" class="btn btn-info" onclick="toggleEditMode()">
                                        <i class="fas fa-edit"></i> Edit Mode
                                    </button>
                                    <button type="button" class="btn btn-secondary" onclick="window.print()">
                                        <i class="fas fa-print"></i> Print
                                    </button>
                                </div>
                            </div>

                            <!-- Assets Section -->
                            <div class="account-group">
                                <h5>Assets</h5>
                                
                                <!-- Non-current Assets -->
                                <div class="account-subgroup">
                                    <h6 class="section-title">Non-current Assets:</h6>
                                    <div class="account-rows" id="non-current-assets">
                                        <div class="account-row">
                                            <div class="d-flex align-items-center justify-content-between w-100">
                                                <div class="d-flex align-items-center">
                                                    <span class="dots">.......</span>
                                                    <span>Property, Plant and Equipment</span>
                                                </div>
                                                <input type="number" class="form-control form-control-sm amount-input" 
                                                       name="ppe" onchange="updateBalanceSheet()">
                                            </div>
                                        </div>
                                        <!-- Additional non-current assets will be added here -->
                                    </div>
                                    <div class="account-row subtotal">
                                        <div class="d-flex align-items-center justify-content-between w-100">
                                            <span>Total Non-current Assets</span>
                                            <span class="amount" id="total_non_current_assets">₦0.00</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Current Assets -->
                                <div class="account-subgroup">
                                    <h6>Current Assets:</h6>
                                    <div class="account-rows" id="current-assets">
                                        <!-- Similar structure for current assets -->
                                    </div>
                                    <div class="account-row subtotal">
                                        <div class="d-flex align-items-center justify-content-between w-100">
                                            <span>Total Current Assets</span>
                                            <span class="amount" id="total_current_assets">₦0.00</span>
                                        </div>
                                    </div>
                                </div>

                                <div class="account-row total">
                                    <div class="d-flex align-items-center justify-content-between w-100">
                                        <span>Total Assets</span>
                                        <span class="amount" id="total_assets">₦0.00</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Cash Flow -->
                    <div class="tab-pane fade" id="cashflow">
                        <div class="financial-statement">
                            <div class="statement-header">
                                <h3><?= htmlspecialchars($pharmacy_name) ?></h3>
                                <h4>Cash Flow Statement</h4>
                                <p>For the period <?= date('F j, Y', strtotime($startDate)) ?> to <?= date('F j, Y', strtotime($endDate)) ?></p>
                            </div>

                            <!-- Add this section buttons at the top of each statement -->
                            <div class="statement-controls mb-3 d-print-none">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-primary" onclick="addNewField(currentSection)">
                                        <i class="fas fa-plus"></i> Add Field
                                    </button>
                                    <button type="button" class="btn btn-success" onclick="processStatement()">
                                        <i class="fas fa-calculator"></i> Calculate
                                    </button>
                                    <button type="button" class="btn btn-info" onclick="toggleEditMode()">
                                        <i class="fas fa-edit"></i> Edit Mode
                                    </button>
                                    <button type="button" class="btn btn-secondary" onclick="window.print()">
                                        <i class="fas fa-print"></i> Print
                                    </button>
                                </div>
                            </div>

                            <!-- Operating Activities -->
                            <div class="account-group">
                                <h5>Operating Activities</h5>
                                <div class="account-row">
                                    <span>Cash Receipts from Customers</span>
                                    <span>₦<?= number_format($cashFlowData['cash_receipts'], 2) ?></span>
                                </div>
                                <div class="account-row">
                                    <span>Cash Payments for Expenses</span>
                                    <span>₦<?= number_format($cashFlowData['cash_payments'], 2) ?></span>
                                </div>
                                <div class="account-row account-total">
                                    <span>Net Cash from Operations</span>
                                    <span>₦<?= number_format($cashFlowData['cash_receipts'] - $cashFlowData['cash_payments'], 2) ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Financial Ratios -->
                    <div class="tab-pane fade" id="ratios">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="ratio-card">
                                    <h5>Gross Profit Margin</h5>
                                    <div class="ratio-value">
                                        <?= number_format($financialRatios['gross_profit_margin'], 2) ?>%
                                    </div>
                                    <small class="text-muted">Net Sales vs Cost of Goods</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="ratio-card">
                                    <h5>Inventory Turnover</h5>
                                    <div class="ratio-value">
                                        <?= number_format($financialRatios['inventory_turnover'], 2) ?>x
                                    </div>
                                    <small class="text-muted">COGS / Average Inventory</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="ratio-card">
                                    <h5>Operating Margin</h5>
                                    <div class="ratio-value">
                                        <?= number_format($financialRatios['operating_margin'], 2) ?>%
                                    </div>
                                    <small class="text-muted">Operating Income / Revenue</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="ratio-card">
                                    <h5>Cash Ratio</h5>
                                    <div class="ratio-value">
                                        <?= number_format($financialRatios['cash_ratio'], 2) ?>
                                    </div>
                                    <small class="text-muted">Cash / Current Liabilities</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div> <!-- End of main-content -->
    </div> <!-- End of wrapper -->

    <!-- Add Entry Modal -->
    <div class="modal fade" id="addEntryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Accounting Entry</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="entryForm" onsubmit="saveEntry(event)">
                    <div class="modal-body">
                        <input type="hidden" id="entrySection" name="section">
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <input type="text" class="form-control" name="description" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount</label>
                            <input type="number" class="form-control" name="amount" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Type</label>
                            <select class="form-select" name="type" required>
                                <option value="debit">Debit</option>
                                <option value="credit">Credit</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Date</label>
                            <input type="date" class="form-control" name="date" required>
                        </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 Entry</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap2\js\bootstrap.bundle.min.js"></script>
    <script>
function prepareModal(section) {
    document.getElementById('entrySection').value = section;
}

async function saveEntry(event) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);

    try {
        const response = await fetch('save_accounting_entry.php', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) throw new Error('Network response was not ok');
        const result = await response.json();

        if (result.success) {
            location.reload();
        } else {
            alert(result.message || 'Error saving entry');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error saving entry');
    }
}

async function deleteEntry(id) {
    if (!confirm('Are you sure you want to delete this entry?')) return;

    try {
        const response = await fetch('delete_accounting_entry.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id })
        });

        if (!response.ok) throw new Error('Network response was not ok');
        const result = await response.json();

        if (result.success) {
            location.reload();
        } else {
            alert(result.message || 'Error deleting entry');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error deleting entry');
    }
}

async function saveEntrySimple(event, section) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);
    formData.append('section', section);

    try {
        const response = await fetch('save_accounting_entry.php', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();
        
        if (result.success) {
            location.reload();
        } else {
            throw new Error(result.message || 'Error saving entry');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error saving entry');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // Add change event listeners to all input fields
    document.querySelectorAll('input[type="number"]').forEach(input => {
        input.addEventListener('change', updateTotals);
    });
    
    // Initial calculation
    updateTotals();

    // Populate fields from session data if available
    populateFromSession(<?= json_encode($sessionData) ?>);
});

function updateTotals() {
    // Revenue calculations
    const revenueSection = document.querySelector('#revenue-section');
    let totalRevenue = 0;
    revenueSection.querySelectorAll('input[type="number"]').forEach(input => {
        totalRevenue += parseFloat(input.value) || 0;
    });

    // Cost of Sales calculations
    const cogsSection = document.querySelector('#cogs-section');
    let totalCogs = 0;
    cogsSection.querySelectorAll('input[type="number"]').forEach(input => {
        totalCogs += parseFloat(input.value) || 0;
    });

    // Gross Profit
    const grossProfit = totalRevenue - totalCogs;

    // Operating Expenses calculations
    const opexSection = document.querySelector('#opex-section');
    let totalOperatingExpenses = 0;
    opexSection.querySelectorAll('input[type="number"]').forEach(input => {
        totalOperatingExpenses += parseFloat(input.value) || 0;
    });

    // Operating Profit
    const operatingProfit = grossProfit - totalOperatingExpenses;

    // Update all totals
    updateDisplay('total_revenue', totalRevenue);
    updateDisplay('total_cost_of_sales', totalCogs);
    updateDisplay('gross_profit', grossProfit);
    updateDisplay('total_operating_expenses', totalOperatingExpenses);
    updateDisplay('operating_profit', operatingProfit);
}

function updateBalanceSheet() {
    // Non-current Assets
    const ppe = getInputValue('ppe');
    const intangibleAssets = getInputValue('intangible_assets') || 0;
    const totalNonCurrentAssets = ppe + intangibleAssets;

    // Current Assets
    const inventory = getInputValue('inventory');
    const receivables = getInputValue('receivables');
    const cash = getInputValue('cash');
    const totalCurrentAssets = inventory + receivables + cash;

    // Total Assets
    const totalAssets = totalNonCurrentAssets + totalCurrentAssets;

    // Update Balance Sheet displays
    updateDisplay('total_non_current_assets', totalNonCurrentAssets);
    updateDisplay('total_current_assets', totalCurrentAssets);
    updateDisplay('total_assets', totalAssets);
}

// Helper function to get input values
function getInputValue(name) {
    const input = document.querySelector(`[name="${name}"]`);
    return input ? parseFloat(input.value) || 0 : 0;
}

// Helper function to update display values
function updateDisplay(id, value) {
    const element = document.getElementById(id);
    if (element) {
        element.textContent = formatCurrency(value);
    }
}

// Helper function to format currency
function formatCurrency(value) {
    return `₦${value.toLocaleString('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    })}`;
}

// Function to validate input
function validateInput(input) {
    const value = parseFloat(input.value);
    if (isNaN(value) || value < 0) {
        input.value = 0;
        alert('Please enter a valid positive number');
        return false;
    }
    return true;
}

// Add validation to all number inputs
document.querySelectorAll('input[type="number"]').forEach(input => {
    input.addEventListener('change', function() {
        if (validateInput(this)) {
            updateTotals();
        }
    });
});

let currentSection = 'revenue'; // Track current active section

function addNewField(sectionId) {
    // Get the correct container based on section
    let container;
    switch(sectionId) {
        case 'revenue-section':
        case 'cogs-section':
        case 'opex-section':
            container = document.querySelector(`#${sectionId} .col-md-8`);
            break;
        default:
            console.error('Invalid section ID');
            return;
    }
    
    const totalRow = container.querySelector('.account-total');
    
    const newRow = document.createElement('div');
    newRow.className = 'account-row';
    newRow.innerHTML = `
        <div class="d-flex justify-content-between align-items-center w-100">
            <input type="text" class="form-control form-control-sm w-50 me-2" 
                   placeholder="Enter description">
            <div class="d-flex align-items-center">
                <input type="number" class="form-control form-control-sm w-25" 
                       onchange="updateTotals()" value="0">
                <button type="button" class="btn btn-danger btn-sm ms-2" 
                        onclick="removeField(this)">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    `;
    
    // Insert before the total row
    if (totalRow) {
        container.insertBefore(newRow, totalRow);
    } else {
        container.appendChild(newRow);
    }
    
    // Add event listener to the new number input
    const numberInput = newRow.querySelector('input[type="number"]');
    numberInput.addEventListener('change', updateTotals);
}

function removeField(button) {
    const row = button.closest('.account-row');
    row.remove();
    updateTotals();
}

// Add this function to save to session
function saveToSession() {
    const accountingData = {
        date: document.querySelector('[name="start_date"]').value,
        revenue: collectSectionEntries('revenue-section'),
        costs: collectSectionEntries('cogs-section'),
        expenses: collectSectionEntries('opex-section')
    };

    // Save to session using AJAX
    fetch('save_to_session.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(accountingData)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            alert('Data saved to session successfully');
        } else {
            throw new Error(result.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error saving to session');
    });
}

async function saveAllEntries() {
    const date = document.querySelector('[name="start_date"]').value;
    
    // Collect all entries
    const data = {
        date: date,
        revenue: collectSectionEntries('revenue-section'),
        costs: collectSectionEntries('cogs-section'),
        expenses: collectSectionEntries('opex-section')
    };

    try {
        const response = await fetch('save_accounting_entries.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) throw new Error('Network response was not ok');
        const result = await response.json();

        if (result.success) {
            alert('Entries saved successfully');
        } else {
            throw new Error(result.message || 'Error saving entries');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error saving entries');
    }
}

function collectSectionEntries(sectionId) {
    const entries = [];
    const section = document.querySelector(`#${sectionId}`);
    
    section.querySelectorAll('.account-row:not(.account-total)').forEach(row => {
        const description = row.querySelector('input[type="text"]')?.value || 
                          row.querySelector('span:first-child')?.textContent || 'Untitled';
        const amount = parseFloat(row.querySelector('input[type="number"]')?.value || 0);
        
        if (amount !== 0) {
            entries.push({
                description: description,
                amount: amount
            });
        }
    });
    
    return entries;
}

// Add this function to handle PDF generation
function generatePDF() {
    // First, convert all inputs to static text
    document.querySelectorAll('.account-row').forEach(row => {
        const input = row.querySelector('input[type="number"]');
        const description = row.querySelector('input[type="text"]');
        
        if (input) {
            const value = parseFloat(input.value) || 0;
            const staticValue = document.createElement('span');
            staticValue.className = 'print-only-value';
            staticValue.textContent = formatCurrency(value);
            input.parentNode.insertBefore(staticValue, input);
            input.classList.add('no-print');
        }
        
        if (description) {
            const staticDesc = document.createElement('span');
            staticDesc.className = 'print-only-desc';
            staticDesc.textContent = description.value || 'Untitled Item';
            description.parentNode.insertBefore(staticDesc, description);
            description.classList.add('no-print');
        }
    });

    // Trigger print dialog
    window.print();

    // Remove static elements after printing
    setTimeout(() => {
        document.querySelectorAll('.print-only-value, .print-only-desc').forEach(el => el.remove());
        document.querySelectorAll('.no-print').forEach(el => el.classList.remove('no-print'));
    }, 1000);
}

// Add this function to populate fields from session data
function populateFromSession(sessionData) {
    if (!sessionData) return;

    // Set date
    document.querySelector('[name="start_date"]').value = sessionData.date;

    // Populate revenue entries
    sessionData.revenue.forEach(entry => {
        if (entry.description && entry.amount) {
            addNewFieldWithValues('revenue-section', entry.description, entry.amount);
        }
    });

    // Populate cost entries
    sessionData.costs.forEach(entry => {
        if (entry.description && entry.amount) {
            addNewFieldWithValues('cogs-section', entry.description, entry.amount);
        }
    });

    // Populate expense entries
    sessionData.expenses.forEach(entry => {
        if (entry.description && entry.amount) {
            addNewFieldWithValues('opex-section', entry.description, entry.amount);
        }
    });

    // Update totals
    updateTotals();
}

function addNewFieldWithValues(sectionId, description, amount) {
    const container = document.querySelector(`#${sectionId} .col-md-8`);
    const totalRow = container.querySelector('.account-total');
    
    const newRow = document.createElement('div');
    newRow.className = 'account-row';
    newRow.innerHTML = `
        <div class="d-flex justify-content-between align-items-center w-100">
            <input type="text" class="form-control form-control-sm w-50 me-2" 
                   placeholder="Enter description" value="${description}">
            <div class="d-flex align-items-center">
                <input type="number" class="form-control form-control-sm w-25" 
                       onchange="updateTotals()" value="${amount}">
                <button type="button" class="btn btn-danger btn-sm ms-2" 
                        onclick="removeField(this)">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    `;
    
    if (totalRow) {
        container.insertBefore(newRow, totalRow);
    } else {
        container.appendChild(newRow);
    }
    
    // Add event listener to the new number input
    const numberInput = newRow.querySelector('input[type="number"]');
    numberInput.addEventListener('change', updateTotals);
}
    </script>
    <!-- Add this right before your closing </body> tag -->
<script>
    // Initialize with session data if available
    <?php if ($sessionData): ?>
    document.addEventListener('DOMContentLoaded', function() {
        populateFromSession(<?php echo json_encode($sessionData); ?>);
    });
    <?php endif; ?>
</script>
</body>
</html>