<?php
/**
 * ============================================================================
 * prices/set-alert.php - Create Price Alert (Enhanced)
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Set Price Alert';
$userId = getUserId();

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

// Get product types
$productTypes = $priceClass->getProductTypes();

// Pre-selected product from query string
$preselectedProduct = $_GET['product'] ?? '';

// Handle form submission
if (isPost()) {
    $data = [
        'product_type' => $_POST['product_type'],
        'target_price' => $_POST['target_price'],
        'condition' => $_POST['condition']
    ];
    
    $result = $priceClass->createAlert($userId, $data['product_type'], $data['target_price'], $data['condition']);
    
    if ($result['success']) {
        redirect('/prices/alerts.php', $result['message'], 'success');
    } else {
        setFlashMessage($result['message'], 'error');
    }
}

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

<style>
.alert-wizard {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 3rem 0;
    margin-bottom: 2rem;
    border-radius: 15px;
}

.wizard-steps {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 1rem;
    margin-bottom: 2rem;
}

.wizard-step {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    transition: all 0.3s;
}

.wizard-step.active {
    background: white;
    color: #667eea;
    transform: scale(1.2);
}

.wizard-step.completed {
    background: #10b981;
    color: white;
}

.cursor-pointer {
    cursor: pointer;
}

.alert-option {
    transition: all 0.3s ease;
    border: 3px solid #e5e7eb;
    border-radius: 15px;
    overflow: hidden;
}

.alert-option:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    border-color: #059669;
}

.alert-option.selected {
    border-color: #059669;
    background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
}

.alert-option input[type="radio"]:checked ~ label {
    color: #059669;
}

.price-input-wrapper {
    position: relative;
}

.currency-symbol {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    font-weight: bold;
    color: #6b7280;
    font-size: 1.25rem;
}

.price-input {
    padding-left: 60px;
    font-size: 1.5rem;
    font-weight: bold;
    color: #059669;
}

.current-price-card {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-left: 5px solid #f59e0b;
    padding: 1.5rem;
    border-radius: 10px;
    margin-bottom: 1.5rem;
}

.benefit-item {
    display: flex;
    align-items: start;
    gap: 1rem;
    padding: 1rem;
    background: #f9fafb;
    border-radius: 10px;
    margin-bottom: 1rem;
    transition: all 0.3s;
}

.benefit-item:hover {
    background: #f3f4f6;
    transform: translateX(5px);
}

.benefit-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #059669;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.preview-card {
    background: linear-gradient(135deg, #ede9fe 0%, #ddd6fe 100%);
    border-left: 5px solid #8b5cf6;
    padding: 1.5rem;
    border-radius: 10px;
}

.step-content {
    display: none;
}

.step-content.active {
    display: block;
    animation: fadeIn 0.5s;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.success-animation {
    width: 100px;
    height: 100px;
    margin: 0 auto 2rem;
    border-radius: 50%;
    background: #10b981;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.1);
    }
}
</style>

<div class="container-fluid py-4">
    <!-- Wizard Header -->
    <div class="alert-wizard text-white text-center">
        <div class="container">
            <h1 class="display-5 mb-3">
                <i class="bi bi-bell-fill"></i> Create Price Alert
            </h1>
            <p class="lead mb-4">Get notified when prices match your target</p>
            
            <!-- Progress Steps -->
            <div class="wizard-steps">
                <div class="wizard-step active" id="step1Indicator">1</div>
                <div style="width: 60px; height: 2px; background: rgba(255,255,255,0.3);"></div>
                <div class="wizard-step" id="step2Indicator">2</div>
                <div style="width: 60px; height: 2px; background: rgba(255,255,255,0.3);"></div>
                <div class="wizard-step" id="step3Indicator">3</div>
            </div>
        </div>
    </div>

    <div class="container" style="max-width: 900px;">
        <div class="row">
            <!-- Main Form Area -->
            <div class="col-lg-8">
                <div class="card border-0 shadow-lg">
                    <div class="card-body p-4 p-md-5">
                        <form method="POST" id="alertForm">
                            <!-- Step 1: Select Product -->
                            <div class="step-content active" id="step1">
                                <h4 class="mb-4">
                                    <span class="badge bg-success me-2">Step 1</span>
                                    Select Product
                                </h4>
                                
                                <div class="mb-4">
                                    <label class="form-label fw-semibold fs-5">
                                        Which product do you want to track?
                                    </label>
                                    <select class="form-select form-select-lg" name="product_type" id="productSelect" required>
                                        <option value="">Choose a product...</option>
                                        <?php foreach ($productTypes as $type): ?>
                                            <option value="<?php echo htmlspecialchars($type['product_type']); ?>"
                                                    <?php echo $preselectedProduct === $type['product_type'] ? 'selected' : ''; ?>>
                                                <?php 
                                                $icons = [
                                                    'maize' => '🌽',
                                                    'sugar_cane' => '🎋',
                                                    'vegetables' => '🥬',
                                                    'poultry' => '🐔',
                                                    'coffee' => '☕',
                                                    'beans' => '🫘',
                                                    'cassava' => '🥔'
                                                ];
                                                echo ($icons[$type['product_type']] ?? '🌾') . ' ';
                                                echo ucwords(str_replace('_', ' ', $type['product_type'])); 
                                                ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <!-- Current Price Display -->
                                <div id="currentPriceCard" style="display: none;">
                                    <div class="current-price-card">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <small class="text-muted d-block mb-1">Current Market Average</small>
                                                <h2 class="mb-0 text-warning" id="currentPrice">-</h2>
                                            </div>
                                            <div class="text-end">
                                                <i class="bi bi-graph-up" style="font-size: 3rem; opacity: 0.5;"></i>
                                            </div>
                                        </div>
                                        <small class="text-muted">
                                            <i class="bi bi-info-circle"></i> Based on recent market data
                                        </small>
                                    </div>
                                </div>

                                <button type="button" class="btn btn-success btn-lg w-100" onclick="nextStep(2)">
                                    Next: Set Condition <i class="bi bi-arrow-right"></i>
                                </button>
                            </div>

                            <!-- Step 2: Alert Condition -->
                            <div class="step-content" id="step2">
                                <h4 class="mb-4">
                                    <span class="badge bg-success me-2">Step 2</span>
                                    Alert Condition
                                </h4>

                                <p class="text-muted mb-4">When should we notify you?</p>

                                <div class="row g-4 mb-4">
                                    <div class="col-md-6">
                                        <div class="alert-option">
                                            <input type="radio" class="form-check-input d-none" name="condition" 
                                                   value="below" id="conditionBelow" required>
                                            <label for="conditionBelow" class="cursor-pointer w-100 p-0">
                                                <div class="card-body text-center p-4">
                                                    <div class="mb-3">
                                                        <i class="bi bi-arrow-down-circle text-success" 
                                                           style="font-size: 4rem;"></i>
                                                    </div>
                                                    <h4 class="mb-2">Price Drops Below</h4>
                                                    <p class="text-muted mb-0">
                                                        Perfect for buyers looking for good deals
                                                    </p>
                                                    <div class="mt-3">
                                                        <span class="badge bg-success">Buying Opportunity</span>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="alert-option">
                                            <input type="radio" class="form-check-input d-none" name="condition" 
                                                   value="above" id="conditionAbove" required>
                                            <label for="conditionAbove" class="cursor-pointer w-100 p-0">
                                                <div class="card-body text-center p-4">
                                                    <div class="mb-3">
                                                        <i class="bi bi-arrow-up-circle text-danger" 
                                                           style="font-size: 4rem;"></i>
                                                    </div>
                                                    <h4 class="mb-2">Price Rises Above</h4>
                                                    <p class="text-muted mb-0">
                                                        Perfect for sellers looking to maximize profit
                                                    </p>
                                                    <div class="mt-3">
                                                        <span class="badge bg-danger">Selling Opportunity</span>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                <div class="d-flex gap-2">
                                    <button type="button" class="btn btn-outline-secondary btn-lg" onclick="prevStep(1)">
                                        <i class="bi bi-arrow-left"></i> Back
                                    </button>
                                    <button type="button" class="btn btn-success btn-lg flex-grow-1" onclick="nextStep(3)">
                                        Next: Set Price <i class="bi bi-arrow-right"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Step 3: Target Price -->
                            <div class="step-content" id="step3">
                                <h4 class="mb-4">
                                    <span class="badge bg-success me-2">Step 3</span>
                                    Target Price
                                </h4>

                                <p class="text-muted mb-4">At what price should we alert you?</p>

                                <div class="mb-4">
                                    <label class="form-label fw-semibold fs-5">Enter Target Price</label>
                                    <div class="price-input-wrapper">
                                        <span class="currency-symbol">UGX</span>
                                        <input type="number" class="form-control form-control-lg price-input" 
                                               name="target_price" id="targetPrice" min="0" step="100" 
                                               placeholder="0" required>
                                    </div>
                                    <small class="text-muted">
                                        <i class="bi bi-lightbulb"></i> 
                                        Tip: Check current market prices to set a realistic target
                                    </small>
                                </div>

                                <!-- Preview -->
                                <div id="alertPreview" class="preview-card" style="display: none;">
                                    <h5 class="mb-3">
                                        <i class="bi bi-eye"></i> Alert Preview
                                    </h5>
                                    <div class="d-flex align-items-center gap-3">
                                        <div class="flex-shrink-0">
                                            <div class="success-animation" style="width: 60px; height: 60px; animation: none;">
                                                <i class="bi bi-bell-fill fs-3 text-white"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1">
                                            <p class="mb-0 fs-5" id="previewText"></p>
                                        </div>
                                    </div>
                                </div>

                                <div class="d-flex gap-2 mt-4">
                                    <button type="button" class="btn btn-outline-secondary btn-lg" onclick="prevStep(2)">
                                        <i class="bi bi-arrow-left"></i> Back
                                    </button>
                                    <button type="submit" class="btn btn-success btn-lg flex-grow-1">
                                        <i class="bi bi-check-circle"></i> Create Alert
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Benefits -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom">
                        <h5 class="mb-0">
                            <i class="bi bi-star-fill text-warning"></i> Benefits
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="benefit-item">
                            <div class="benefit-icon">
                                <i class="bi bi-bell"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Instant Notifications</h6>
                                <small class="text-muted">Get alerted immediately when price targets are met</small>
                            </div>
                        </div>

                        <div class="benefit-item">
                            <div class="benefit-icon">
                                <i class="bi bi-graph-up"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Better Decisions</h6>
                                <small class="text-muted">Buy low, sell high with timely price information</small>
                            </div>
                        </div>

                        <div class="benefit-item">
                            <div class="benefit-icon">
                                <i class="bi bi-clock"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Save Time</h6>
                                <small class="text-muted">No need to constantly check market prices</small>
                            </div>
                        </div>

                        <div class="benefit-item">
                            <div class="benefit-icon">
                                <i class="bi bi-shield-check"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Always On</h6>
                                <small class="text-muted">24/7 price monitoring, even when you're offline</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tips -->
                <div class="card border-0 shadow-sm bg-light">
                    <div class="card-body">
                        <h6 class="mb-3">
                            <i class="bi bi-lightbulb-fill text-warning"></i> Pro Tips
                        </h6>
                        <ul class="small mb-0">
                            <li class="mb-2">Set multiple alerts for different price points</li>
                            <li class="mb-2">Check historical trends before setting targets</li>
                            <li class="mb-2">Enable notifications on your device for instant alerts</li>
                            <li class="mb-0">You can edit or delete alerts anytime</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentStep = 1;

// Product selection handler
$('#productSelect').on('change', function() {
    const product = $(this).val();
    if (product) {
        loadCurrentPrice(product);
    } else {
        $('#currentPriceCard').hide();
    }
    updatePreview();
});

// Load current price
function loadCurrentPrice(product) {
    $.get(APP_URL + '/ajax/get-current-price.php', { product: product }, function(response) {
        if (response.success && response.data) {
            $('#currentPrice').text('UGX ' + response.data.avg_price.toLocaleString());
            $('#currentPriceCard').fadeIn();
        }
    }).fail(function() {
        // If AJAX fails, just hide the card
        $('#currentPriceCard').hide();
    });
}

// Load price if product is preselected
<?php if ($preselectedProduct): ?>
loadCurrentPrice('<?php echo $preselectedProduct; ?>');
<?php endif; ?>

// Step navigation
function nextStep(step) {
    // Validate current step
    if (currentStep === 1 && !$('#productSelect').val()) {
        showToast('Please select a product', 'warning');
        return;
    }
    if (currentStep === 2 && !$('input[name="condition"]:checked').val()) {
        showToast('Please select an alert condition', 'warning');
        return;
    }
    
    $('.step-content').removeClass('active');
    $('#step' + step).addClass('active');
    
    $('.wizard-step').removeClass('active');
    for (let i = 1; i < step; i++) {
        $('#step' + i + 'Indicator').addClass('completed');
    }
    $('#step' + step + 'Indicator').addClass('active');
    
    currentStep = step;
    
    // Scroll to top
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function prevStep(step) {
    nextStep(step);
}

// Handle alert option selection
$('.alert-option').on('click', function() {
    const condition = $(this).find('input[type="radio"]').val();
    $('.alert-option').removeClass('selected');
    $(this).addClass('selected');
    $('input[name="condition"][value="' + condition + '"]').prop('checked', true);
    updatePreview();
});

// Update preview
function updatePreview() {
    const product = $('#productSelect option:selected').text().trim();
    const condition = $('input[name="condition"]:checked').val();
    const price = $('#targetPrice').val();

    if (product && product !== 'Choose a product...' && condition && price) {
        const conditionText = condition === 'below' ? 'drops below' : 'rises above';
        const text = `Notify me when ${product} price ${conditionText} UGX ${parseFloat(price).toLocaleString()}`;
        $('#previewText').text(text);
        $('#alertPreview').fadeIn();
    } else {
        $('#alertPreview').hide();
    }
}

// Update preview on price input
$('#targetPrice').on('input change', updatePreview);
$('input[name="condition"]').on('change', updatePreview);

// Form submission
$('#alertForm').on('submit', function(e) {
    if (!$('#targetPrice').val() || parseFloat($('#targetPrice').val()) <= 0) {
        e.preventDefault();
        showToast('Please enter a valid target price', 'error');
        return false;
    }
});
</script>

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