<?php
/**
 * ============================================================================
 * prices/submit-price.php - User Price Submission Form
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Submit Market Price';
$userId = getUserId();

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

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

// Handle form submission
if (isPost()) {
    $uploadedPhoto = null;
    
    // Handle photo upload
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../assets/uploads/price-reports/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileExtension = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
        $allowedExtensions = ['jpg', 'jpeg', 'png'];
        
        if (in_array($fileExtension, $allowedExtensions)) {
            $fileName = 'price_' . $userId . '_' . time() . '.' . $fileExtension;
            $uploadPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadPath)) {
                $uploadedPhoto = '/assets/uploads/price-reports/' . $fileName;
            }
        }
    }
    
    // Insert price report
    try {
        $sql = "INSERT INTO price_reports 
                (user_id, product_type, market_location, price, unit, quantity_available, 
                 quality_rating, photo_url, notes, verification_status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')";
        
        $stmt = $db->prepare($sql);
        $result = $stmt->execute([
            $userId,
            $_POST['product_type'],
            $_POST['market_location'],
            $_POST['price'],
            $_POST['unit'],
            $_POST['quantity_available'] ?? null,
            $_POST['quality_rating'] ?? null,
            $uploadedPhoto,
            $_POST['notes'] ?? null
        ]);
        
        if ($result) {
            // Notify admins
            $notifSql = "INSERT INTO notifications (user_id, title, message, type, icon, link)
                        SELECT id, 'New Price Report', 'A user submitted a new price report', 
                               'info', 'tag', '/admin/price-reports.php'
                        FROM users WHERE user_type = 'admin'";
            $db->query($notifSql);
            
            redirect('/prices/', 'Thank you! Your price report has been submitted for verification.', 'success');
        }
    } catch (PDOException $e) {
        setFlashMessage('Error submitting price report. Please try again.', 'error');
    }
}

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

<style>
.submission-card {
    max-width: 800px;
    margin: 0 auto;
}

.photo-preview {
    max-width: 100%;
    max-height: 300px;
    border-radius: 10px;
    display: none;
    margin-top: 1rem;
}

.quality-option {
    cursor: pointer;
    transition: all 0.3s;
    padding: 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 10px;
    text-align: center;
}

.quality-option:hover {
    border-color: #059669;
    background: #f0fdf4;
}

.quality-option input[type="radio"]:checked + label {
    border-color: #059669;
    background: #059669;
    color: white;
}

.info-box {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 1.5rem;
    border-radius: 15px;
    margin-bottom: 2rem;
}

.unit-selector {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.unit-btn {
    flex: 1;
    min-width: 80px;
}
</style>

<div class="container py-4">
    <div class="submission-card">
        <!-- Header -->
        <div class="text-center mb-4">
            <h2>
                <i class="bi bi-plus-circle text-success"></i> Submit Market Price
            </h2>
            <p class="text-muted">Help fellow farmers by sharing current market prices</p>
        </div>

        <!-- Info Box -->
        <div class="info-box">
            <h5 class="mb-2">
                <i class="bi bi-info-circle"></i> Why Submit Prices?
            </h5>
            <p class="mb-0 opacity-75">
                Your price reports help create a real-time market information system that benefits 
                all farmers. Accurate prices lead to better selling decisions and fair market access.
            </p>
        </div>

        <!-- Submission Form -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-bottom">
                <h5 class="mb-0">
                    <i class="bi bi-clipboard-data"></i> Price Information
                </h5>
            </div>
            <div class="card-body p-4">
                <form method="POST" enctype="multipart/form-data" id="priceSubmissionForm">
                    <!-- Product Type -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="bi bi-basket"></i> Product Type
                            <span class="text-danger">*</span>
                        </label>
                        <select class="form-select form-select-lg" name="product_type" required>
                            <option value="">Select product...</option>
                            <?php foreach ($productTypes as $type): ?>
                                <option value="<?php echo htmlspecialchars($type['product_type']); ?>">
                                    <?php echo ucwords(str_replace('_', ' ', $type['product_type'])); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Market Location -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="bi bi-geo-alt"></i> Market Location
                            <span class="text-danger">*</span>
                        </label>
                        <div class="row g-2">
                            <div class="col-md-8">
                                <select class="form-select form-select-lg" name="market_location" id="marketSelect" required>
                                    <option value="">Select market...</option>
                                    <?php foreach ($markets as $market): ?>
                                        <option value="<?php echo htmlspecialchars($market); ?>">
                                            <?php echo htmlspecialchars($market); ?>
                                        </option>
                                    <?php endforeach; ?>
                                    <option value="other">Other (specify below)</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <button type="button" class="btn btn-outline-primary btn-lg w-100" onclick="getCurrentLocation()">
                                    <i class="bi bi-geo"></i> Use My Location
                                </button>
                            </div>
                        </div>
                        <input type="text" class="form-control mt-2" id="customMarket" 
                               placeholder="Enter market name" style="display: none;">
                    </div>

                    <!-- Price and Unit -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-currency-exchange"></i> Price (UGX)
                                <span class="text-danger">*</span>
                            </label>
                            <input type="number" class="form-control form-control-lg" name="price" 
                                   min="0" step="100" placeholder="e.g., 5000" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-rulers"></i> Unit
                                <span class="text-danger">*</span>
                            </label>
                            <div class="unit-selector">
                                <button type="button" class="btn btn-outline-success unit-btn" 
                                        onclick="selectUnit('kg')">kg</button>
                                <button type="button" class="btn btn-outline-success unit-btn" 
                                        onclick="selectUnit('bag')">Bag</button>
                                <button type="button" class="btn btn-outline-success unit-btn" 
                                        onclick="selectUnit('tray')">Tray</button>
                                <button type="button" class="btn btn-outline-success unit-btn" 
                                        onclick="selectUnit('piece')">Piece</button>
                            </div>
                            <input type="text" class="form-control mt-2" name="unit" id="unitInput" 
                                   placeholder="Or enter custom unit" required>
                        </div>
                    </div>

                    <!-- Optional: Quantity Available -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="bi bi-box-seam"></i> Quantity Available (Optional)
                        </label>
                        <input type="number" class="form-control" name="quantity_available" 
                               min="0" step="0.1" placeholder="e.g., 100">
                        <small class="text-muted">Approximately how much is available in the market?</small>
                    </div>

                    <!-- Quality Rating -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="bi bi-star"></i> Product Quality (Optional)
                        </label>
                        <div class="row g-2">
                            <div class="col-6 col-md-3">
                                <input type="radio" class="btn-check" name="quality_rating" 
                                       value="poor" id="qualityPoor">
                                <label class="quality-option w-100" for="qualityPoor">
                                    <div class="text-danger fs-3">😞</div>
                                    <div>Poor</div>
                                </label>
                            </div>
                            <div class="col-6 col-md-3">
                                <input type="radio" class="btn-check" name="quality_rating" 
                                       value="fair" id="qualityFair">
                                <label class="quality-option w-100" for="qualityFair">
                                    <div class="text-warning fs-3">😐</div>
                                    <div>Fair</div>
                                </label>
                            </div>
                            <div class="col-6 col-md-3">
                                <input type="radio" class="btn-check" name="quality_rating" 
                                       value="good" id="qualityGood">
                                <label class="quality-option w-100" for="qualityGood">
                                    <div class="text-success fs-3">🙂</div>
                                    <div>Good</div>
                                </label>
                            </div>
                            <div class="col-6 col-md-3">
                                <input type="radio" class="btn-check" name="quality_rating" 
                                       value="excellent" id="qualityExcellent">
                                <label class="quality-option w-100" for="qualityExcellent">
                                    <div class="text-success fs-3">😄</div>
                                    <div>Excellent</div>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Photo Upload -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="bi bi-camera"></i> Photo Evidence (Optional)
                        </label>
                        <input type="file" class="form-control" name="photo" 
                               accept="image/jpeg,image/png,image/jpg" id="photoInput">
                        <small class="text-muted">
                            Adding a photo increases the credibility of your report
                        </small>
                        <img id="photoPreview" class="photo-preview" alt="Preview">
                    </div>

                    <!-- Notes -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="bi bi-chat-left-text"></i> Additional Notes (Optional)
                        </label>
                        <textarea class="form-control" name="notes" rows="3" 
                                  placeholder="Any additional information about the price, market conditions, etc."></textarea>
                    </div>

                    <!-- Terms Agreement -->
                    <div class="mb-4">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="agreeTerms" required>
                            <label class="form-check-label" for="agreeTerms">
                                I confirm that this price information is accurate to the best of my knowledge
                            </label>
                        </div>
                    </div>

                    <!-- Submit Buttons -->
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-success btn-lg">
                            <i class="bi bi-check-circle"></i> Submit Price Report
                        </button>
                        <a href="<?php echo APP_URL; ?>/prices/" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle"></i> Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Benefits Info -->
        <div class="card border-0 bg-light mt-4">
            <div class="card-body">
                <h6 class="mb-3">
                    <i class="bi bi-trophy text-warning"></i> Benefits of Contributing
                </h6>
                <div class="row">
                    <div class="col-md-6 mb-2">
                        <i class="bi bi-check-circle text-success"></i> Build your reputation
                    </div>
                    <div class="col-md-6 mb-2">
                        <i class="bi bi-check-circle text-success"></i> Help your community
                    </div>
                    <div class="col-md-6 mb-2">
                        <i class="bi bi-check-circle text-success"></i> Access better market data
                    </div>
                    <div class="col-md-6 mb-2">
                        <i class="bi bi-check-circle text-success"></i> Earn verification badges
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Market selection handler
document.getElementById('marketSelect').addEventListener('change', function() {
    const customMarket = document.getElementById('customMarket');
    if (this.value === 'other') {
        customMarket.style.display = 'block';
        customMarket.required = true;
    } else {
        customMarket.style.display = 'none';
        customMarket.required = false;
    }
});

// Unit selector
function selectUnit(unit) {
    document.querySelectorAll('.unit-btn').forEach(btn => btn.classList.remove('active', 'btn-success'));
    event.target.classList.add('active', 'btn-success');
    document.getElementById('unitInput').value = unit;
}

// Photo preview
document.getElementById('photoInput').addEventListener('change', function() {
    const file = this.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('photoPreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
});

// Get current location
function getCurrentLocation() {
    if (navigator.geolocation) {
        showLoading();
        navigator.geolocation.getCurrentPosition(
            function(position) {
                hideLoading();
                // In a real implementation, you would reverse geocode these coordinates
                showToast('Location detected! Please select the nearest market from the list.', 'success');
                console.log('Lat:', position.coords.latitude, 'Lng:', position.coords.longitude);
            },
            function(error) {
                hideLoading();
                showToast('Could not detect location. Please select manually.', 'warning');
            }
        );
    } else {
        showToast('Geolocation is not supported by your browser', 'error');
    }
}

// Form validation
document.getElementById('priceSubmissionForm').addEventListener('submit', function(e) {
    const price = document.querySelector('input[name="price"]').value;
    
    if (parseFloat(price) < 0) {
        e.preventDefault();
        showToast('Please enter a valid price', 'error');
        return false;
    }
    
    if (!document.getElementById('agreeTerms').checked) {
        e.preventDefault();
        showToast('Please confirm the accuracy of your report', 'error');
        return false;
    }
});
</script>

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