<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'beneficiaries';
$database = new Database();
$db = $database->getConnection();

// Check for messages from other scripts
$success_message = $_SESSION['success_message'] ?? '';
$error_message = $_SESSION['error_message'] ?? '';
unset($_SESSION['success_message'], $_SESSION['error_message']);

// Toggle favorite status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_favorite'])) {
    $beneficiary_id = filter_input(INPUT_POST, 'beneficiary_id', FILTER_VALIDATE_INT);
    $is_favorite = isset($_POST['is_favorite']) ? 1 : 0;
    
    if ($beneficiary_id) {
        try {
            $stmt = $db->prepare("UPDATE beneficiaries SET is_favorite = ? WHERE id = ? AND user_id = ?");
            $stmt->execute([$is_favorite, $beneficiary_id, $_SESSION['user_id']]);
            
            if ($stmt->rowCount() > 0) {
                $success_message = "Beneficiary has been " . ($is_favorite ? "added to" : "removed from") . " favorites.";
            } else {
                $error_message = "Beneficiary not found or you don't have permission to update it.";
            }
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating the beneficiary.";
            error_log("Beneficiary Update Error: " . $e->getMessage());
        }
    }
}

// Fetch all beneficiaries with recipient details
$stmt = $db->prepare("
    SELECT 
        b.*,
        u.first_name,
        u.last_name,
        COALESCE(u.account_number, b.account_number) AS display_account_number
    FROM 
        beneficiaries b
    LEFT JOIN 
        users u ON b.recipient_id = u.id
    WHERE 
        b.user_id = ?
    ORDER BY 
        b.is_favorite DESC, b.name ASC
");
$stmt->execute([$_SESSION['user_id']]);
$beneficiaries = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Beneficiaries Page Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --border-color: #e2e8f0;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --danger-color: #ef4444;
}

.beneficiary-card {
    background-color: white;
    border-radius: 1rem;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
}

.beneficiary-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.05);
}

.beneficiary-card.favorite {
    border: 2px solid var(--warning-color);
}

.favorite-badge {
    position: absolute;
    top: 0;
    right: 0;
    background-color: var(--warning-color);
    color: white;
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    border-bottom-left-radius: 0.5rem;
}

.beneficiary-header {
    padding: 1.5rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
}

.beneficiary-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background-color: var(--primary-light);
    color: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    font-weight: 600;
    margin-right: 1rem;
    flex-shrink: 0;
}

