<?php
// Include database configuration
include('../config/database.php');
session_start();

// Redirect to login if not logged in
if (!isset($_SESSION['assessor_id'])) {
    header("Location: login.php");
    exit();
}

$assessor_id = $_SESSION['assessor_id'];

// Fetch proposals assigned to the logged-in assessor
$sql = "SELECT proposals.id, proposals.full_name, proposals.business_idea_title, 
        COALESCE(assessments.total_score, 0) AS total_score
        FROM proposals
        JOIN proposal_assignments ON proposals.id = proposal_assignments.proposal_id
        LEFT JOIN (
            SELECT proposal_id, assessor_id, 
                   (idea_novelty + idea_breakthrough + idea_competitors + idea_technology_solution + 
                    idea_novel_future + market_need + market_problem + market_present_future + 
                    market_share + market_risk + market_timing + return_resources + 
                    return_profit + return_investors + return_team_capacity + advantage_competitors + 
                    advantage_better + advantage_protectable + impact_sdg + impact_jobs) AS total_score
            FROM assessments
            WHERE assessor_id = ?
        ) AS assessments ON proposals.id = assessments.proposal_id
        WHERE proposal_assignments.assessor_id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("ii", $assessor_id, $assessor_id);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    die("Database error: Unable to prepare statement.");
}

$conn->close();
?>

<?php include('header.php'); ?>
<div class="container mt-5">
    <h2 class="mb-4">Assigned Proposals</h2>
    <div class="row">
        <div class="col-md-4">
            <div class="list-group" id="proposalList">
                <?php if ($result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <a href="#" class="list-group-item list-group-item-action" data-id="<?php echo $row['id']; ?>">
                            <span <?php echo $row['total_score'] > 0 ? '' : 'class="fw-bold"'; ?>><?php echo htmlspecialchars($row['full_name']); ?></span><br>
                            <span><?php echo htmlspecialchars($row['business_idea_title']); ?></span>
                            <?php if ($row['total_score'] > 0): ?>
                                <?php
                                $totalScore = $row['total_score']; // Use the total score directly
                                $badgeClass = '';
                                if ($totalScore >= 70) {
                                    $badgeClass = 'bg-success';
                                } elseif ($totalScore >= 50) {
                                    $badgeClass = 'bg-warning';
                                } else {
                                    $badgeClass = 'bg-danger';
                                }
                                ?>
                                <span class="badge <?php echo $badgeClass; ?> float-end"><?php echo $totalScore; ?></span>
                            <?php endif; ?>
                        </a>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="alert alert-info" role="alert">
                        No proposals assigned yet.
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <div class="col-md-8">
            <div id="proposalContent" class="border p-3">
                <h5>Select a proposal to view details</h5>
            </div>
        </div>
    </div>
</div>

<?php include('../includes/footer.php'); ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const proposalList = document.getElementById('proposalList');
    const proposalContent = document.getElementById('proposalContent');

    proposalList.addEventListener('click', function(event) {
        const target = event.target.closest('a');
        if (!target) return;

        const proposalId = target.getAttribute('data-id');

        fetch(`get_proposal.php?id=${proposalId}`)
            .then(response => response.text())
            .then(data => {
                proposalContent.innerHTML = data;
                const assessButton = document.createElement('button');
                assessButton.classList.add('btn', 'btn-black', 'mt-3');
                assessButton.style.borderRadius = '0';
                assessButton.textContent = proposalContent.querySelector('.badge') ? 'Edit Assessment' : 'Assess';
                assessButton.onclick = () => {
                    window.location.href = `assessment.php?id=${proposalId}`;
                };
                proposalContent.appendChild(assessButton);
            });
    });
});
</script>
