<?php
// Include session check for admin protection
include('session_check.php');

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

// Check if proposal ID and assessor ID are set
if (isset($_POST['proposal_id']) && isset($_POST['assessor_id'])) {
    $proposal_id = intval($_POST['proposal_id']);
    $assessor_id = intval($_POST['assessor_id']);

    // Check if the proposal is already assigned to this assessor
    $check_sql = "SELECT * FROM proposal_assignments WHERE proposal_id = ? AND assessor_id = ?";
    if ($check_stmt = $conn->prepare($check_sql)) {
        $check_stmt->bind_param("ii", $proposal_id, $assessor_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        if ($check_result->num_rows > 0) {
            $_SESSION['message'] = "This proposal is already assigned to the selected assessor.";
            $_SESSION['message_type'] = "danger";
        } else {
            // Insert assignment into the database
            $sql = "INSERT INTO proposal_assignments (proposal_id, assessor_id) VALUES (?, ?)";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("ii", $proposal_id, $assessor_id);
                if ($stmt->execute()) {
                    $_SESSION['message'] = "Proposal assigned successfully!";
                    $_SESSION['message_type'] = "success";
                } else {
                    $_SESSION['message'] = "Error: " . $stmt->error;
                    $_SESSION['message_type'] = "danger";
                }
                $stmt->close();
            } else {
                $_SESSION['message'] = "Database error: Unable to prepare statement.";
                $_SESSION['message_type'] = "danger";
            }
        }
        $check_stmt->close();
    } else {
        $_SESSION['message'] = "Database error: Unable to prepare statement.";
        $_SESSION['message_type'] = "danger";
    }
} else {
    $_SESSION['message'] = "Invalid request.";
    $_SESSION['message_type'] = "danger";
}

$conn->close();
header("Location: view_proposals.php");
exit();
?>
