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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_account':
                $account_code = $_POST['account_code'];
                $account_name = $_POST['account_name'];
                $account_type = $_POST['account_type'];
                $account_category = $_POST['account_category'];
                $description = $_POST['description'] ?? '';
                
                $stmt = $conn->prepare("
                    INSERT INTO chart_of_accounts (account_code, account_name, account_type, account_category, description, store_id)
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $stmt->bind_param("sssssi", $account_code, $account_name, $account_type, $account_category, $description, $store_id);
                
                if ($stmt->execute()) {
                    $success_message = "Account added successfully!";
                } else {
                    $error_message = "Error adding account: " . $conn->error;
                }
                break;
                
            case 'update_balance':
                $account_id = $_POST['account_id'];
                $opening_balance = $_POST['opening_balance'];
                
                $stmt = $conn->prepare("
                    UPDATE chart_of_accounts 
                    SET opening_balance = ?, current_balance = ?
                    WHERE id = ? AND store_id = ?
                ");
                $stmt->bind_param("ddii", $opening_balance, $opening_balance, $account_id, $store_id);
                
                if ($stmt->execute()) {
                    $success_message = "Account balance updated successfully!";
                } else {
                    $error_message = "Error updating balance: " . $conn->error;
                }
                break;
        }
    }
}

// Get chart of accounts
$stmt = $conn->prepare("
    SELECT 
        coa.*,
        COALESCE(SUM(CASE WHEN coa.account_type IN ('asset', 'expense') THEN jel.debit_amount - jel.credit_amount ELSE jel.credit_amount - jel.debit_amount END), 0) as calculated_balance
    FROM chart_of_accounts coa
    LEFT JOIN journal_entry_lines jel ON coa.id = jel.account_id
    LEFT JOIN journal_entries je ON jel.journal_entry_id = je.id AND je.status = 'posted'
    WHERE coa.store_id = ?
    GROUP BY coa.id
    ORDER BY coa.account_code
");
$stmt->bind_param("i", $store_id);
$stmt->execute();
$accounts = $stmt->get_result();

// Get account types for dropdown
$account_types = ['asset', 'liability', 'equity', 'revenue', 'expense'];
$account_categories = [
    'current_asset', 'fixed_asset', 'current_liability', 'long_term_liability', 
    'equity', 'revenue', 'cost_of_sales', 'operating_expense', 'other_expense'
];
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="row">
                <div class="col-sm-12">
                    <h3 class="page-title">Chart of Accounts</h3>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                        <li class="breadcrumb-item active">Chart of Accounts</li>
                    </ul>
                </div>
            </div>
        </div>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Add Account Button -->
        <div class="row mb-3">
            <div class="col-12">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addAccountModal">
                    <i class="feather-plus"></i> Add Account
                </button>
                <a href="financial_reports.php" class="btn btn-secondary">
                    <i class="feather-bar-chart-2"></i> Financial Reports
                </a>
            </div>
        </div>

        <!-- Chart of Accounts Table -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Chart of Accounts</h4>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Account Code</th>
                                        <th>Account Name</th>
                                        <th>Type</th>
                                        <th>Category</th>
                                        <th>Opening Balance</th>
                                        <th>Current Balance</th>
                                        <th>Calculated Balance</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($account = $accounts->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($account['account_code']); ?></td>
                                        <td><?php echo htmlspecialchars($account['account_name']); ?></td>
                                        <td>
                                            <span class="badge bg-<?php 
                                                echo $account['account_type'] === 'asset' ? 'primary' : 
                                                    ($account['account_type'] === 'liability' ? 'warning' : 
                                                    ($account['account_type'] === 'equity' ? 'info' : 
                                                    ($account['account_type'] === 'revenue' ? 'success' : 'danger'))); 
                                            ?>">
                                                <?php echo ucfirst($account['account_type']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo ucwords(str_replace('_', ' ', $account['account_category'])); ?></td>
                                        <td><?php echo number_format($account['opening_balance'], 2); ?></td>
                                        <td><?php echo number_format($account['current_balance'], 2); ?></td>
                                        <td class="<?php echo $account['calculated_balance'] < 0 ? 'text-danger' : 'text-success'; ?>">
                                            <?php echo number_format($account['calculated_balance'], 2); ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo $account['is_active'] ? 'success' : 'secondary'; ?>">
                                                <?php echo $account['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                    data-bs-toggle="modal" data-bs-target="#editBalanceModal"
                                                    data-account-id="<?php echo $account['id']; ?>"
                                                    data-account-name="<?php echo htmlspecialchars($account['account_name']); ?>"
                                                    data-opening-balance="<?php echo $account['opening_balance']; ?>">
                                                <i class="feather-edit"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Account Modal -->
<div class="modal fade" id="addAccountModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Account</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_account">
                    
                    <div class="mb-3">
                        <label class="form-label">Account Code</label>
                        <input type="text" name="account_code" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Account Name</label>
                        <input type="text" name="account_name" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Account Type</label>
                        <select name="account_type" class="form-select" required>
                            <option value="">Select Type</option>
                            <?php foreach ($account_types as $type): ?>
                                <option value="<?php echo $type; ?>"><?php echo ucfirst($type); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Account Category</label>
                        <select name="account_category" class="form-select" required>
                            <option value="">Select Category</option>
                            <?php foreach ($account_categories as $category): ?>
                                <option value="<?php echo $category; ?>"><?php echo ucwords(str_replace('_', ' ', $category)); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Account</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Balance Modal -->
<div class="modal fade" id="editBalanceModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Account Balance</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_balance">
                    <input type="hidden" name="account_id" id="editAccountId">
                    
                    <div class="mb-3">
                        <label class="form-label">Account Name</label>
                        <input type="text" id="editAccountName" class="form-control" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Opening Balance</label>
                        <input type="number" name="opening_balance" id="editOpeningBalance" class="form-control" step="0.01" 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">Update Balance</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Handle edit balance modal
document.getElementById('editBalanceModal').addEventListener('show.bs.modal', function (event) {
    var button = event.relatedTarget;
    var accountId = button.getAttribute('data-account-id');
    var accountName = button.getAttribute('data-account-name');
    var openingBalance = button.getAttribute('data-opening-balance');
    
    document.getElementById('editAccountId').value = accountId;
    document.getElementById('editAccountName').value = accountName;
    document.getElementById('editOpeningBalance').value = openingBalance;
});
</script>

<?php include 'footer.php'; ?>
