<?php include 'header.php'; ?>

<?php
// Pagination settings
$bidsPerPage = 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($currentPage - 1) * $bidsPerPage;

// Get total count
$totalBids = 0;
$stmt = $conn->prepare("SELECT COUNT(*) as total FROM upwork_bids_history WHERE user_id = ?");
$stmt->bind_param("s", $userId);
if ($stmt->execute()) {
    $res = $stmt->get_result();
    if ($res && $res->num_rows > 0) {
        $totalBids = $res->fetch_assoc()['total'];
    }
}
$stmt->close();

// Calculate total pages
$totalPages = ceil($totalBids / $bidsPerPage);

// Load bid history from database with pagination
$bids = [];
$stmt = $conn->prepare("SELECT * FROM upwork_bids_history WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bind_param("sii", $userId, $bidsPerPage, $offset);
if ($stmt->execute()) {
    $res = $stmt->get_result();
    if ($res && $res->num_rows > 0) {
        while ($row = $res->fetch_assoc()) {
            $bids[] = $row;
        }
    }
}
$stmt->close();
?>

<div class="page-content">
    <div class="container-fluid">

        <!-- start page title -->
        <div class="row">
            <div class="col-12">
                <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-transparent">
                    <h4 class="mb-sm-0">My Bids</h4>

                    <div class="page-title-right">
                        <ol class="breadcrumb m-0">
                            <li class="breadcrumb-item"><a href="javascript: void(0);">Upwork</a></li>
                            <li class="breadcrumb-item active">My Bids</li>
                        </ol>
                    </div>

                </div>
            </div>
        </div>
        <!-- end page title -->

        <div class="row">
            <div class="col-12">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <h5 class="card-title mb-0">Bid History</h5>
                                <p class="text-muted">View all your submitted bids</p>
                            </div>
                            <div class="col-md-6 text-end">
                                <span class="badge bg-primary"><?php echo $totalBids; ?> Total Bids</span>
                                <?php if ($totalPages > 1): ?>
                                    <span class="badge bg-info ms-2">Page <?php echo $currentPage; ?> of <?php echo $totalPages; ?></span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <?php if (empty($bids)): ?>
                            <div class="text-center py-5">
                                <i class="ri-file-list-line" style="font-size: 48px; color: #6c757d;"></i>
                                <h5 class="mt-3">No Bids Found</h5>
                                <p class="text-muted">You haven't submitted any bids yet.</p>
                                <a href="search.php" class="btn btn-primary">Start Searching</a>
                            </div>
                        <?php else: ?>
                            <div id="bidsContainer">
                                <?php foreach ($bids as $bid): 
                                    $client = json_decode($bid['client'], true);
                                    $skills = json_decode($bid['skills'], true);
                                    $timeAgo = getTimeAgo($bid['created_at']);
                                ?>
                                    <div class="card mb-3" style="border-radius: 10px;">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <div class="flex-grow-1">
                                                    <h5 class="card-title mb-1">
                                                        <a href="https://www.upwork.com/jobs/<?php echo htmlspecialchars($bid['jcipher']); ?>/" target="_blank" rel="noopener noreferrer" class="text-decoration-none">
                                                            <?php echo htmlspecialchars($bid['jtitle']); ?>
                                                        </a>
                                                    </h5>
                                                    <div class="text-muted" style="font-size: 10px;">
                                                        Bid submitted <?php echo $timeAgo; ?>
                                                    </div>
                                                </div>
                                                <div class="d-flex align-items-center gap-2">
                                                    <?php if ($client && $client['paymentVerificationStatus'] === 'VERIFIED'): ?>
                                                        <span class="badge bg-success" style="font-size: 10px;"><i class="ri-verified-badge-line me-1" style="font-size: 12px;"></i>Payment Verified</span>
                                                    <?php endif; ?>
                                                    <a href="https://www.upwork.com/jobs/<?php echo htmlspecialchars($bid['jcipher']); ?>/" target="_blank" rel="noopener noreferrer" class="p-2">
                                                        <i class="ri-external-link-line" style="font-size: 14px;"></i>
                                                    </a>
                                                </div>
                                            </div>

                                            <div class="row mb-3">
                                                <div class="col-md-6">
                                                    <div class="d-flex align-items-center gap-3">
                                                        <?php if ($client && isset($client['totalReviews'])): ?>
                                                            <div class="d-flex align-items-center mt-2">
                                                                <?php 
                                                                $rating = $client['totalFeedback'] ?? 0;
                                                                for ($i = 0; $i < 5; $i++): 
                                                                    $starClass = $i < $rating ? 'ri-star-fill text-warning' : 'ri-star-fill text-muted';
                                                                ?>
                                                                    <i class="<?php echo $starClass; ?>" style="font-size: 16px;"></i>
                                                                <?php endfor; ?>
                                                                <small class="text-muted ms-1" style="font-size: 14px;">(<?php echo $client['totalReviews'] ?? 0; ?>)</small>
                                                            </div>
                                                        <?php endif; ?>
                                                        <?php if ($client && isset($client['country'])): ?>
                                                            <div class="text-muted" style="font-size: 14px;">
                                                                <i class="ri-map-pin-line me-1"></i>
                                                                <?php echo htmlspecialchars($client['country']); ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <div class="col-md-6 text-end">
                                                    <?php if ($client && isset($client['totalSpent']['amount'])): ?>
                                                        <div class="text-muted" style="font-size: 14px;">
                                                            <?php echo number_format($client['totalSpent']['amount']); ?> <?php echo $client['totalSpent']['isoCurrencyCode']; ?> spent
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>

                                            <div class="mb-2">
                                                <div class="d-flex align-items-center gap-3">
                                                    <?php if ($bid['jobType']): ?>
                                                        <span class="badge bg-secondary" style="font-size: 10px;"><?php echo htmlspecialchars($bid['jobType']); ?></span>
                                                    <?php endif; ?>
                                                    <?php if ($bid['jprice']): ?>
                                                        <span class="badge bg-info" style="font-size: 10px;"><?php echo htmlspecialchars($bid['jprice']); ?></span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>

                                            <?php if ($bid['description']): ?>
                                                <div class="card-text mb-4" style="font-size: 12px; line-height: 1.4;">
                                                    <?php echo htmlspecialchars(substr($bid['description'], 0, 300)) . (strlen($bid['description']) > 300 ? '...' : ''); ?>
                                                </div>
                                            <?php endif; ?>

                                            <?php if ($skills && is_array($skills)): ?>
                                                <div class="mb-3">
                                                    <div class="d-flex flex-wrap gap-1">
                                                        <?php foreach ($skills as $skill): ?>
                                                            <span class="badge bg-success" style="font-size: 10px;"><?php echo htmlspecialchars($skill); ?></span>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            <?php endif; ?>

                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <small class="text-muted">Bid Amount: <strong>$<?php echo htmlspecialchars($bid['price']); ?></strong></small>
                                                </div>
                                                <div>
                                                    <div class="text-success" style="font-size: 16px; font-weight: 600; text-align: center; padding: 10px;">
                                                        Applied
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Cover Letter Preview -->
                                            <div class="mt-3">
                                                <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#coverLetter<?php echo $bid['id']; ?>" aria-expanded="false">
                                                    <i class="ri-eye-line me-1"></i>View Cover Letter
                                                </button>
                                                <div class="collapse mt-2" id="coverLetter<?php echo $bid['id']; ?>">
                                                    <div class="card card-body bg-light" style="font-size: 12px; max-height: 200px; overflow-y: auto;">
                                                        <?php echo nl2br(htmlspecialchars($bid['cover_letter'])); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <!-- Pagination -->
                            <?php if ($totalPages > 1): ?>
                                <nav aria-label="Bids pagination" class="mt-4">
                                    <ul class="pagination justify-content-center">
                                        <!-- Previous Page -->
                                        <?php if ($currentPage > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $currentPage - 1; ?>">
                                                    <i class="ri-arrow-left-line"></i> Previous
                                                </a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">
                                                    <i class="ri-arrow-left-line"></i> Previous
                                                </span>
                                            </li>
                                        <?php endif; ?>

                                        <!-- Page Numbers -->
                                        <?php
                                        $startPage = max(1, $currentPage - 2);
                                        $endPage = min($totalPages, $currentPage + 2);
                                        
                                        // Show first page if not in range
                                        if ($startPage > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=1">1</a>
                                            </li>
                                            <?php if ($startPage > 2): ?>
                                                <li class="page-item disabled">
                                                    <span class="page-link">...</span>
                                                </li>
                                            <?php endif; ?>
                                        <?php endif; ?>

                                        <!-- Page numbers in range -->
                                        <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                                            <li class="page-item <?php echo $i == $currentPage ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                            </li>
                                        <?php endfor; ?>

                                        <!-- Show last page if not in range -->
                                        <?php if ($endPage < $totalPages): ?>
                                            <?php if ($endPage < $totalPages - 1): ?>
                                                <li class="page-item disabled">
                                                    <span class="page-link">...</span>
                                                </li>
                                            <?php endif; ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $totalPages; ?>"><?php echo $totalPages; ?></a>
                                            </li>
                                        <?php endif; ?>

                                        <!-- Next Page -->
                                        <?php if ($currentPage < $totalPages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $currentPage + 1; ?>">
                                                    Next <i class="ri-arrow-right-line"></i>
                                                </a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">
                                                    Next <i class="ri-arrow-right-line"></i>
                                                </span>
                                            </li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>

                                <!-- Pagination Info -->
                                <div class="text-center text-muted mt-2">
                                    Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $bidsPerPage, $totalBids); ?> of <?php echo $totalBids; ?> bids
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        
</div>

<?php
function getTimeAgo($datetime) {
    $time = time() - strtotime($datetime);
    
    if ($time < 60) return 'just now';
    if ($time < 3600) return floor($time/60) . ' minutes ago';
    if ($time < 86400) return floor($time/3600) . ' hours ago';
    if ($time < 2592000) return floor($time/86400) . ' days ago';
    if ($time < 31536000) return floor($time/2592000) . ' months ago';
    return floor($time/31536000) . ' years ago';
}
?>

<?php include 'footer.php'; ?>