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

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

// Initialize search term
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Fetch proposals from the database
$sql = "SELECT proposals.*, COUNT(proposal_assignments.id) as num_assignments
        FROM proposals
        LEFT JOIN proposal_assignments ON proposals.id = proposal_assignments.proposal_id
        WHERE full_name LIKE '%$search%' OR 
              business_idea_title LIKE '%$search%' OR 
              brief_description LIKE '%$search%'
        GROUP BY proposals.id";
$result = $conn->query($sql);

// Fetch assessors from the database
$assessors_sql = "SELECT * FROM assessors";
$assessors_result = $conn->query($assessors_sql);
?>

<?php include('../../includes/header.php'); ?>
<div class="container mt-5">
    <h1 class="mb-4">Proposals</h1>

    <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-<?php echo $_SESSION['message_type']; ?> alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['message']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['message']); unset($_SESSION['message_type']); ?>
    <?php endif; ?>

    <!-- Search Form -->
    <form method="GET" action="" class="mb-4">
        <div class="input-group" style="max-width: 400px;">
            <input type="text" class="form-control" name="search" placeholder="Search proposals..." value="<?php echo htmlspecialchars($search); ?>">
            <button class="btn btn-outline-primary" type="submit"><i class="fas fa-search"></i></button>
        </div>
    </form>

    <table class="table table-striped">
        <thead class="table-dark">
            <tr>
                <th>Name</th>
                <th>Business Idea Title</th>
                <th>Brief Description</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            if ($result->num_rows > 0) {
                // Output data of each row
                while($row = $result->fetch_assoc()) {
                    $assignedClass = $row["num_assignments"] > 0 ? 'btn-primary' : 'btn-outline-secondary';
                    echo "<tr>";
                    echo "<td>" . $row["full_name"] . "</td>";
                    echo "<td>" . $row["business_idea_title"] . "</td>";
                    echo "<td>" . $row["brief_description"] . "</td>";
                    echo '<td>
                        <div class="d-flex justify-content-between">
                            <a href="#" class="btn btn-outline-primary me-2" data-bs-toggle="modal" data-bs-target="#viewProposalModal" data-id="' . $row["id"] . '">View</a>
                            <button class="btn ' . $assignedClass . ' me-2" style="min-width: 120px;" data-bs-toggle="modal" data-bs-target="#assignModal" data-id="' . $row["id"] . '">
                                Assign <sup>' . $row["num_assignments"] . '</sup>
                            </button>
                        </div>
                    </td>';
                    echo "</tr>";
                }
            } else {
                echo "<tr><td colspan='4'>No proposals found</td></tr>";
            }
            ?>
        </tbody>
    </table>
</div>

<!-- View Proposal Modal -->
<div class="modal fade" id="viewProposalModal" tabindex="-1" aria-labelledby="viewProposalModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewProposalModalLabel">Proposal Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="modal-body-content">
                <!-- Proposal details will be loaded here with JavaScript -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Assign Modal -->
<div class="modal fade" id="assignModal" tabindex="-1" aria-labelledby="assignModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="assignModalLabel">Assign Proposal</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="assignForm" method="POST" action="assign.php">
                    <input type="hidden" name="proposal_id" id="proposalId">
                    <div class="mb-3">
                        <label for="assessor_id" class="form-label">Select Assessor</label>
                        <select class="form-control" id="assessor_id" name="assessor_id">
                            <?php
                            if ($assessors_result->num_rows > 0) {
                                while($assessor = $assessors_result->fetch_assoc()) {
                                    echo '<option value="' . $assessor["id"] . '">' . $assessor["title"] . ' ' . $assessor["name"] . '</option>';
                                }
                            } else {
                                echo '<option value="">No assessors found</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">Assign</button>
                </form>
            </div>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    const viewModal = document.getElementById('viewProposalModal');
    const modalBody = document.getElementById('modal-body-content');

    viewModal.addEventListener('show.bs.modal', function(event) {
        const button = event.relatedTarget;
        const proposalId = button.getAttribute('data-id');

        fetch('get_proposal.php?id=' + proposalId)
            .then(response => response.text())
            .then(data => {
                modalBody.innerHTML = data;
            });
    });

    const assignModal = document.getElementById('assignModal');
    const proposalIdInput = document.getElementById('proposalId');

    assignModal.addEventListener('show.bs.modal', function(event) {
        const button = event.relatedTarget;
        const proposalId = button.getAttribute('data-id');
        proposalIdInput.value = proposalId;
    });

    // Auto-close alert after 3 seconds
    const alert = document.querySelector('.alert');
    if (alert) {
        setTimeout(() => {
            alert.classList.add('fade');
            setTimeout(() => {
                alert.classList.remove('show');
            }, 150);
        }, 3000);
    }
});
</script>
