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

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

$corp_id = $_GET['corp_id'] ?? '';

if (!$corp_id) {
    header('Location: calculate_commissions.php');
    exit();
}

// Get corporate details
$sql = "SELECT corporate FROM corporate WHERE corp_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $corp_id);
$stmt->execute();
$corporate = $stmt->get_result()->fetch_assoc();

// Get debit notes with commission calculations
$sql = "SELECT 
    pdn.*,
    c.corporate as corporate_name
FROM premium_debit_notes pdn
JOIN corporate c ON pdn.corp_id = c.corp_id
WHERE pdn.corp_id = ? AND pdn.status = 'ALLOCATED'
ORDER BY pdn.debit_date DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $corp_id);
$stmt->execute();
$debits = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Commissions')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link rel="stylesheet" type="text/css" href="assets/libs/datatables/datatables.min.css"/>
    <style>
.commission-summary {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.summary-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

.summary-item:last-child {
    margin-bottom: 0;
    padding-top: 10px;
    border-top: 1px solid #dee2e6;
}

.status-filter {
    margin-bottom: 20px;
}

@media print {
    .no-print {
        display: none !important;
    }
    
    .card {
        border: none !important;
    }
    
    .table td, .table th {
        padding: 0.5rem !important;
    }
}
</style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance', 'title' => 'Commission Details')); ?>

                    <div class="row">
                        <div class="col-xxl-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">
                                        Commission Details for <?php echo htmlspecialchars($corporate['corporate']); ?>
                                    </h4>
                                    <div class="flex-shrink-0">
                                        <button class="btn btn-primary btn-sm" onclick="window.print();">
                                            <i class="ri-printer-line align-middle me-1"></i> Print
                                        </button>
                                        <a href="calculate_commissions.php" class="btn btn-light btn-sm">
                                            <i class="ri-arrow-left-line align-middle me-1"></i> Back
                                        </a>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="commissionsTable">
                                            <thead>
                                                <tr>
                                                    <th>Debit No</th>
                                                    <th>Debit Date</th>
                                                    <th>Gross Premium</th>
                                                    <th>PHCF Amount</th>
                                                    <th>Commission Base</th>
                                                    <th>Initial Commission</th>
                                                    <th>Final Commission</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $totalCommission = 0;
                                                foreach ($debits as $debit): 
                                                    $grossPremium = $debit['amount'];
                                                    $phcfAmount = $grossPremium * 0.0045;
                                                    $commissionBase = $grossPremium - $phcfAmount;
                                                    $initialCommission = $commissionBase * 0.10;
                                                    $finalCommission = $initialCommission * 0.95;
                                                    $totalCommission += $finalCommission;
                                                ?>
                                                <tr>
                                                    <td><?php echo $debit['debit_no']; ?></td>
                                                    <td><?php echo date('d/m/Y', strtotime($debit['debit_date'])); ?></td>
                                                    <td class="text-end">
                                                        <?php echo number_format($grossPremium, 2); ?>
                                                    </td>
                                                    <td class="text-end">
                                                        <?php echo number_format($phcfAmount, 2); ?>
                                                    </td>
                                                    <td class="text-end">
                                                        <?php echo number_format($commissionBase, 2); ?>
                                                    </td>
                                                    <td class="text-end">
                                                        <?php echo number_format($initialCommission, 2); ?>
                                                    </td>
                                                    <td class="text-end">
                                                        <?php echo number_format($finalCommission, 2); ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?php 
                                                            echo $debit['status'] === 'POSTED' ? 'success' : 
                                                                ($debit['status'] === 'DRAFT' ? 'warning' : 'danger'); 
                                                        ?>">
                                                            <?php echo $debit['status']; ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                            <tfoot>
                                                <tr class="table-primary">
                                                    <th colspan="6" class="text-end">Total Commission:</th>
                                                    <th class="text-end"><?php echo number_format($totalCommission, 2); ?></th>
                                                    <th></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>

                                    <?php if (empty($debits)): ?>
                                    <div class="text-center text-muted mt-4">
                                        No debit notes found for this corporate
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="assets/libs/datatables/datatables.min.js"></script>

    <script>
    $(document).ready(function() {
        $('#commissionsTable').DataTable({
            pageLength: 25,
            order: [[1, 'desc']],
            footerCallback: function(row, data, start, end, display) {
                const api = this.api();
                
                // Calculate total commission for filtered rows
                const totalCommission = api
                    .column(6, { search: 'applied' })
                    .data()
                    .reduce((acc, val) => acc + parseFloat(val.replace(/[^0-9.-]+/g, '')), 0);
                    
                // Update total in footer
                $(api.column(6).footer()).html(
                    formatCurrency(totalCommission)
                );
            }
        });

        function formatCurrency(amount) {
            return new Intl.NumberFormat('en-KE', {
                style: 'currency',
                currency: 'KES'
            }).format(amount);
        }
    });
    </script>
</body>
</html>