<?php
// view_payment_allocation.php - View Payment Allocation Details
include 'layouts/session.php';
include 'layouts/dbconn.php';

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

if ($allocation_id === 0) {
    header("Location: list_payment_allocations.php");
    exit();
}

// Get allocation details with all related information
$allocation_sql = "SELECT 
    pa.*,
    bp.payment_number as bulk_payment_number,
    bp.payment_date as bulk_payment_date,
    bp.total_amount as bulk_total_amount,
    esp.provider_name,
    esp.provider_code,
    esp.provider_type,
    esp.contact_person,
    esp.email as provider_email,
    esp.phone as provider_phone,
    d.doctor_id,
    u.full_name as doctor_name,
    d.specialization,
    d.medical_license,
    p.patient_number,
    u.full_name as patient_name,
    created_user.full_name as created_by_name,
    verified_user.full_name as verified_by_name,
    approved_user.full_name as approved_by_name
FROM payment_allocations pa
JOIN bulk_payments bp ON pa.bulk_payment_id = bp.bulk_payment_id
JOIN external_service_providers esp ON pa.provider_id = esp.provider_id
LEFT JOIN doctors d ON pa.doctor_id = d.doctor_id
LEFT JOIN users u ON d.user_id = u.user_id
LEFT JOIN patients p ON pa.patient_id = p.patient_id
LEFT JOIN users created_user ON pa.created_by = created_user.user_id
LEFT JOIN users verified_user ON pa.verified_by = verified_user.user_id
LEFT JOIN users approved_user ON pa.approved_by = approved_user.user_id
WHERE pa.allocation_id = ?";

$stmt = $conn->prepare($allocation_sql);
$stmt->bind_param('i', $allocation_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Allocation not found";
    header("Location: list_payment_allocations.php");
    exit();
}

