<?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'];
$proposal_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($proposal_id == 0) {
    die("Invalid request.");
}

// Fetch proposal details
$sql = "SELECT * FROM proposals WHERE id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $proposal_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows == 1) {
        $proposal = $result->fetch_assoc();
    } else {
        die("Proposal not found.");
    }
    $stmt->close();
} else {
    die("Database error: Unable to prepare statement.");
}

// Fetch existing assessment details if any
$sql = "SELECT * FROM assessments WHERE proposal_id = ? AND assessor_id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("ii", $proposal_id, $assessor_id);
    $stmt->execute();
    $assessment_result = $stmt->get_result();
    $assessment = $assessment_result->fetch_assoc();
    $stmt->close();
} else {
    die("Database error: Unable to prepare statement.");
}

$conn->close();
?>

<?php include('header.php'); ?>
<div class="container mt-5">
    <h2 class="mb-4">Assessment for <?php echo htmlspecialchars($proposal['full_name']); ?></h2>
    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <button type="button" class="btn btn-outline-primary mb-3" data-bs-toggle="modal" data-bs-target="#proposalModal">View Proposal</button>
                    <form method="POST" action="submit_assessment.php" onsubmit="return validateForm()">
                        <input type="hidden" name="proposal_id" value="<?php echo $proposal_id; ?>">
                        <input type="hidden" name="assessor_id" value="<?php echo $assessor_id; ?>">

                        <!-- Form Fields Here, pre-filled with existing assessment data if available -->
                        <div class="accordion" id="assessmentAccordion">
                            <!-- Idea/Innovation Section -->
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="headingIdea">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseIdea" aria-expanded="true" aria-controls="collapseIdea">
                                        Idea/Innovation
                                    </button>
                                </h2>
                                <div id="collapseIdea" class="accordion-collapse collapse show" aria-labelledby="headingIdea" data-bs-parent="#assessmentAccordion">
                                    <div class="accordion-body">
                                        <div class="mb-3">
                                            <label for="idea_novelty" class="form-label">The idea is novel, new and different from what already exist on the market, industry or society (MOS)</label>
                                            <input type="number" class="form-control" id="idea_novelty" name="idea_novelty" value="<?php echo htmlspecialchars($assessment['idea_novelty'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="idea_breakthrough" class="form-label">The idea has a possibility of breakthrough in the market</label>
                                            <input type="number" class="form-control" id="idea_breakthrough" name="idea_breakthrough" value="<?php echo htmlspecialchars($assessment['idea_breakthrough'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="idea_competitors" class="form-label">There are less similar ideas and competitors on the market</label>
                                            <input type="number" class="form-control" id="idea_competitors" name="idea_competitors" value="<?php echo htmlspecialchars($assessment['idea_competitors'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="idea_technology_solution" class="form-label">The idea provides a unique technology solution</label>
                                            <input type="number" class="form-control" id="idea_technology_solution" name="idea_technology_solution" value="<?php echo htmlspecialchars($assessment['idea_technology_solution'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="idea_novel_future" class="form-label">The idea is currently novel and can remain novel in the future</label>
                                            <input type="number" class="form-control" id="idea_novel_future" name="idea_novel_future" value="<?php echo htmlspecialchars($assessment['idea_novel_future'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Market Section -->
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="headingMarket">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseMarket" aria-expanded="false" aria-controls="collapseMarket">
                                        Market and Potential
                                    </button>
                                </h2>
                                <div id="collapseMarket" class="accordion-collapse collapse" aria-labelledby="headingMarket" data-bs-parent="#assessmentAccordion">
                                    <div class="accordion-body">
                                        <div class="mb-3">
                                            <label for="market_need" class="form-label">There is a real need for the idea</label>
                                            <input type="number" class="form-control" id="market_need" name="market_need" value="<?php echo htmlspecialchars($assessment['market_need'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="market_problem" class="form-label">The idea solves a clear problem in the MOI</label>
                                            <input type="number" class="form-control" id="market_problem" name="market_problem" value="<?php echo htmlspecialchars($assessment['market_problem'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="market_present_future" class="form-label">There is enough present and future market to patronize the idea</label>
                                            <input type="number" class="form-control" id="market_present_future" name="market_present_future" value="<?php echo htmlspecialchars($assessment['market_present_future'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="market_share" class="form-label">The idea can obtain significant share of the existing market</label>
                                            <input type="number" class="form-control" id="market_share" name="market_share" value="<?php echo htmlspecialchars($assessment['market_share'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="market_risk" class="form-label">The idea is not risky and the chances of success is high</label>
                                            <input type="number" class="form-control" id="market_risk" name="market_risk" value="<?php echo htmlspecialchars($assessment['market_risk'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="market_timing" class="form-label">The timing right for this idea</label>
                                            <input type="number" class="form-control" id="market_timing" name="market_timing" value="<?php echo htmlspecialchars($assessment['market_timing'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Return Section -->
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="headingReturn">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseReturn" aria-expanded="false" aria-controls="collapseReturn">
                                        Return
                                    </button>
                                </h2>
                                <div id="collapseReturn" class="accordion-collapse collapse" aria-labelledby="headingReturn" data-bs-parent="#assessmentAccordion">
                                    <div class="accordion-body">
                                        <div class="mb-3">
                                            <label for="return_resources" class="form-label">The resource requirement for the idea is reasonable and not difficult to generate</label>
                                            <input type="number" class="form-control" id="return_resources" name="return_resources" value="<?php echo htmlspecialchars($assessment['return_resources'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="return_profit" class="form-label">The idea has the potential of generating significant and stable return (profit)</label>
                                            <input type="number" class="form-control" id="return_profit" name="return_profit" value="<?php echo htmlspecialchars($assessment['return_profit'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="return_investors" class="form-label">The idea has the possibility of attracting potential investors</label>
                                            <input type="number" class="form-control" id="return_investors" name="return_investors" value="<?php echo htmlspecialchars($assessment['return_investors'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                        <label for="return_team_capacity" class="form-label">The entrepreneurial team has the capacity to implement the idea</label>
                                            <input type="number" class="form-control" id="return_team_capacity" name="return_team_capacity" value="<?php echo htmlspecialchars($assessment['return_team_capacity'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Advantage Section -->
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="headingAdvantage">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseAdvantage" aria-expanded="false" aria-controls="collapseAdvantage">
                                        Advantage
                                    </button>
                                </h2>
                                <div id="collapseAdvantage" class="accordion-collapse collapse" aria-labelledby="headingAdvantage" data-bs-parent="#assessmentAccordion">
                                    <div class="accordion-body">
                                        <div class="mb-3">
                                            <label for="advantage_competitors" class="form-label">There are less competitors and similar ideas on the market</label>
                                            <input type="number" class="form-control" id="advantage_competitors" name="advantage_competitors" value="<?php echo htmlspecialchars($assessment['advantage_competitors'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="advantage_better" class="form-label">The idea can do better than what exist on the market</label>
                                            <input type="number" class="form-control" id="advantage_better" name="advantage_better" value="<?php echo htmlspecialchars($assessment['advantage_better'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="advantage_protectable" class="form-label">The idea can be protected by intellectual property regulations</label>
                                            <input type="number" class="form-control" id="advantage_protectable" name="advantage_protectable" value="<?php echo htmlspecialchars($assessment['advantage_protectable'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Social Impact Section -->
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="headingImpact">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseImpact" aria-expanded="false" aria-controls="collapseImpact">
                                        Social Impact
                                    </button>
                                </h2>
                                <div id="collapseImpact" class="accordion-collapse collapse" aria-labelledby="headingImpact" data-bs-parent="#assessmentAccordion">
                                    <div class="accordion-body">
                                        <div class="mb-3">
                                            <label for="impact_sdg" class="form-label">The idea addresses sustainability development goals</label>
                                            <input type="number" class="form-control" id="impact_sdg" name="impact_sdg" value="<?php echo htmlspecialchars($assessment['impact_sdg'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                        <div class="mb-3">
                                            <label for="impact_jobs" class="form-label">The idea has the possibility of generating jobs.</label>
                                            <input type="number" class="form-control" id="impact_jobs" name="impact_jobs" value="<?php echo htmlspecialchars($assessment['impact_jobs'] ?? ''); ?>" min="0" max="5">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-black mt-3" style="border-radius: 0;">Submit Assessment</button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <h5>Scoring Summary</h5>
                    <div id="scoringSummary">
                        <p><strong>Idea/Innovation:</strong> <span id="ideaScore"></span></p>
                        <p><strong>Market and Potential:</strong> <span id="marketScore"></span></p>
                        <p><strong>Return:</strong> <span id="returnScore"></span></p>
                        <p><strong>Advantage:</strong> <span id="advantageScore"></span></p>
                        <p><strong>Social Impact:</strong> <span id="impactScore"></span></p>
                    </div>
                    <div id="totalScore">
                        <strong>Total Score: </strong><span class="badge"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal for viewing full proposal -->
