<?php
/**
 * Price Negotiation Page
 * Digital Marketplace
 */

require_once __DIR__ . '/config/database.php';

$page_title = 'Price Negotiation';

// Get product
$product_id = (int)($_GET['product'] ?? 0);
$product = null;

if ($product_id) {
    $product = get_product_by_id($product_id);
}

if (!$product) {
    set_flash_message('Product not found.', 'error');
    header('Location: ' . BASE_URL . '/products.php');
    exit;
}

$errors = [];
$success = false;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!is_user_logged_in()) {
        $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
        header('Location: ' . BASE_URL . '/login.php');
        exit;
    }
    
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $offered_price = (float)($_POST['offered_price'] ?? 0);
        $message = sanitize($_POST['message'] ?? '');
        
        if ($offered_price <= 0) {
            $errors[] = 'Please enter a valid offer price.';
        } elseif ($offered_price >= $product['price']) {
            $errors[] = 'Your offer must be lower than the original price.';
        }
        
        if (empty($errors)) {
            if (create_negotiation($product_id, get_current_user_id(), $offered_price, $message)) {
                $success = true;
                set_flash_message('Your offer has been submitted! We will review it shortly.', 'success');
                
                // Send admin notification
                send_admin_notification('New Negotiation', "New negotiation offer for {$product['name']} at " . format_price($offered_price));
            } else {
                $errors[] = 'Failed to submit offer. Please try again.';
            }
        }
    }
}

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

<section class="section">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8" data-aos="fade-up">
                <div class="card">
                    <div class="card-header">
                        <h4 class="mb-0"><i class="fas fa-handshake me-2"></i>Price Negotiation</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($success): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-check-circle fa-4x text-success mb-4"></i>
                                <h3>Offer Submitted!</h3>
                                <p class="text-muted mb-4">
                                    Your offer has been received. We'll review it and get back to you soon.
                                </p>
                                <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $product['slug']; ?>" class="btn btn-primary">
                                    <i class="fas fa-arrow-left me-2"></i>Back to Product
                                </a>
                            </div>
                        <?php else: ?>
                            <!-- Product Info -->
                            <div class="d-flex align-items-center mb-4 p-3 bg-dark rounded">
                                <img src="<?php echo get_product_image_url($product); ?>" 
                                     alt="<?php echo sanitize($product['name']); ?>"
                                     class="rounded me-3"
                                     style="width: 80px; height: 80px; object-fit: cover;"
                                     onerror="this.src='<?php echo ASSETS_URL; ?>/images/no-image.jpg'">
                                <div>
                                    <h5 class="mb-1"><?php echo sanitize($product['name']); ?></h5>
                                    <p class="text-muted mb-0">Original Price: <strong class="text-primary"><?php echo format_price($product['price']); ?></strong></p>
                                </div>
                            </div>
                            
                            <?php if (!empty($errors)): ?>
                                <div class="alert alert-danger">
                                    <?php foreach ($errors as $error): ?>
                                        <p class="mb-1"><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?></p>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (!is_user_logged_in()): ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    Please <a href="<?php echo BASE_URL; ?>/login.php">login</a> or <a href="<?php echo BASE_URL; ?>/register.php">register</a> to submit a price offer.
                                </div>
                            <?php else: ?>
                                <form method="POST">
                                    <?php echo csrf_field(); ?>
                                    
                                    <div class="mb-4">
                                        <label for="offered_price" class="form-label">Your Offer Price <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                                            <input type="number" class="form-control" id="offered_price" 
                                                   name="offered_price" step="0.01" min="0.01" 
                                                   max="<?php echo $product['price'] - 0.01; ?>" required
                                                   placeholder="Enter your offer">
                                        </div>
                                        <small class="text-muted">Enter an amount lower than <?php echo format_price($product['price']); ?></small>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <label for="message" class="form-label">Message (Optional)</label>
                                        <textarea class="form-control" id="message" name="message" rows="4"
                                                  placeholder="Explain why you're making this offer..."></textarea>
                                    </div>
                                    
                                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                        <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $product['slug']; ?>" class="btn btn-outline-light">Cancel</a>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-paper-plane me-2"></i>Submit Offer
                                        </button>
                                    </div>
                                </form>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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