<?php
/**
 * ============================================================================
 * prices/alerts.php - Manage Price Alerts
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Price Alerts';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();
$priceClass = new \App\Price($db);

// Get user's alerts
$alerts = $priceClass->getUserAlerts($userId);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-bell text-warning"></i> My Price Alerts
                    </h2>
                    <p class="text-muted mb-0">Get notified when prices match your criteria</p>
                </div>
                <a href="<?php echo APP_URL; ?>/prices/set-alert.php" class="btn btn-success">
                    <i class="bi bi-plus-circle"></i> Create New Alert
                </a>
            </div>
        </div>
    </div>

    <!-- Alerts List -->
    <div class="row">
        <?php if (!empty($alerts)): ?>
            <?php foreach ($alerts as $alert): ?>
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="card border-0 shadow-sm h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <h5 class="mb-0">
                                    <?php echo ucwords(str_replace('_', ' ', $alert['product_type'])); ?>
                                </h5>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" 
                                           <?php echo $alert['is_active'] ? 'checked' : ''; ?>
                                           onchange="toggleAlert(<?php echo $alert['id']; ?>, this.checked)">
                                </div>
                            </div>

                            <div class="mb-3">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-bell-fill <?php echo $alert['is_active'] ? 'text-success' : 'text-muted'; ?>"></i>
                                    <span class="badge bg-<?php echo $alert['is_active'] ? 'success' : 'secondary'; ?>">
                                        <?php echo $alert['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </div>

                                <div class="alert alert-<?php echo $alert['condition'] === 'above' ? 'danger' : 'success'; ?> mb-2">
                                    <strong>Notify me when price goes</strong><br>
                                    <span class="text-uppercase"><?php echo $alert['condition']; ?></span>
                                    <h4 class="mb-0 mt-1"><?php echo formatCurrency($alert['target_price']); ?></h4>
                                </div>

                                <small class="text-muted">
                                    <i class="bi bi-calendar"></i> 
                                    Created <?php echo timeAgo($alert['created_at']); ?>
                                </small>
                            </div>
                        </div>

                        <div class="card-footer bg-transparent border-top">
                            <div class="d-grid gap-2">
                                <button class="btn btn-sm btn-outline-danger" 
                                        onclick="deleteAlert(<?php echo $alert['id']; ?>)">
                                    <i class="bi bi-trash"></i> Delete Alert
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>

            <!-- Info Card -->
            <div class="col-12 mt-3">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i>
                    <strong>How it works:</strong> You'll receive a notification when the market price for your selected product 
                    reaches your target price. Prices are updated daily from various markets.
                </div>
            </div>

        <?php else: ?>
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-bell-slash text-muted" style="font-size: 4rem;"></i>
                        <h4 class="mt-3">No Price Alerts Set</h4>
                        <p class="text-muted">
                            Create your first price alert to get notified when prices meet your target
                        </p>
                        <a href="<?php echo APP_URL; ?>/prices/set-alert.php" class="btn btn-success btn-lg mt-2">
                            <i class="bi bi-plus-circle"></i> Create Your First Alert
                        </a>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Quick Links -->
    <div class="row mt-4">
        <div class="col-md-4 mb-3">
            <a href="<?php echo APP_URL; ?>/prices/" class="card border-0 shadow-sm text-decoration-none h-100">
                <div class="card-body text-center p-4">
                    <i class="bi bi-tags text-primary" style="font-size: 3rem;"></i>
                    <h5 class="mt-3">View Current Prices</h5>
                    <p class="text-muted small mb-0">Check latest market prices</p>
                </div>
            </a>
        </div>
        <div class="col-md-4 mb-3">
            <a href="<?php echo APP_URL; ?>/prices/comparison.php" class="card border-0 shadow-sm text-decoration-none h-100">
                <div class="card-body text-center p-4">
                    <i class="bi bi-arrow-left-right text-success" style="font-size: 3rem;"></i>
                    <h5 class="mt-3">Compare Prices</h5>
                    <p class="text-muted small mb-0">Across different markets</p>
                </div>
            </a>
        </div>
        <div class="col-md-4 mb-3">
            <a href="<?php echo APP_URL; ?>/prices/set-alert.php" class="card border-0 shadow-sm text-decoration-none h-100">
                <div class="card-body text-center p-4">
                    <i class="bi bi-plus-circle text-warning" style="font-size: 3rem;"></i>
                    <h5 class="mt-3">Create New Alert</h5>
                    <p class="text-muted small mb-0">Set price notification</p>
                </div>
            </a>
        </div>
    </div>
</div>

<script>
function toggleAlert(alertId, isActive) {
    showLoading();
    $.post(APP_URL + '/ajax/toggle-alert.php', {
        alert_id: alertId,
        is_active: isActive ? 1 : 0
    }, function(response) {
        hideLoading();
        if (response.success) {
            showToast(response.message, 'success');
        } else {
            showToast(response.message, 'error');
            location.reload();
        }
    }).fail(function() {
        hideLoading();
        showToast('Connection error', 'error');
        location.reload();
    });
}

function deleteAlert(alertId) {
    confirmAction(
        'Delete Alert',
        'Are you sure you want to delete this price alert?',
        function() {
            showLoading();
            $.post(APP_URL + '/ajax/delete-alert.php', {
                alert_id: alertId
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                }
            }).fail(function() {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    );
}
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>
