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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_mapping':
                $mapping_code = $_POST['mapping_code'];
                $mapping_name = $_POST['mapping_name'];
                $account_id = $_POST['account_id'];
                $description = $_POST['description'];
                
                $stmt = $conn->prepare("
                    INSERT INTO account_mappings (
                        mapping_code, mapping_name, account_id, description
                    ) VALUES (?, ?, ?, ?)
                ");
                $stmt->bind_param("ssis", $mapping_code, $mapping_name, $account_id, $description);
                
                if ($stmt->execute()) {
                    $success_message = "Account mapping added successfully!";
                } else {
                    $error_message = "Error adding mapping: " . $conn->error;
                }
                break;
                
            case 'update_mapping':
                $mapping_id = $_POST['mapping_id'];
                $mapping_name = $_POST['mapping_name'];
                $account_id = $_POST['account_id'];
                $description = $_POST['description'];
                $is_active = $_POST['is_active'] ? 1 : 0;
                
                $stmt = $conn->prepare("
                    UPDATE account_mappings 
                    SET mapping_name = ?, account_id = ?, description = ?, is_active = ?
                    WHERE id = ?
                ");
                $stmt->bind_param("sisi", $mapping_name, $account_id, $description, $is_active, $mapping_id);
                
                if ($stmt->execute()) {
                    $success_message = "Account mapping updated successfully!";
                } else {
                    $error_message = "Error updating mapping: " . $conn->error;
                }
                break;
        }
    }
}

// Get mappings for display
$stmt = $conn->prepare("
    SELECT 
        am.*,
        coa.account_code,
        coa.account_name,
        coa.account_type,
        coa.account_category
    FROM account_mappings am
    LEFT JOIN chart_of_accounts coa ON am.account_id = coa.id
    ORDER BY am.mapping_code
");
$stmt->execute();
$mappings = $stmt->get_result();

// Get accounts for dropdown
$stmt = $conn->prepare("
    SELECT id, account_code, account_name, account_type, account_category
    FROM chart_of_accounts 
    WHERE is_active = 1 
    ORDER BY account_code
");
$stmt->execute();
$accounts = $stmt->get_result();
?>

<div class="page-wrapper">
    <div class="content">
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fa fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fa fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <div class="page-header">
            <div class="page-title">
                <h4>Account Mappings</h4>
                <h6>Manage transaction to account mappings</h6>
            </div>
            <div class="page-btn">
                <button class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addMappingModal">
                    <i class="fa fa-plus"></i> Add Mapping
                </button>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table datatable">
                        <thead>
                            <tr>
                                <th>Mapping Code</th>
                                <th>Mapping Name</th>
                                <th>Account</th>
                                <th>Account Type</th>
                                <th>Description</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($mapping = $mappings->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($mapping['mapping_code']); ?></strong>
                                    </td>
                                    <td><?php echo htmlspecialchars($mapping['mapping_name']); ?></td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($mapping['account_code'] . ' - ' . $mapping['account_name']); ?></strong>
                                        <br><small class="text-muted"><?php echo ucwords(str_replace('_', ' ', $mapping['account_category'])); ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo $mapping['account_type'] === 'asset' ? 'success' : 
                                                ($mapping['account_type'] === 'liability' ? 'warning' : 
                                                ($mapping['account_type'] === 'equity' ? 'info' : 
                                                ($mapping['account_type'] === 'revenue' ? 'primary' : 'danger'))); 
                                        ?>">
                                            <?php echo ucfirst($mapping['account_type']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo htmlspecialchars($mapping['description']); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $mapping['is_active'] ? 'success' : 'secondary'; ?>">
                                            <?php echo $mapping['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary" onclick="editMapping(<?php echo $mapping['id']; ?>)">
                                            <i class="fa fa-edit"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Mapping Modal -->
<div class="modal fade" id="addMappingModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Account Mapping</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add_mapping">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="mapping_code" class="form-label">Mapping Code *</label>
                                <input type="text" class="form-control" id="mapping_code" name="mapping_code" required>
                                <small class="text-muted">e.g., rev_Sale, exp_CostOfSales, ast_Cash</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="mapping_name" class="form-label">Mapping Name *</label>
                                <input type="text" class="form-control" id="mapping_name" name="mapping_name" required>
                                <small class="text-muted">e.g., Sales Revenue, Cost of Goods Sold</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="mb-3">
                                <label for="account_id" class="form-label">Chart of Account *</label>
                                <select class="form-select" id="account_id" name="account_id" required>
                                    <option value="">Select Account</option>
                                    <?php while ($account = $accounts->fetch_assoc()): ?>
                                        <option value="<?php echo $account['id']; ?>">
                                            <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name'] . ' (' . ucfirst($account['account_type']) . ')'); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" 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 Mapping</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Mapping Modal -->
<div class="modal fade" id="editMappingModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Account Mapping</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="update_mapping">
                <input type="hidden" name="mapping_id" id="edit_mapping_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_mapping_code" class="form-label">Mapping Code</label>
                                <input type="text" class="form-control" id="edit_mapping_code" readonly>
                                <small class="text-muted">Mapping code cannot be changed</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_mapping_name" class="form-label">Mapping Name *</label>
                                <input type="text" class="form-control" id="edit_mapping_name" name="mapping_name" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="mb-3">
                                <label for="edit_account_id" class="form-label">Chart of Account *</label>
                                <select class="form-select" id="edit_account_id" name="account_id" required>
                                    <option value="">Select Account</option>
                                    <?php 
                                    $accounts->data_seek(0); // Reset result pointer
                                    while ($account = $accounts->fetch_assoc()): 
                                    ?>
                                        <option value="<?php echo $account['id']; ?>">
                                            <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name'] . ' (' . ucfirst($account['account_type']) . ')'); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label for="edit_description" class="form-label">Description</label>
                                <textarea class="form-control" id="edit_description" name="description" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="edit_is_active" class="form-label">Status</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active" value="1">
                                    <label class="form-check-label" for="edit_is_active">
                                        Active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </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 Mapping</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editMapping(mappingId) {
    // Fetch mapping details via AJAX
    fetch('ajax/get_mapping.php?id=' + mappingId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const mapping = data.mapping;
                document.getElementById('edit_mapping_id').value = mapping.id;
                document.getElementById('edit_mapping_code').value = mapping.mapping_code;
                document.getElementById('edit_mapping_name').value = mapping.mapping_name;
                document.getElementById('edit_account_id').value = mapping.account_id;
                document.getElementById('edit_description').value = mapping.description || '';
                document.getElementById('edit_is_active').checked = mapping.is_active == 1;
                
                // Show the modal
                new bootstrap.Modal(document.getElementById('editMappingModal')).show();
            } else {
                alert('Error loading mapping details: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading mapping details');
        });
}
</script>

</body>
</html>
