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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get transaction ID
$transaction_id = $_GET['id'] ?? '';
if (!$transaction_id) {
    header('Location: list_transactions.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

// Fetch transaction details
$transaction_query = "SELECT ft.*, c.first_name, c.last_name, c.contributor_number, c.phone_primary, c.email,
                     f.fund_name, f.fund_code, u.full_name as processed_by_name, u.email as processed_by_email
                     FROM fund_transactions ft
                     LEFT JOIN contributors c ON ft.contributor_id = c.contributor_id
                     LEFT JOIN funds f ON ft.fund_id = f.fund_id
                     LEFT JOIN users u ON ft.processed_by = u.user_id
                     WHERE ft.transaction_id = ?";
$stmt = $conn->prepare($transaction_query);
$stmt->bind_param("i", $transaction_id);
$stmt->execute();
$transaction = $stmt->get_result()->fetch_assoc();

if (!$transaction) {
    header('Location: list_transactions.php?error=transaction_not_found');
    exit();
}

// Get related transactions for this contributor and fund
$related_query = "SELECT ft.transaction_id, ft.transaction_number, ft.transaction_type, ft.amount, ft.transaction_date, ft.status
                  FROM fund_transactions ft
                  WHERE ft.contributor_id = ? AND ft.fund_id = ? AND ft.transaction_id != ?
                  ORDER BY ft.transaction_date DESC, ft.created_at DESC
                  LIMIT 10";
$stmt_related = $conn->prepare($related_query);
$stmt_related->bind_param("iii", $transaction['contributor_id'], $transaction['fund_id'], $transaction_id);
$stmt_related->execute();
$related_transactions = $stmt_related->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Transaction Details - Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .detail-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
        }
        
        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-label {
            font-weight: 500;
            color: #64748b;
        }
        
        .info-value {
            font-weight: 600;
            color: #1e293b;
            text-align: right;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-completed { background: #dcfce7; color: #166534; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .status-failed { background: #fee2e2; color: #991b1b; }
        
        .transaction-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .transaction-contribution { background: #dcfce7; color: #166534; }
        .transaction-withdrawal { background: #fee2e2; color: #991b1b; }
        .transaction-transfer-in { background: #ddd6fe; color: #5b21b6; }
        .transaction-transfer-out { background: #fef3c7; color: #92400e; }
        
        .amount-display {
            font-size: 2rem;
            font-weight: 700;
            text-align: center;
            padding: 2rem;
            border-radius: 12px;
            margin: 1rem 0;
        }
        
        .amount-positive {
            background: #dcfce7;
            color: #166534;
        }
        
        .amount-negative {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            color: white;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
            color: #64748b;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .quick-actions {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .amount-display {
                font-size: 1.5rem;
                padding: 1.5rem;
            }
            
            .quick-actions {
                flex-direction: column;
            }
        }
    </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">
                        <h1 class="page-title">Transaction Details</h1>
                        <p class="page-subtitle">
                            <?php echo htmlspecialchars($transaction['transaction_number']); ?> • 
                            <?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['transaction_type']))); ?>
                        </p>
                    </div>

                    <!-- Quick Actions -->
                    <div class="quick-actions">
                        <?php if ($transaction['transaction_type'] == 'WITHDRAWAL'): ?>
                            <a href="list_withdrawals.php" class="btn btn-outline-secondary">
                                <i class="ph-arrow-left me-2"></i>Back to Withdrawals
                            </a>
                        <?php else: ?>
                            <a href="list_transactions.php" class="btn btn-outline-secondary">
                                <i class="ph-arrow-left me-2"></i>Back to Transactions
                            </a>
                        <?php endif; ?>
                        <a href="view_contributor.php?id=<?php echo $transaction['contributor_id']; ?>" class="btn btn-primary">
                            <i class="ph-user me-2"></i>View Contributor
                        </a>
                        <button onclick="window.print()" class="btn btn-outline-secondary">
                            <i class="ph-printer me-2"></i>Print Receipt
                        </button>
                    </div>

                    <div class="row">
                        <!-- Transaction Details -->
                        <div class="col-md-8">
                            <!-- Amount Display -->
                            <div class="detail-card">
                                <div class="amount-display <?php echo in_array($transaction['transaction_type'], ['WITHDRAWAL', 'TRANSFER_OUT']) ? 'amount-negative' : 'amount-positive'; ?>">
                                    <?php echo in_array($transaction['transaction_type'], ['WITHDRAWAL', 'TRANSFER_OUT']) ? '-' : '+'; ?>KES <?php echo number_format($transaction['amount']); ?>
                                </div>
                                <div class="text-center">
                                    <?php 
                                    $type_class = match($transaction['transaction_type']) {
                                        'CONTRIBUTION' => 'transaction-contribution',
                                        'WITHDRAWAL' => 'transaction-withdrawal',
                                        'TRANSFER_IN' => 'transaction-transfer-in',
                                        'TRANSFER_OUT' => 'transaction-transfer-out',
                                        default => 'transaction-contribution'
                                    };
                                    ?>
                                    <span class="transaction-badge <?php echo $type_class; ?>" style="font-size: 1rem; padding: 0.5rem 1rem;">
                                        <?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['transaction_type']))); ?>
                                    </span>
                                </div>
                            </div>

                            <!-- Transaction Information -->
                            <div class="detail-card">
                                <h3 class="mb-3">Transaction Information</h3>
                                <div class="info-grid">
                                    <div>
                                        <div class="info-item">
                                            <span class="info-label">Transaction Number:</span>
                                            <span class="info-value" style="font-family: monospace;"><?php echo htmlspecialchars($transaction['transaction_number']); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Date:</span>
                                            <span class="info-value"><?php echo date('M j, Y', strtotime($transaction['transaction_date'])); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Time:</span>
                                            <span class="info-value"><?php echo date('g:i A', strtotime($transaction['created_at'])); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Status:</span>
                                            <span class="info-value">
                                                <?php 
                                                $status_class = match($transaction['status']) {
                                                    'COMPLETED' => 'status-completed',
                                                    'PENDING' => 'status-pending',
                                                    'CANCELLED' => 'status-cancelled',
                                                    'FAILED' => 'status-failed',
                                                    default => 'status-pending'
                                                };
                                                ?>
                                                <span class="status-badge <?php echo $status_class; ?>">
                                                    <?php echo ucfirst(strtolower($transaction['status'])); ?>
                                                </span>
                                            </span>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="info-item">
                                            <span class="info-label">Payment Method:</span>
                                            <span class="info-value"><?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['payment_method']))); ?></span>
                                        </div>
                                        <?php if ($transaction['reference_number']): ?>
                                        <div class="info-item">
                                            <span class="info-label">Reference Number:</span>
                                            <span class="info-value" style="font-family: monospace;"><?php echo htmlspecialchars($transaction['reference_number']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="info-item">
                                            <span class="info-label">Balance After:</span>
                                            <span class="info-value">KES <?php echo number_format($transaction['balance_after']); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Processed By:</span>
                                            <span class="info-value"><?php echo htmlspecialchars($transaction['processed_by_name'] ?? 'System'); ?></span>
                                        </div>
                                    </div>
                                </div>

                                <?php if ($transaction['description'] || $transaction['purpose']): ?>
                                <div class="mt-3">
                                    <?php if ($transaction['purpose']): ?>
                                    <div class="info-item">
                                        <span class="info-label">Purpose:</span>
                                        <span class="info-value"><?php echo htmlspecialchars($transaction['purpose']); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($transaction['description']): ?>
                                    <div class="info-item">
                                        <span class="info-label">Description:</span>
                                        <span class="info-value"><?php echo htmlspecialchars($transaction['description']); ?></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Contributor & Fund Information -->
                        <div class="col-md-4">
                            <!-- Contributor Information -->
                            <div class="detail-card">
                                <h3 class="mb-3">Contributor Information</h3>
                                <div class="info-item">
                                    <span class="info-label">Name:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($transaction['first_name'] . ' ' . $transaction['last_name']); ?></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">Contributor #:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($transaction['contributor_number']); ?></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">Phone:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($transaction['phone_primary']); ?></span>
                                </div>
                                <?php if ($transaction['email']): ?>
                                <div class="info-item">
                                    <span class="info-label">Email:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($transaction['email']); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Fund Information -->
                            <div class="detail-card">
                                <h3 class="mb-3">Fund Information</h3>
                                <div class="info-item">
                                    <span class="info-label">Fund Name:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($transaction['fund_name']); ?></span>
                                </div>
                                <?php if ($transaction['fund_code']): ?>
                                <div class="info-item">
                                    <span class="info-label">Fund Code:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($transaction['fund_code']); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Related Transactions -->
                            <?php if ($related_transactions->num_rows > 0): ?>
                            <div class="detail-card">
                                <h3 class="mb-3">Recent Related Transactions</h3>
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Type</th>
                                            <th>Amount</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($related = $related_transactions->fetch_assoc()): ?>
                                        <tr>
                                            <td><?php echo date('M j', strtotime($related['transaction_date'])); ?></td>
                                            <td>
                                                <?php 
                                                $related_type_class = match($related['transaction_type']) {
                                                    'CONTRIBUTION' => 'transaction-contribution',
                                                    'WITHDRAWAL' => 'transaction-withdrawal',
                                                    'TRANSFER_IN' => 'transaction-transfer-in',
                                                    'TRANSFER_OUT' => 'transaction-transfer-out',
                                                    default => 'transaction-contribution'
                                                };
                                                ?>
                                                <span class="transaction-badge <?php echo $related_type_class; ?>">
                                                    <?php echo substr(ucfirst(str_replace('_', ' ', strtolower($related['transaction_type']))), 0, 10); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span style="color: <?php echo in_array($related['transaction_type'], ['WITHDRAWAL', 'TRANSFER_OUT']) ? '#dc2626' : '#059669'; ?>;">
                                                    <?php echo in_array($related['transaction_type'], ['WITHDRAWAL', 'TRANSFER_OUT']) ? '-' : '+'; ?><?php echo number_format($related['amount']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php 
                                                $related_status_class = match($related['status']) {
                                                    'COMPLETED' => 'status-completed',
                                                    'PENDING' => 'status-pending',
                                                    'CANCELLED' => 'status-cancelled',
                                                    'FAILED' => 'status-failed',
                                                    default => 'status-pending'
                                                };
                                                ?>
                                                <span class="status-badge <?php echo $related_status_class; ?>">
                                                    <?php echo substr(ucfirst(strtolower($related['status'])), 0, 4); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Print functionality
            $('.btn[onclick="window.print()"]').on('click', function() {
                window.print();
            });
        });
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>