$allocation = $result->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Allocation')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .detail-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .info-row {
            display: flex;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            flex: 0 0 200px;
            font-weight: 600;
            color: #64748b;
        }
        
        .info-value {
            flex: 1;
            color: #1e293b;
        }
        
        .status-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            text-transform: uppercase;
        }
        
        .badge-draft { background: #e0e7ff; color: #4338ca; }
        .badge-pending-approval { background: #fef3c7; color: #92400e; }
        .badge-approved { background: #d1fae5; color: #065f46; }
        .badge-paid { background: #d1fae5; color: #047857; }
        .badge-rejected { background: #fee2e2; color: #991b1b; }
        .badge-cancelled { background: #f1f5f9; color: #475569; }
        
        .calculation-box {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 8px;
            padding: 1.5rem;
        }
        
        .calc-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            font-size: 1rem;
        }
        
        .calc-row.total {
            border-top: 2px solid #22c55e;
            margin-top: 0.5rem;
            padding-top: 1rem;
            font-weight: 700;
            font-size: 1.125rem;
            color: #047857;
        }
        
        .timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .timeline::before {
            content: '';
            position: absolute;
            left: 0.5rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }
        
        .timeline-item {
            position: relative;
            padding-bottom: 1.5rem;
        }
        
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -1.5rem;
            top: 0.25rem;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #667eea;
            border: 2px solid white;
            box-shadow: 0 0 0 2px #667eea;
        }
        
        .timeline-time {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .timeline-desc {
            color: #1e293b;
            margin-top: 0.25rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h3 class="mb-2">
                                    <i class="ri-file-text-line me-2"></i>
                                    Allocation: <?php echo htmlspecialchars($allocation['allocation_number']); ?>
                                </h3>
                                <p class="mb-0 opacity-75">Payment allocation details and history</p>
                            </div>
                            <div class="col-auto">
                                <a href="list_payment_allocations.php" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i>Back to List
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="ri-check-line me-2"></i><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <!-- Main Details -->
                        <div class="col-lg-8">
                            
                            <!-- Status and Actions -->
                            <div class="detail-card">
                                <div class="d-flex justify-content-between align-items-start mb-4">
                                    <div>
                                        <h5>Status</h5>
                                        <span class="status-badge badge-<?php echo strtolower(str_replace('_', '-', $allocation['allocation_status'])); ?>">
                                            <?php echo str_replace('_', ' ', $allocation['allocation_status']); ?>
                                        </span>
                                    </div>
                                    <div class="d-flex gap-2">
                                        <?php if ($allocation['allocation_status'] === 'DRAFT'): ?>
                                        <a href="edit_payment_allocation.php?id=<?php echo $allocation_id; ?>" class="btn btn-info">
                                            <i class="ri-edit-line me-1"></i>Edit
                                        </a>
                                        <?php endif; ?>
                                        <button onclick="window.print()" class="btn btn-secondary">
                                            <i class="ri-printer-line me-1"></i>Print
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Bulk Payment Info -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-bank-line"></i>Bulk Payment Details
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Payment Number</div>
                                    <div class="info-value">
                                        <a href="view_bulk_payment.php?id=<?php echo $allocation['bulk_payment_id']; ?>">
                                            <?php echo htmlspecialchars($allocation['bulk_payment_number']); ?>
                                        </a>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Payment Date</div>
                                    <div class="info-value"><?php echo date('d M Y', strtotime($allocation['bulk_payment_date'])); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Total Payment Amount</div>
                                    <div class="info-value">
                                        <strong>KES <?php echo number_format($allocation['bulk_total_amount'], 2); ?></strong>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Provider Info -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-building-line"></i>Service Provider
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Provider Name</div>
                                    <div class="info-value">
                                        <?php echo htmlspecialchars($allocation['provider_name']); ?>
                                        <span class="badge bg-secondary ms-2"><?php echo htmlspecialchars($allocation['provider_code']); ?></span>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Provider Type</div>
                                    <div class="info-value"><?php echo str_replace('_', ' ', $allocation['provider_type']); ?></div>
                                </div>
                            </div>
                            
                            <!-- Service Details -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-file-text-line"></i>Service Details
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Service Date</div>
                                    <div class="info-value"><?php echo date('d M Y', strtotime($allocation['service_date'])); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Service Category</div>
                                    <div class="info-value">
                                        <span class="badge bg-primary"><?php echo ucfirst(strtolower($allocation['service_category'])); ?></span>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Service Description</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($allocation['service_description'])); ?></div>
                                </div>
                            </div>
                            
                            <!-- Doctor Details -->
                            <?php if ($allocation['doctor_name']): ?>
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-user-heart-line"></i>Doctor Details
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Doctor Name</div>
                                    <div class="info-value"><?php echo htmlspecialchars($allocation['doctor_name']); ?></div>
                                </div>
                                <?php if ($allocation['specialization']): ?>
                                <div class="info-row">
                                    <div class="info-label">Specialization</div>
                                    <div class="info-value"><?php echo htmlspecialchars($allocation['specialization']); ?></div>
                                </div>
                                <?php endif; ?>
                                <div class="info-row">
                                    <div class="info-label">Payment Status</div>
                                    <div class="info-value">
                                        <span class="badge bg-<?php echo $allocation['doctor_payment_status'] === 'PAID' ? 'success' : 'warning'; ?>">
                                            <?php echo str_replace('_', ' ', $allocation['doctor_payment_status']); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Financial Breakdown -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-money-dollar-circle-line"></i>Financial Breakdown
                                </div>
                                
                                <div class="calculation-box">
                                    <div class="calc-row">
                                        <span>Total Service Cost:</span>
                                        <strong>KES <?php echo number_format($allocation['total_service_cost'], 2); ?></strong>
                                    </div>
                                    
                                    <div class="calc-row">
                                        <span>Allocation Type:</span>
                                        <strong><?php echo str_replace('_', ' ', $allocation['allocation_type']); ?></strong>
                                    </div>
                                    
                                    <?php if ($allocation['doctor_allocation'] > 0): ?>
                                    <div class="calc-row">
                                        <span>Doctor Allocation (<?php echo number_format($allocation['doctor_commission_rate'], 2); ?>%):</span>
                                        <span class="text-primary">KES <?php echo number_format($allocation['doctor_allocation'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($allocation['facility_allocation'] > 0): ?>
                                    <div class="calc-row">
                                        <span>Facility Allocation (<?php echo number_format($allocation['facility_percentage'], 2); ?>%):</span>
                                        <span class="text-info">KES <?php echo number_format($allocation['facility_allocation'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($allocation['tax_withheld'] > 0): ?>
                                    <div class="calc-row">
                                        <span>Less: Tax Withheld:</span>
                                        <span class="text-danger">KES <?php echo number_format($allocation['tax_withheld'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($allocation['doctor_allocation'] > 0): ?>
                                    <div class="calc-row total">
                                        <span>Net Doctor Payment:</span>
                                        <strong>KES <?php echo number_format($allocation['net_doctor_payment'], 2); ?></strong>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                        </div>
                        
                        <!-- Sidebar -->
                        <div class="col-lg-4">
                            
                            <!-- Audit Trail -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-time-line"></i>Audit Trail
                                </div>
                                
                                <div class="timeline">
                                    <div class="timeline-item">
                                        <div class="timeline-time">
                                            <?php echo date('d M Y, H:i', strtotime($allocation['created_at'])); ?>
                                        </div>
                                        <div class="timeline-desc">
                                            <strong>Created</strong> by <?php echo htmlspecialchars($allocation['created_by_name']); ?>
                                        </div>
                                    </div>
                                    
                                    <?php if ($allocation['approved_at']): ?>
                                    <div class="timeline-item">
                                        <div class="timeline-time">
                                            <?php echo date('d M Y, H:i', strtotime($allocation['approved_at'])); ?>
                                        </div>
                                        <div class="timeline-desc">
                                            <strong>Approved</strong> by <?php echo htmlspecialchars($allocation['approved_by_name']); ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="timeline-item">
                                        <div class="timeline-time">
                                            <?php echo date('d M Y, H:i', strtotime($allocation['updated_at'])); ?>
                                        </div>
                                        <div class="timeline-desc">
                                            <strong>Last Updated</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                    
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
</body>
</html>