.beneficiary-name {
    font-size: 1.125rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.beneficiary-bank {
    color: #64748b;
    font-size: 0.875rem;
}

.beneficiary-body {
    padding: 1.5rem;
    flex-grow: 1;
}

.beneficiary-detail {
    margin-bottom: 1rem;
}

.detail-label {
    font-size: 0.75rem;
    color: #64748b;
    margin-bottom: 0.25rem;
}

.detail-value {
    font-weight: 500;
}

.account-number {
    font-family: 'Courier New', monospace;
    letter-spacing: 1px;
}

.beneficiary-footer {
    padding: 1rem 1.5rem;
    background-color: #f3f4f6;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
}

.btn-icon {
    width: 36px;
    height: 36px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}

.empty-state {
    text-align: center;
    padding: 3rem;
    background-color: white;
    border-radius: 1rem;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.empty-state-icon {
    font-size: 4rem;
    color: #d1d5db;
    margin-bottom: 1rem;
}

.search-filter-bar {
    background-color: white;
    border-radius: 0.75rem;
    padding: 1rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    align-items: center;
}

.search-input-group {
    flex-grow: 1;
    position: relative;
}

.search-input-group .form-control {
    padding-left: 2.5rem;
    border-radius: 0.5rem;
}

.search-input-group .search-icon {
    position: absolute;
    left: 0.75rem;
    top: 50%;
    transform: translateY(-50%);
    color: #64748b;
    pointer-events: none;
}
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0">Manage Beneficiaries</h1>
            <a href="add-beneficiary.php" class="btn btn-primary">
                <i class='bx bx-plus me-1'></i> Add New Beneficiary
            </a>
        </div>

        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Search and Filter Bar -->
        <div class="search-filter-bar">
            <div class="search-input-group">
                <i class='bx bx-search search-icon'></i>
                <input type="text" class="form-control" id="searchBeneficiary" placeholder="Search beneficiaries...">
            </div>
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="showFavoritesOnly">
                <label class="form-check-label" for="showFavoritesOnly">Show favorites only</label>
            </div>
        </div>

        <div class="row g-4" id="beneficiariesContainer">
            <?php if (empty($beneficiaries)): ?>
                <div class="col-12">
                    <div class="empty-state">
                        <i class='bx bx-user-plus empty-state-icon'></i>
                        <h5>No Beneficiaries Found</h5>
                        <p class="text-muted">You haven't added any beneficiaries yet. Add your first beneficiary to make transfers easier.</p>
                        <a href="add-beneficiary.php" class="btn btn-primary mt-3">
                            <i class='bx bx-plus me-1'></i> Add Your First Beneficiary
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($beneficiaries as $beneficiary): ?>
                    <div class="col-md-6 col-lg-4 beneficiary-item" data-favorite="<?php echo $beneficiary['is_favorite'] ? 'true' : 'false'; ?>">
                        <div class="beneficiary-card <?php echo $beneficiary['is_favorite'] ? 'favorite' : ''; ?>">
                            <?php if ($beneficiary['is_favorite']): ?>
                                <div class="favorite-badge"><i class='bx bxs-star'></i> Favorite</div>
                            <?php endif; ?>
                            <div class="beneficiary-header">
                                <div class="beneficiary-avatar">
                                    <?php echo strtoupper(substr($beneficiary['name'], 0, 1)); ?>
                                </div>
                                <div>
                                    <div class="beneficiary-name"><?php echo htmlspecialchars($beneficiary['name']); ?></div>
                                    <div class="beneficiary-bank">
                                        <?php 
                                        if (!empty($beneficiary['bank_name'])) {
                                            echo htmlspecialchars($beneficiary['bank_name']);
                                        } else {
                                            echo 'Same Bank';
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>
                            <div class="beneficiary-body">
                                <div class="beneficiary-detail">
                                    <div class="detail-label">Account Number</div>
                                    <div class="detail-value account-number">
                                        <?php echo htmlspecialchars($beneficiary['display_account_number']); ?>
                                    </div>
                                </div>
                                <?php if (!empty($beneficiary['first_name'])): ?>
                                    <div class="beneficiary-detail">
                                        <div class="detail-label">Full Name</div>
                                        <div class="detail-value">
                                            <?php echo htmlspecialchars($beneficiary['first_name'] . ' ' . $beneficiary['last_name']); ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="beneficiary-footer">
                                <div>
                                    <form method="POST" action="beneficiaries.php" class="d-inline">
                                        <input type="hidden" name="beneficiary_id" value="<?php echo $beneficiary['id']; ?>">
                                        <input type="hidden" name="is_favorite" value="<?php echo $beneficiary['is_favorite'] ? '0' : '1'; ?>">
                                        <button type="submit" name="toggle_favorite" class="btn btn-icon btn-outline-warning" title="<?php echo $beneficiary['is_favorite'] ? 'Remove from favorites' : 'Add to favorites'; ?>">
                                            <i class='bx <?php echo $beneficiary['is_favorite'] ? 'bxs-star' : 'bx-star'; ?>'></i>
                                        </button>
                                    </form>
                                </div>
                                <div>
                                    <a href="transfer.php?step=2&beneficiary=<?php echo $beneficiary['id']; ?>" class="btn btn-primary me-2">
                                        <i class='bx bx-send me-1'></i> Send Money
                                    </a>
                                    <a href="delete-beneficiary.php?id=<?php echo $beneficiary['id']; ?>" class="btn btn-outline-danger" onclick="return confirm('Are you sure you want to delete this beneficiary?');">
                                        <i class='bx bx-trash'></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Search functionality
    const searchInput = document.getElementById('searchBeneficiary');
    const beneficiaryItems = document.querySelectorAll('.beneficiary-item');
    
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        
        beneficiaryItems.forEach(item => {
            const name = item.querySelector('.beneficiary-name').textContent.toLowerCase();
            const accountNumber = item.querySelector('.account-number').textContent.toLowerCase();
            const bank = item.querySelector('.beneficiary-bank').textContent.toLowerCase();
            
            if (name.includes(searchTerm) || accountNumber.includes(searchTerm) || bank.includes(searchTerm)) {
                item.style.display = '';
            } else {
                item.style.display = 'none';
            }
        });
    });
    
    // Filter favorites
    const showFavoritesOnly = document.getElementById('showFavoritesOnly');
    
    showFavoritesOnly.addEventListener('change', function() {
        beneficiaryItems.forEach(item => {
            if (this.checked && item.dataset.favorite !== 'true') {
                item.style.display = 'none';
            } else {
                item.style.display = '';
            }
        });
    });
});
</script>
