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

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



// Initialize variables for form data
$title = $name = $area = $contact = $username = $password = '';
$errors = [];
$success = '';

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $_POST['title'];
    $name = $_POST['name'];
    $area = $_POST['area'];
    $contact = $_POST['contact'];
    $username = $_POST['username'];
    $password = $username . $contact; // Default password is username+contact

    // Validate input
    if (empty($title)) $errors[] = "Title is required";
    if (empty($name)) $errors[] = "Name is required";
    if (empty($area)) $errors[] = "Area is required";
    if (empty($contact)) $errors[] = "Contact is required";
    if (empty($username)) $errors[] = "Username is required";

    // Check for duplicates
    $sql = "SELECT * FROM assessors WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $errors[] = "Username already exists.";
    }

    // Check for errors
    if (count($errors) == 0) {
        // Hash the password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Insert assessor into the database
        $sql = "INSERT INTO assessors (title, name, area, contact, username, password) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssss", $title, $name, $area, $contact, $username, $hashed_password);

        if ($stmt->execute()) {
            $success = "Assessor added successfully!";
            header("Location: add_assessor.php?success=" . urlencode($success));
            exit();
        } else {
            $errors[] = "Error adding assessor: " . $conn->error;
        }
    }

    $stmt->close();
}

// Fetch assessors from the database
$sql = "SELECT * FROM assessors";
$result = $conn->query($sql);

$conn->close();
?>

<?php include('../../includes/header.php'); ?>
<div class="container mt-5 d-flex justify-content-center">
    <div class="card" style="width: 50%;">
        <div class="card-body">
            <h1 class="mb-4 text-center">Add Assessor</h1>

            <?php if (!empty($_GET['success'])) : ?>
                <div class="alert alert-success">
                    <p><?php echo htmlspecialchars($_GET['success']); ?></p>
                </div>
            <?php endif; ?>

            <?php if (!empty($errors)) : ?>
                <div class="alert alert-danger">
                    <?php foreach ($errors as $error) : ?>
                        <p><?php echo $error; ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="add_assessor.php">
                <div class="mb-3">
                    <label for="title" class="form-label">Title</label>
                    <select class="form-control" id="title" name="title">
                        <option value="Prof.">Prof.</option>
                        <option value="Dr.">Dr.</option>
                        <option value="Mr.">Mr.</option>
                        <option value="Mrs.">Mrs.</option>
                        <option value="Ms.">Ms.</option>
                        <option value="Miss.">Miss.</option>
                        <option value="Rev.">Rev.</option>
                        <option value="Esq.">Esq.</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="name" class="form-label">Name</label>
                    <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($name); ?>">
                </div>
                <div class="mb-3">
                    <label for="area" class="form-label">Area</label>
                    <input type="text" class="form-control" id="area" name="area" value="<?php echo htmlspecialchars($area); ?>">
                </div>
                <div class="mb-3">
                    <label for="contact" class="form-label">Contact</label>
                    <input type="text" class="form-control" id="contact" name="contact" value="<?php echo htmlspecialchars($contact); ?>">
                </div>
                <div class="mb-3">
                    <label for="username" class="form-label">Username</label>
                    <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>">
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" class="form-control" id="password" name="password" value="<?php echo htmlspecialchars($password); ?>" readonly>
                </div>
                <button type="submit" class="btn btn-black" style="background-color: #2c2b7c; color: #fff; border-radius: 0;">Add Assessor</button>
            </form>
        </div>
    </div>
</div>

<div class="container mt-5 mb-5">
    <h2 class="mb-4">Manage Assessors</h2>
    <table class="table table-striped">
        <thead class="table-dark">
            <tr>
                <th>Title</th>
                <th>Name</th>
                <th>Area</th>
                <th>Contact</th>
                <th>Username</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    echo "<tr>";
                    echo "<td>" . $row['title'] . "</td>";
                    echo "<td>" . $row['name'] . "</td>";
                    echo "<td>" . $row['area'] . "</td>";
                    echo "<td>" . $row['contact'] . "</td>";
                    echo "<td>" . $row['username'] . "</td>";
                    echo '<td>
                        <a href="edit_assessor.php?id=' . $row['id'] . '" class="btn btn-outline-primary me-2">Edit</a>
                        <a href="delete_assessor.php?id=' . $row['id'] . '" class="btn btn-outline-danger">Delete</a>
                    </td>';
                    echo "</tr>";
                }
            } else {
                echo "<tr><td colspan='6'>No assessors found</td></tr>";
            }
            ?>
        </tbody>
    </table>
</div>

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