<?php
// reconcile_bulk_payment.php - Reconcile Bulk Payment
include 'layouts/session.php';
include 'layouts/dbconn.php';

$bulk_payment_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get payment and allocations summary
$summary_sql = "SELECT 
    bp.payment_number,
    bp.total_amount,
    bp.allocated_amount,
    bp.unallocated_amount,
    esp.provider_name,
    COUNT(pa.allocation_id) as total_allocations,
    SUM(CASE WHEN pa.allocation_status NOT IN ('CANCELLED', 'REJECTED') THEN pa.total_service_cost ELSE 0 END) as verified_allocated
FROM bulk_payments bp
JOIN external_service_providers esp ON bp.provider_id = esp.provider_id
LEFT JOIN payment_allocations pa ON bp.bulk_payment_id = pa.bulk_payment_id
WHERE bp.bulk_payment_id = ?
GROUP BY bp.bulk_payment_id";

$stmt = $conn->prepare($summary_sql);
$stmt->bind_param('i', $bulk_payment_id);
$stmt->execute();
$summary = $stmt->get_result()->fetch_assoc();

$discrepancy = $summary['total_amount'] - $summary['verified_allocated'];

// Handle reconciliation submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reconcile'])) {
    $reconciliation_notes = trim($_POST['reconciliation_notes']);
    $reconciliation_status = abs($discrepancy) < 0.01 ? 'COMPLETED' : 'DISCREPANCY';
    
    $update_sql = "UPDATE bulk_payments SET
                   reconciliation_status = ?,
                   reconciled_by = ?,
                   reconciled_at = CURRENT_TIMESTAMP
                   WHERE bulk_payment_id = ?";
    $stmt = $conn->prepare($update_sql);
    $user_id = $_SESSION['user_id'];
    $stmt->bind_param('sii', $reconciliation_status, $user_id, $bulk_payment_id);
    $stmt->execute();
    
    $_SESSION['success_message'] = "Payment reconciled successfully";
    header("Location: view_bulk_payment.php?id=" . $bulk_payment_id);
    exit();
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Reconcile Payment')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="page-header" style="background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%);">
                        <h3 class="text-white">Reconcile Payment: <?php echo htmlspecialchars($summary['payment_number']); ?></h3>
                    </div>
                    
                    <div class="row">
                        <div class="col-lg-8 mx-auto">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">Reconciliation Summary</h5>
                                    
                                    <div class="alert alert-<?php echo abs($discrepancy) < 0.01 ? 'success' : 'warning'; ?>">
                                        <?php if (abs($discrepancy) < 0.01): ?>
                                            <i class="ri-check-line me-2"></i>Payment is fully allocated and balanced
                                        <?php else: ?>
                                            <i class="ri-alert-line me-2"></i>Discrepancy detected: KES <?php echo number_format(abs($discrepancy), 2); ?>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <table class="table">
                                        <tr>
                                            <td>Total Payment Amount:</td>
                                            <td class="text-end"><strong>KES <?php echo number_format($summary['total_amount'], 2); ?></strong></td>
                                        </tr>
                                        <tr>
                                            <td>Total Allocations:</td>
                                            <td class="text-end"><strong>KES <?php echo number_format($summary['verified_allocated'], 2); ?></strong></td>
                                        </tr>
                                        <tr>
                                            <td>Number of Allocations:</td>
                                            <td class="text-end"><strong><?php echo $summary['total_allocations']; ?></strong></td>
                                        </tr>
                                        <tr class="table-<?php echo abs($discrepancy) < 0.01 ? 'success' : 'warning'; ?>">
                                            <td><strong>Difference:</strong></td>
                                            <td class="text-end"><strong>KES <?php echo number_format($discrepancy, 2); ?></strong></td>
                                        </tr>
                                    </table>
                                    
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Reconciliation Notes</label>
                                            <textarea class="form-control" name="reconciliation_notes" rows="4"
                                                      placeholder="Add notes about this reconciliation..."></textarea>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between">
                                            <a href="view_bulk_payment.php?id=<?php echo $bulk_payment_id; ?>" class="btn btn-secondary">Cancel</a>
                                            <button type="submit" name="reconcile" class="btn btn-success">
                                                <i class="ri-check-double-line me-1"></i>Complete Reconciliation
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>