<div class="modal fade" id="proposalModal" tabindex="-1" aria-labelledby="proposalModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="proposalModalLabel">Proposal Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h5>Business Idea Title:</h5>
                <p><?php echo htmlspecialchars($proposal['business_idea_title']); ?></p>
                <h5>Brief Description:</h5>
                <p><?php echo htmlspecialchars($proposal['brief_description']); ?></p>
                <h5>Target Market:</h5>
                <p><?php echo htmlspecialchars($proposal['target_market']); ?></p>
                <h5>Competitors:</h5>
                <p><?php echo htmlspecialchars($proposal['competitors']); ?></p>
                <h5>Market Trends:</h5>
                <p><?php echo htmlspecialchars($proposal['market_trends']); ?></p>
                <h5>Initial Capital:</h5>
                <p><?php echo htmlspecialchars($proposal['initial_capital']); ?></p>
                <h5>Required Resources:</h5>
                <p><?php echo htmlspecialchars($proposal['required_resources']); ?></p>
                <h5>Skills Needed:</h5>
                <p><?php echo htmlspecialchars($proposal['skills_needed']); ?></p>
                <h5>Potential Partnerships:</h5>
                <p><?php echo htmlspecialchars($proposal['potential_partnerships']); ?></p>
                <h5>Social Impact:</h5>
                <p><?php echo htmlspecialchars($proposal['social_impact']); ?></p>
                <h5>Technological Elements:</h5>
                <p><?php echo htmlspecialchars($proposal['technological_elements']); ?></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Update scoring summary
    const updateSummary = () => {
        let totalScore = 0;
        let ideaScore = 0;
        let marketScore = 0;
        let returnScore = 0;
        let advantageScore = 0;
        let impactScore = 0;

        ideaScore += parseInt(document.getElementById('idea_novelty').value || 0);
        ideaScore += parseInt(document.getElementById('idea_breakthrough').value || 0);
        ideaScore += parseInt(document.getElementById('idea_competitors').value || 0);
        ideaScore += parseInt(document.getElementById('idea_technology_solution').value || 0);
        ideaScore += parseInt(document.getElementById('idea_novel_future').value || 0);

        marketScore += parseInt(document.getElementById('market_need').value || 0);
        marketScore += parseInt(document.getElementById('market_problem').value || 0);
        marketScore += parseInt(document.getElementById('market_present_future').value || 0);
        marketScore += parseInt(document.getElementById('market_share').value || 0);
        marketScore += parseInt(document.getElementById('market_risk').value || 0);
        marketScore += parseInt(document.getElementById('market_timing').value || 0);

        returnScore += parseInt(document.getElementById('return_resources').value || 0);
        returnScore += parseInt(document.getElementById('return_profit').value || 0);
        returnScore += parseInt(document.getElementById('return_investors').value || 0);
        returnScore += parseInt(document.getElementById('return_team_capacity').value || 0);

        advantageScore += parseInt(document.getElementById('advantage_competitors').value || 0);
        advantageScore += parseInt(document.getElementById('advantage_better').value || 0);
        advantageScore += parseInt(document.getElementById('advantage_protectable').value || 0);

        impactScore += parseInt(document.getElementById('impact_sdg').value || 0);
        impactScore += parseInt(document.getElementById('impact_jobs').value || 0);

        totalScore = ideaScore + marketScore + returnScore + advantageScore + impactScore;

        document.getElementById('ideaScore').textContent = ideaScore;
        document.getElementById('marketScore').textContent = marketScore;
        document.getElementById('marketScore').textContent = marketScore;
        document.getElementById('returnScore').textContent = returnScore;
        document.getElementById('advantageScore').textContent = advantageScore;
        document.getElementById('impactScore').textContent = impactScore;

        const totalScoreElement = document.getElementById('totalScore').querySelector('span');
        totalScoreElement.textContent = totalScore;

        // Update badge color
        totalScoreElement.classList.remove('bg-success', 'bg-warning', 'bg-danger');
        if (totalScore >= 70) {
            totalScoreElement.classList.add('bg-success');
        } else if (totalScore >= 50) {
            totalScoreElement.classList.add('bg-warning');
        } else {
            totalScoreElement.classList.add('bg-danger');
        }
    };

    const validateForm = () => {
        let isValid = true;
        document.querySelectorAll('input[type="number"]').forEach(input => {
            const value = parseInt(input.value);
            if (value < 0 || value > 5) {
                isValid = false;
                alert('Scores must be between 0 and 5.');
            }
        });
        return isValid;
    };

    document.querySelectorAll('input[type="number"]').forEach(input => {
        input.addEventListener('input', updateSummary);
    });

    updateSummary();
});
</script>
