<?php
session_start();
require '../includes/config.php';

// Restrict to admins
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

// Validate database connection
if (!$conn || mysqli_connect_error()) {
    die('Database connection failed: ' . mysqli_connect_error());
}

// Check evaluation_forms schema
$schema_check = mysqli_query($conn, "DESCRIBE evaluation_forms");
$required_columns = ['form_id', 'title', 'start_date', 'end_date'];
$columns = [];
if ($schema_check) {
    while ($row = mysqli_fetch_assoc($schema_check)) {
        $columns[] = $row['Field'];
    }
}
foreach ($required_columns as $col) {
    if (!in_array($col, $columns)) {
        die("Error: Missing column '$col' in evaluation_forms table. Please update the database schema.");
    }
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $questions = isset($_POST['questions']) ? $_POST['questions'] : [];

    // Validate inputs
    if (empty($title) || empty($start_date) || empty($end_date) || empty($questions)) {
        $error = "All fields are required, including at least one question.";
    } elseif (strtotime($start_date) >= strtotime($end_date)) {
        $error = "End date must be after start date.";
    } else {
        // Insert evaluation form
        $query = "INSERT INTO evaluation_forms (title, start_date, end_date) VALUES (?, ?, ?)";
        $stmt = mysqli_prepare($conn, $query);
        if ($stmt === false) {
            $error = "Failed to prepare query for evaluation_forms: " . mysqli_error($conn);
        } else {
            mysqli_stmt_bind_param($stmt, 'sss', $title, $start_date, $end_date);
            if (mysqli_stmt_execute($stmt)) {
                $form_id = mysqli_insert_id($conn);

                // Insert questions
                $query = "INSERT INTO questions (form_id, question_text, question_type, options) VALUES (?, ?, ?, ?)";
                $stmt = mysqli_prepare($conn, $query);
                $question_success = true;
                if ($stmt === false) {
                    $error = "Failed to prepare query for questions: " . mysqli_error($conn);
                    $question_success = false;
                } else {
                    foreach ($questions as $q) {
                        $text = trim($q['text']);
                        $type = $q['type'];
                        $options = isset($q['options']) && !empty($q['options']) ? trim($q['options']) : null;
                        if (empty($text) || empty($type)) {
                            $error = "Question text or type cannot be empty.";
                            $question_success = false;
                            break;
                        }
                        mysqli_stmt_bind_param($stmt, 'isss', $form_id, $text, $type, $options);
                        if (!mysqli_stmt_execute($stmt)) {
                            $error = "Failed to insert question: " . mysqli_error($conn);
                            $question_success = false;
                            break;
                        }
                    }
                    mysqli_stmt_close($stmt);
                }

                if ($question_success) {
                    $success = "Evaluation form created successfully!";
                } else {
                    $error = $error ?: "Failed to save questions.";
                    mysqli_query($conn, "DELETE FROM evaluation_forms WHERE form_id = $form_id");
                }
            } else {
                $error = "Failed to execute query for evaluation_forms: " . mysqli_error($conn);
                mysqli_stmt_close($stmt);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Create Evaluation Form</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/create.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Create Evaluation Form</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group mb-3">
                <label>Form Title</label>
                <input type="text" name="title" class="form-control" value="<?php echo isset($_POST['title']) ? htmlspecialchars($_POST['title']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Start Date</label>
                <input type="date" name="start_date" class="form-control" value="<?php echo isset($_POST['start_date']) ? htmlspecialchars($_POST['start_date']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>End Date</label>
                <input type="date" name="end_date" class="form-control" value="<?php echo isset($_POST['end_date']) ? htmlspecialchars($_POST['end_date']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Questions</label>
                <div id="questions-container"></div>
                <button type="button" id="add-question-btn" class="btn btn-secondary mt-2">Add Question</button>
                <p id="js-fallback" class="text-danger mt-2" style="display: none;">JavaScript is disabled or failed to load. Please enable JavaScript to add questions.</p>
            </div>
            <button type="submit" class="btn btn-primary">Create Form</button>
            <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
        </form>
    </div>

    <script src="../js/form_create.js"></script>
    <script>
        console.log('Inline script: Running');
        const addQuestionBtn = document.getElementById('add-question-btn');
        if (addQuestionBtn) {
            console.log('Inline script: add-question-btn found');
            addQuestionBtn.addEventListener('click', () => {
                console.log('Inline script: Add Question button clicked');
            });
        } else {
            console.error('Inline script: add-question-btn not found');
            document.getElementById('js-fallback').style.display = 'block';
        }
    </script>
</body>
</html>