<?php
/**
 * Admin Negotiations Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Negotiations';

// Handle response
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['respond'])) {
    $negotiation_id = (int)$_POST['negotiation_id'];
    $status = sanitize($_POST['status']);
    $admin_message = sanitize($_POST['admin_message'] ?? '');
    $counter_price = !empty($_POST['counter_price']) ? (float)$_POST['counter_price'] : null;
    
    if (respond_to_negotiation($negotiation_id, $status, $admin_message, $counter_price)) {
        set_flash_message('Response sent successfully!', 'success');
    } else {
        set_flash_message('Failed to send response.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filters
$status_filter = sanitize($_GET['status'] ?? '');

// Build query
$sql = "SELECT n.*, p.name as product_name, p.slug as product_slug, p.price as original_price, u.name as user_name, u.email as user_email 
        FROM negotiations n 
        JOIN products p ON n.product_id = p.id 
        JOIN users u ON n.user_id = u.id 
        WHERE 1=1";
$count_sql = "SELECT COUNT(*) FROM negotiations n WHERE 1=1";
$params = [];

if ($status_filter) {
    $sql .= " AND n.status = ?";
    $count_sql .= " AND n.status = ?";
    $params[] = $status_filter;
}

$sql .= " ORDER BY n.created_at DESC LIMIT ? OFFSET ?";

// Get total count
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_negotiations = $stmt->fetchColumn();
$total_pages = ceil($total_negotiations / $per_page);

// Get negotiations
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge($params, [$per_page, $offset]));
$negotiations = $stmt->fetchAll();

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

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-handshake me-2"></i>Price Negotiations</h1>
    </div>
    
    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="accepted" <?php echo $status_filter === 'accepted' ? 'selected' : ''; ?>>Accepted</option>
                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        <option value="expired" <?php echo $status_filter === 'expired' ? 'selected' : ''; ?>>Expired</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter me-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Negotiations Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Customer</th>
                            <th>Original Price</th>
                            <th>Offered Price</th>
                            <th>Discount</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($negotiations as $negotiation): 
                            $discount = calculate_discount($negotiation['original_price'], $negotiation['offered_price']);
                        ?>
                        <tr>
                            <td>
                                <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $negotiation['product_slug']; ?>" target="_blank">
                                    <?php echo sanitize($negotiation['product_name']); ?>
                                </a>
                            </td>
                            <td>
                                <?php echo sanitize($negotiation['user_name']); ?>
                                <small class="d-block text-muted"><?php echo sanitize($negotiation['user_email']); ?></small>
                            </td>
                            <td><?php echo format_price($negotiation['original_price']); ?></td>
                            <td><strong class="text-primary"><?php echo format_price($negotiation['offered_price']); ?></strong></td>
                            <td>
                                <span class="badge bg-success">-<?php echo $discount; ?>%</span>
                            </td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo match($negotiation['status']) {
                                        'accepted' => 'success',
                                        'rejected' => 'danger',
                                        'pending' => 'warning',
                                        'expired' => 'secondary',
                                        default => 'secondary'
                                    };
                                ?>">
                                    <?php echo ucfirst($negotiation['status']); ?>
                                </span>
                            </td>
                            <td><?php echo format_date($negotiation['created_at']); ?></td>
                            <td>
                                <?php if ($negotiation['status'] === 'pending'): ?>
                                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#respondModal<?php echo $negotiation['id']; ?>">
                                    <i class="fas fa-reply me-1"></i>Respond
                                </button>
                                <?php else: ?>
                                <button type="button" class="btn btn-sm btn-secondary" data-bs-toggle="modal" data-bs-target="#viewModal<?php echo $negotiation['id']; ?>">
                                    <i class="fas fa-eye me-1"></i>View
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        
                        <!-- Respond Modal -->
                        <div class="modal fade" id="respondModal<?php echo $negotiation['id']; ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content bg-dark">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Respond to Offer</h5>
                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                    </div>
                                    <form method="POST">
                                        <div class="modal-body">
                                            <input type="hidden" name="negotiation_id" value="<?php echo $negotiation['id']; ?>">
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Product</label>
                                                <input type="text" class="form-control" value="<?php echo sanitize($negotiation['product_name']); ?>" disabled>
                                            </div>
                                            
                                            <div class="row mb-3">
                                                <div class="col-6">
                                                    <label class="form-label">Original Price</label>
                                                    <input type="text" class="form-control" value="<?php echo format_price($negotiation['original_price']); ?>" disabled>
                                                </div>
                                                <div class="col-6">
                                                    <label class="form-label">Offered Price</label>
                                                    <input type="text" class="form-control" value="<?php echo format_price($negotiation['offered_price']); ?>" disabled>
                                                </div>
                                            </div>
                                            
                                            <?php if ($negotiation['message']): ?>
                                            <div class="mb-3">
                                                <label class="form-label">Customer Message</label>
                                                <textarea class="form-control" rows="3" disabled><?php echo sanitize($negotiation['message']); ?></textarea>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Response <span class="text-danger">*</span></label>
                                                <select name="status" class="form-select" required>
                                                    <option value="">Select response...</option>
                                                    <option value="accepted">Accept Offer</option>
                                                    <option value="rejected">Reject Offer</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Message to Customer</label>
                                                <textarea name="admin_message" class="form-control" rows="3" placeholder="Optional message..."></textarea>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                            <button type="submit" name="respond" class="btn btn-primary">Send Response</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <!-- View Modal -->
                        <div class="modal fade" id="viewModal<?php echo $negotiation['id']; ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content bg-dark">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Negotiation Details</h5>
                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="mb-3">
                                            <label class="form-label">Product</label>
                                            <input type="text" class="form-control" value="<?php echo sanitize($negotiation['product_name']); ?>" disabled>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-6">
                                                <label class="form-label">Original Price</label>
                                                <input type="text" class="form-control" value="<?php echo format_price($negotiation['original_price']); ?>" disabled>
                                            </div>
                                            <div class="col-6">
                                                <label class="form-label">Offered Price</label>
                                                <input type="text" class="form-control" value="<?php echo format_price($negotiation['offered_price']); ?>" disabled>
                                            </div>
                                        </div>
                                        
                                        <?php if ($negotiation['message']): ?>
                                        <div class="mb-3">
                                            <label class="form-label">Customer Message</label>
                                            <textarea class="form-control" rows="3" disabled><?php echo sanitize($negotiation['message']); ?></textarea>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($negotiation['admin_message']): ?>
                                        <div class="mb-3">
                                            <label class="form-label">Your Response</label>
                                            <textarea class="form-control" rows="3" disabled><?php echo sanitize($negotiation['admin_message']); ?></textarea>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Status</label>
                                            <input type="text" class="form-control" value="<?php echo ucfirst($negotiation['status']); ?>" disabled>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Responded At</label>
                                            <input type="text" class="form-control" value="<?php echo $negotiation['responded_at'] ? format_datetime($negotiation['responded_at']) : 'Not yet responded'; ?>" disabled>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="card-footer">
            <nav>
                <ul class="pagination justify-content-center mb-0">
                    <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

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