<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Offers - Flex Market</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { font-family: 'Poppins', sans-serif; }
        body { background: #f5f5f5; }
        .sidebar { min-height: 100vh; background: linear-gradient(180deg, #9c27b0 0%, #673ab7 100%); box-shadow: 2px 0 10px rgba(0,0,0,0.1); }
        .sidebar .nav-link { color: rgba(255,255,255,0.85); padding: 14px 20px; border-radius: 10px; margin: 6px 0; transition: all 0.3s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: rgba(255,255,255,0.15); color: #fff; transform: translateX(5px); }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .offer-card { background: white; border-radius: 15px; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.08); margin-bottom: 20px; transition: all 0.3s; }
        .offer-card:hover { box-shadow: 0 5px 25px rgba(0,0,0,0.12); }
        .status-pending { background: #fff3cd; color: #856404; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status-accepted { background: #d4edda; color: #155724; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status-rejected { background: #f8d7da; color: #721c24; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .buyer-score { background: linear-gradient(135deg, #ffd700, #ffed4e); padding: 10px 15px; border-radius: 10px; font-weight: 600; display: inline-block; }
        .date-badge { background: #e3f2fd; color: #1976d2; padding: 8px 12px; border-radius: 8px; font-size: 13px; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>

            <div class="col-md-9 col-lg-10 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2><i class="bi bi-chat-left-text"></i> Offers Received</h2>
                        <p class="text-muted mb-0">Manage offers from buyers</p>
                    </div>
                </div>

                <!-- Filter Tabs -->
                <ul class="nav nav-pills mb-4">
                    <li class="nav-item">
                        <a class="nav-link <?= empty($status) ? 'active' : '' ?>" href="<?= base_url('seller/offers') ?>">All Offers</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?= $status === 'pending' ? 'active' : '' ?>" href="<?= base_url('seller/offers?status=pending') ?>">
                            Pending 
                            <span class="badge bg-warning text-dark"><?= count(array_filter($offers ?? [], fn($o) => $o['status'] === 'pending')) ?></span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?= $status === 'accepted' ? 'active' : '' ?>" href="<?= base_url('seller/offers?status=accepted') ?>">Accepted</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?= $status === 'rejected' ? 'active' : '' ?>" href="<?= base_url('seller/offers?status=rejected') ?>">Rejected</a>
                    </li>
                </ul>

                <!-- Offers List -->
                <?php if (empty($offers)): ?>
                    <div class="text-center py-5">
                        <i class="bi bi-inbox" style="font-size: 64px; color: #ccc;"></i>
                        <h5 class="mt-3 text-muted">No offers yet</h5>
                        <p class="text-muted">You'll see offers from buyers here</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($offers as $offer): ?>
                        <div class="offer-card">
                            <div class="row">
                                <div class="col-md-2">
                                    <img src="<?= base_url(esc($offer['product_image'] ?? 'placeholder.jpg')) ?>" 
                                         style="width: 100%; height: 120px; object-fit: cover; border-radius: 10px;">
                                </div>
                                <div class="col-md-6">
                                    <div class="d-flex justify-content-between mb-2">
                                        <h5 class="mb-1"><?= esc($offer['product_title']) ?></h5>
                                        <span class="status-<?= esc($offer['status']) ?>"><?= ucfirst($offer['status']) ?></span>
                                    </div>
                                    <p class="text-muted mb-2">
                                        <i class="bi bi-person"></i> <strong><?= esc($offer['buyer_name']) ?></strong>
                                    </p>
                                    
                                    <!-- S26 - Show buyer's total reliability score -->
                                    <div class="buyer-score mb-3">
                                        <i class="bi bi-star-fill"></i> Buyer Reliability: <?= number_format($offer['buyer_reliability_score'] ?? 0, 1) ?>/100
                                        <br><small class="text-muted">Renter Score: <?= number_format($offer['buyer_renter_score'] ?? 0, 1) ?></small>
                                    </div>

                                    <div class="mb-2">
                                        <span class="badge <?= $offer['offer_type'] === 'buy' ? 'bg-success' : 'bg-info' ?>">
                                            <?= ucfirst($offer['offer_type']) ?>
                                        </span>
                                        <strong class="ms-2">Offered: ₹<?= number_format($offer['offered_price'], 2) ?></strong>
                                        <?php if ($offer['offer_type'] === 'rent'): ?>
                                            <small class="text-muted">/day (Deposit: ₹<?= number_format($offer['deposit_amount'], 2) ?>)</small>
                                        <?php endif; ?>
                                    </div>

                                    <!-- S18, B16 - Show rental dates -->
                                    <?php if ($offer['offer_type'] === 'rent' && !empty($offer['rental_start_date'])): ?>
                                        <div class="mt-2">
                                            <span class="date-badge">
                                                <i class="bi bi-calendar-range"></i> 
                                                <?= date('d M Y', strtotime($offer['rental_start_date'])) ?> - 
                                                <?= date('d M Y', strtotime($offer['rental_end_date'])) ?>
                                                (<?= ceil((strtotime($offer['rental_end_date']) - strtotime($offer['rental_start_date'])) / 86400) ?> days)
                                            </span>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($offer['message']): ?>
                                        <p class="mt-2 mb-0 p-2 bg-light rounded">
                                            <small><i class="bi bi-chat-quote"></i> "<?= esc($offer['message']) ?>"</small>
                                        </p>
                                    <?php endif; ?>

                                    <small class="text-muted">
                                        <i class="bi bi-clock"></i> Received: <?= date('d M Y, h:i A', strtotime($offer['created_at'])) ?>
                                    </small>

                                    <!-- S27 - Show time remaining to reject within 1 day -->
                                    <?php if ($offer['status'] === 'accepted' && !empty($offer['accepted_at'])): ?>
                                        <?php 
                                            $acceptedTime = strtotime($offer['accepted_at']);
                                            $oneDayLater = $acceptedTime + 86400;
                                            $canReject = time() < $oneDayLater;
                                            $hoursLeft = max(0, floor(($oneDayLater - time()) / 3600));
                                        ?>
                                        <?php if ($canReject): ?>
                                            <div class="alert alert-warning mt-2 mb-0 p-2">
                                                <i class="bi bi-exclamation-triangle"></i> 
                                                You can still reject within <?= $hoursLeft ?> hour(s)
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <!-- S28 - Show if can reject before pickup -->
                                    <?php if ($offer['status'] === 'accepted' && $offer['offer_type'] === 'rent' && !empty($offer['rental_start_date'])): ?>
                                        <?php 
                                            $pickupDate = strtotime($offer['rental_start_date']);
                                            $oneDayBefore = $pickupDate - 86400;
                                            $canRejectBeforePickup = time() < $oneDayBefore;
                                            $daysLeft = max(0, floor(($pickupDate - time()) / 86400));
                                        ?>
                                        <?php if ($canRejectBeforePickup && $daysLeft > 0): ?>
                                            <div class="alert alert-info mt-2 mb-0 p-2">
                                                <i class="bi bi-info-circle"></i> 
                                                Pickup in <?= $daysLeft ?> day(s). Can reject until 1 day before.
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>

                                <div class="col-md-4 text-end">
                                    <?php if ($offer['status'] === 'pending'): ?>
                                        <div class="d-grid gap-2">
                                            <button class="btn btn-success" onclick="acceptOffer(<?= $offer['id'] ?>, '<?= $offer['offer_type'] ?>')">
                                                <i class="bi bi-check-circle"></i> Accept Offer
                                            </button>
                                            <button class="btn btn-outline-danger" onclick="rejectOffer(<?= $offer['id'] ?>)">
                                                <i class="bi bi-x-circle"></i> Reject
                                            </button>
                                        </div>
                                    <?php elseif ($offer['status'] === 'accepted'): ?>
                                        <?php 
                                            // S27: Can reject within 1 day of acceptance
                                            $acceptedTime = strtotime($offer['accepted_at']);
                                            $canRejectByTime = time() < ($acceptedTime + 86400);
                                            
                                            // S28: Can reject 1 day before pickup
                                            $canRejectByPickup = false;
                                            if ($offer['offer_type'] === 'rent' && !empty($offer['rental_start_date'])) {
                                                $pickupDate = strtotime($offer['rental_start_date']);
                                                $canRejectByPickup = time() < ($pickupDate - 86400);
                                            }
                                            
                                            $canReject = $canRejectByTime || $canRejectByPickup;
                                        ?>
                                        <span class="badge bg-success p-3">
                                            <i class="bi bi-check-circle"></i> Accepted
                                        </span>
                                        <?php if ($canReject): ?>
                                            <button class="btn btn-outline-warning btn-sm mt-2" onclick="rejectOffer(<?= $offer['id'] ?>)">
                                                <i class="bi bi-x-circle"></i> Reject Offer
                                            </button>
                                            <small class="d-block text-muted mt-1">
                                                <?= $canRejectByTime ? 'Within 24h window' : 'Before pickup' ?>
                                            </small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="badge bg-danger p-3">
                                            <i class="bi bi-x-circle"></i> Rejected
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function acceptOffer(offerId, offerType) {
            if (!confirm('Accept this offer?')) return;
            
            fetch(`/seller/accept-offer/${offerId}`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({})
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Failed to accept offer'));
                }
            })
            .catch(err => {
                console.error(err);
                alert('Error accepting offer');
            });
        }

        function rejectOffer(offerId) {
            if (!confirm('Reject this offer? This action cannot be undone.')) return;
            
            fetch(`/seller/reject-offer/${offerId}`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({})
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Failed to reject offer'));
                }
            })
            .catch(err => {
                console.error(err);
                alert('Error rejecting offer');
            });
        }
    </script>
</body>
</html>
