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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT', 'RECEPTIONIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

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

if ($payment_id == 0) {
    header('Location: payments.php');
    exit();
}

// Fetch payment details
$query = "SELECT p.*, 
          i.invoice_number, i.total_amount as invoice_total, i.balance as invoice_balance,
          pat.patient_number,
          u.full_name as patient_name, u.phone_number, u.email,
          receiver.full_name as received_by_name,
          dept.department_name
          FROM payments p
          JOIN invoices i ON p.invoice_id = i.invoice_id
          JOIN patients pat ON p.patient_id = pat.patient_id
          JOIN users u ON pat.user_id = u.user_id
          LEFT JOIN users receiver ON p.received_by = receiver.user_id
          LEFT JOIN departments dept ON pat.department_id = dept.department_id
          WHERE p.payment_id = $payment_id";

$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 0) {
    header('Location: payments.php');
    exit();
}

$payment = mysqli_fetch_assoc($result);
$page_title = "Payment Details - " . $payment['payment_number'];

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .detail-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #64748b;
            font-weight: 500;
        }
        
        .detail-value {
            color: #1e293b;
            font-weight: 600;
        }
        
        .status-badge-large {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1rem;
        }
        
        .payment-header {
            background: linear-gradient(135deg, #059669 0%, #047857 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        @media print {
            .no-print { display: none !important; }
            .payment-header { 
                background: #059669 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </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 Title -->
                    <div class="row no-print">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="payments.php">Payments</a></li>
                                        <li class="breadcrumb-item active">View Payment</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Payment Header -->
                    <div class="payment-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h3><i class="ri-money-dollar-circle-line me-2"></i><?php echo $payment['payment_number']; ?></h3>
                                <p class="mb-0">Payment Date: <?php echo date('d M Y, h:i A', strtotime($payment['payment_date'])); ?></p>
                            </div>
                            <div class="col-md-4 text-md-end">
                                <h2 class="mb-0">KES <?php echo number_format($payment['amount'], 2); ?></h2>
                                <?php
                                $statusColors = [
                                    'COMPLETED' => 'success',
                                    'PENDING' => 'warning',
                                    'FAILED' => 'danger',
                                    'REVERSED' => 'dark',
                                    'REFUNDED' => 'danger'
                                ];
                                $color = $statusColors[$payment['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $color; ?> status-badge-large mt-2">
                                    <?php echo $payment['status']; ?>
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Payment Information -->
                        <div class="col-lg-6">
                            <div class="detail-card">
                                <h5 class="mb-3"><i class="ri-information-line me-2"></i>Payment Information</h5>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Payment Number:</span>
                                    <span class="detail-value"><?php echo $payment['payment_number']; ?></span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Payment Method:</span>
                                    <span class="detail-value">
                                        <span class="badge bg-info"><?php echo str_replace('_', ' ', $payment['payment_method']); ?></span>
                                    </span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Amount:</span>
                                    <span class="detail-value text-success">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Currency:</span>
                                    <span class="detail-value"><?php echo $payment['currency']; ?></span>
                                </div>
                                
                                <?php if ($payment['transaction_reference']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Transaction Reference:</span>
                                    <span class="detail-value"><?php echo $payment['transaction_reference']; ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($payment['mpesa_transaction_id']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">M-Pesa Transaction ID:</span>
                                    <span class="detail-value"><?php echo $payment['mpesa_transaction_id']; ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Received By:</span>
                                    <span class="detail-value"><?php echo $payment['received_by_name']; ?></span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Payment Date:</span>
                                    <span class="detail-value"><?php echo date('d M Y, h:i A', strtotime($payment['payment_date'])); ?></span>
                                </div>
                                
                                <?php if ($payment['notes']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Notes:</span>
                                    <span class="detail-value"><?php echo nl2br(htmlspecialchars($payment['notes'])); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Patient & Invoice Information -->
                        <div class="col-lg-6">
                            <div class="detail-card">
                                <h5 class="mb-3"><i class="ri-user-line me-2"></i>Patient Information</h5>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Patient Name:</span>
                                    <span class="detail-value"><?php echo $payment['patient_name']; ?></span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Patient Number:</span>
                                    <span class="detail-value"><?php echo $payment['patient_number']; ?></span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Phone Number:</span>
                                    <span class="detail-value"><?php echo $payment['phone_number']; ?></span>
                                </div>
                                
                                <?php if ($payment['email']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Email:</span>
                                    <span class="detail-value"><?php echo $payment['email']; ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($payment['department_name']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Department:</span>
                                    <span class="detail-value"><?php echo $payment['department_name']; ?></span>
                                </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="detail-card">
                                <h5 class="mb-3"><i class="ri-file-text-line me-2"></i>Invoice Information</h5>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Invoice Number:</span>
                                    <span class="detail-value">
                                        <a href="view_invoice.php?id=<?php echo $payment['invoice_id']; ?>" class="text-primary">
                                            <?php echo $payment['invoice_number']; ?>
                                        </a>
                                    </span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Invoice Total:</span>
                                    <span class="detail-value">KES <?php echo number_format($payment['invoice_total'], 2); ?></span>
                                </div>
                                
                                <div class="detail-row">
                                    <span class="detail-label">Remaining Balance:</span>
                                    <span class="detail-value text-danger">KES <?php echo number_format($payment['invoice_balance'], 2); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="row no-print">
                        <div class="col-12">
                            <div class="detail-card">
                                <div class="d-flex gap-2 justify-content-end">
                                    <a href="payments.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back to Payments
                                    </a>
                                    <button type="button" class="btn btn-primary" onclick="window.print()">
                                        <i class="ri-printer-line me-1"></i> Print Receipt
                                    </button>
                                    <?php if ($payment['status'] == 'COMPLETED' && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT'])): ?>
                                    <a href="view_invoice.php?id=<?php echo $payment['invoice_id']; ?>" class="btn btn-info">
                                        <i class="ri-file-text-line me-1"></i> View Invoice
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>

        <?php include 'layouts/footer.php'; ?>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>