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

// Initialize variables
$action = $_GET['action'] ?? 'list';
$form_id = $_GET['form_id'] ?? '';

// Debug log
$debug_log = __DIR__ . '/debug.log';
file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] manage_evaluation_forms.php executed, action={$action}, form_id={$form_id}\n", FILE_APPEND);

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Unauthorized access\n", FILE_APPEND);
    header('Location: index.php');
    exit;
}

$error = '';
$success = '';
$forms = mysqli_fetch_all(mysqli_query($conn, "SELECT form_id, title, start_date, end_date FROM evaluation_forms"), MYSQLI_ASSOC);

if ($action === 'delete' && $form_id) {
    $query = "SELECT COUNT(*) as count FROM responses_new WHERE form_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'i', $form_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $count = mysqli_fetch_assoc($result)['count'];
    mysqli_stmt_close($stmt);

    if ($count > 0) {
        $error = "Cannot delete form with existing responses.";
    } else {
        $query = "DELETE FROM questions WHERE form_id = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 'i', $form_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);

        $query = "DELETE FROM evaluation_forms WHERE form_id = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 'i', $form_id);
        if (mysqli_stmt_execute($stmt)) {
            $success = "Form deleted successfully.";
            $action = 'list';
        } else {
            $error = "Failed to delete form: " . mysqli_error($conn);
        }
        mysqli_stmt_close($stmt);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($action === 'create' || $action === 'edit')) {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Form submitted: action=$action, form_id=$form_id\n", FILE_APPEND);
    $title = trim($_POST['title'] ?? '');
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $questions = $_POST['questions'] ?? [];
    $question_types = $_POST['question_types'] ?? [];
    $options = $_POST['options'] ?? [];
    $question_ids = $_POST['question_ids'] ?? [];
    $debug_field = $_POST['debug_field'] ?? '';

    if ($debug_field !== 'form_submitted') {
        $error = "Form submission validation failed.";
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Invalid debug_field: $debug_field\n", FILE_APPEND);
    } elseif (empty($title) || empty($start_date) || empty($end_date)) {
        $error = "Title, start date, and end date are required.";
    } elseif (strtotime($end_date) < strtotime($start_date)) {
        $error = "End date must be after start date.";
    } elseif (empty($questions)) {
        $error = "At least one question is required.";
    } else {
        if ($action === 'create') {
            $query = "INSERT INTO evaluation_forms (title, start_date, end_date) VALUES (?, ?, ?)";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'sss', $title, $start_date, $end_date);
            if (mysqli_stmt_execute($stmt)) {
                $form_id = mysqli_insert_id($conn);
            } else {
                $error = "Failed to create form: " . mysqli_error($conn);
            }
            mysqli_stmt_close($stmt);
        } elseif ($action === 'edit' && $form_id) {
            $query = "UPDATE evaluation_forms SET title = ?, start_date = ?, end_date = ? WHERE form_id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'sssi', $title, $start_date, $end_date, $form_id);
            if (!mysqli_stmt_execute($stmt)) {
                $error = "Failed to update form: " . mysqli_error($conn);
            }
            mysqli_stmt_close($stmt);
        }

        if (!$error && $form_id) {
            $existing_question_ids = array_column(mysqli_fetch_all(mysqli_query($conn, "SELECT question_id FROM questions WHERE form_id = $form_id"), MYSQLI_ASSOC), 'question_id');
            $submitted_question_ids = array_filter($question_ids, 'is_numeric');
            $deleted_question_ids = array_diff($existing_question_ids, $submitted_question_ids);

            if (!empty($deleted_question_ids)) {
                $placeholders = implode(',', array_fill(0, count($deleted_question_ids), '?'));
                $query = "DELETE FROM questions WHERE question_id IN ($placeholders)";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, str_repeat('i', count($deleted_question_ids)), ...$deleted_question_ids);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
                file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Deleted questions: " . implode(',', $deleted_question_ids) . "\n", FILE_APPEND);
            }

            $success_count = 0;
            foreach ($questions as $index => $question_text) {
                if (empty(trim($question_text))) continue;
                $question_type = $question_types[$index] ?? 'text';
                $question_options = $question_type === 'single_choice' && isset($options[$index]) ? json_encode(array_filter(array_map('trim', explode(',', $options[$index])))) : '';
                $qid = isset($question_ids[$index]) && is_numeric($question_ids[$index]) ? $question_ids[$index] : null;

                if ($qid) {
                    $query = "UPDATE questions SET question_text = ?, question_type = ?, options = ? WHERE question_id = ? AND form_id = ?";
                    $stmt = mysqli_prepare($conn, $query);
                    mysqli_stmt_bind_param($stmt, 'sssis', $question_text, $question_type, $question_options, $qid, $form_id);
                } else {
                    $query = "INSERT INTO questions (form_id, question_text, question_type, options) VALUES (?, ?, ?, ?)";
                    $stmt = mysqli_prepare($conn, $query);
                    mysqli_stmt_bind_param($stmt, 'isss', $form_id, $question_text, $question_type, $question_options);
                }

                if (mysqli_stmt_execute($stmt)) {
                    $success_count++;
                    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] " . ($qid ? "Updated" : "Inserted") . " question: '$question_text', type=$question_type, options=$question_options\n", FILE_APPEND);
                } else {
                    $error .= "Failed to save question '$question_text': " . mysqli_error($conn) . "<br>";
                }
                mysqli_stmt_close($stmt);
            }

            if ($success_count > 0 && !$error) {
                $success = "Form " . ($action === 'create' ? 'created' : 'updated') . " with $success_count question(s).";
                $action = 'list';
            }
        }
    }
}

if ($action === 'view' || $action === 'edit') {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Entering $action mode: form_id=$form_id\n", FILE_APPEND);
    $query = "SELECT form_id, title, start_date, end_date FROM evaluation_forms WHERE form_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'i', $form_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $form = mysqli_fetch_assoc($result);
    mysqli_stmt_close($stmt);

    $query = "SELECT question_id, question_text, question_type, options FROM questions WHERE form_id = ? ORDER BY question_id";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'i', $form_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $questions = mysqli_fetch_all($result, MYSQLI_ASSOC);
    mysqli_stmt_close($stmt);

    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] $action mode: form_id=$form_id, " . count($questions) . " questions loaded\n", FILE_APPEND);

    if (!$form) {
        $error = "Form not found.";
        $action = 'list';
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Form not found: form_id=$form_id\n", FILE_APPEND);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Evaluation Forms</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css?ver=20250508" rel="stylesheet">
    <link href="../css/register.css?ver=20250508" rel="stylesheet">
    <link href="../css/manage.css?ver=20250508" rel="stylesheet">
    <style>
        .question-block {
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 5px;
        }
        .question-block.existing {
            background-color: #f8f9fa;
        }
    </style>
    <script>
        function addQuestion(questionText = '', questionType = 'text', options = '', questionId = '') {
            const container = document.getElementById('questions-container');
            const index = container.children.length;
            const isExisting = questionId !== '';
            const html = `
                <div class="question-block mb-3 ${isExisting ? 'existing' : ''}">
                    <input type="hidden" name="question_ids[]" value="${questionId}">
                    <div class="form-group">
                        <label>Question ${index + 1} ${isExisting ? '(Existing)' : ''}</label>
                        <input type="text" name="questions[]" class="form-control" value="${questionText.replace(/"/g, '&quot;')}" required>
                    </div>
                    <div class="form-group">
                        <label>Type</label>
                        <select name="question_types[]" class="form-control" onchange="toggleOptions(this, ${index})">
                            <option value="text" ${questionType === 'text' ? 'selected' : ''}>Text</option>
                            <option value="single_choice" ${questionType === 'single_choice' ? 'selected' : ''}>Single Choice</option>
                        </select>
                    </div>
                    <div class="form-group options-field" style="display: ${questionType === 'single_choice' ? 'block' : 'none'};">
                        <label>Options (comma-separated)</label>
                        <input type="text" name="options[]" class="form-control" value="${options.replace(/"/g, '&quot;')}" placeholder="e.g., Yes,No,Maybe">
                    </div>
                    <button type="button" class="btn btn-danger btn-sm mt-2" onclick="removeQuestion(this)">Remove</button>
                </div>`;
            container.insertAdjacentHTML('beforeend', html);
        }

        function toggleOptions(select, index) {
            const optionsField = select.closest('.question-block').querySelector('.options-field');
            optionsField.style.display = select.value === 'single_choice' ? 'block' : 'none';
        }

        function removeQuestion(button) {
            button.closest('.question-block').remove();
        }

        function confirmDelete() {
            return confirm('Are you sure you want to delete this form and its questions?');
        }
    </script>
</head>
<body>
    <div class="container">
        <h2>Manage Evaluation Forms</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; ?>

        <?php if ($action === 'list'): ?>
            <a href="?action=create" class="btn btn-primary mb-3">Create New Form</a>
            <?php if (empty($forms)): ?>
                <p>No evaluation forms found.</p>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Start Date</th>
                            <th>End Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($forms as $f): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($f['title']); ?></td>
                                <td><?php echo htmlspecialchars($f['start_date']); ?></td>
                                <td><?php echo htmlspecialchars($f['end_date']); ?></td>
                                <td>
                                    <a href="?action=view&form_id=<?php echo $f['form_id']; ?>" class="btn btn-info btn-sm">View</a>
                                    <a href="?action=edit&form_id=<?php echo $f['form_id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                                    <a href="?action=delete&form_id=<?php echo $f['form_id']; ?>" class="btn btn-danger btn-sm" onclick="return confirmDelete()">Delete</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

        <?php elseif ($action === 'create' || $action === 'edit'): ?>
            <?php file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Rendering form: action=$action, form_id=$form_id\n", FILE_APPEND); ?>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="?action=list">Manage Forms</a></li>
                    <li class="breadcrumb-item active" aria-current="page"><?php echo $action === 'create' ? 'Create' : 'Edit'; ?> Form</li>
                </ol>
            </nav>
            <h3><?php echo $action === 'create' ? 'Create' : 'Edit'; ?> Evaluation Form</h3>
            <?php if ($action === 'edit'): ?>
                <div class="alert alert-info">
                    Editing Form ID: <?php echo htmlspecialchars($form_id); ?>, 
                    <?php echo count($questions); ?> Question(s) Loaded
                    <?php if (empty($questions)): ?>
                        <br><strong>Note:</strong> No questions found. Add questions below.
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <form method="POST" id="evaluation-form">
                <input type="hidden" name="debug_field" value="form_submitted">
                <div class="form-group mb-3">
                    <label>Title</label>
                    <input type="text" name="title" class="form-control" value="<?php echo isset($form['title']) ? htmlspecialchars($form['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($form['start_date']) ? htmlspecialchars($form['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($form['end_date']) ? htmlspecialchars($form['end_date']) : ''; ?>" required>
                </div>
                <h4>Questions</h4>
                <div id="questions-container">
                    <?php if ($action === 'edit'): ?>
                        <?php if (!empty($questions)): ?>
                            <?php foreach ($questions as $index => $q): ?>
                                <div class="question-block mb-3 existing">
                                    <input type="hidden" name="question_ids[]" value="<?php echo htmlspecialchars($q['question_id']); ?>">
                                    <div class="form-group">
                                        <label>Question <?php echo $index + 1; ?> (Existing, ID: <?php echo htmlspecialchars($q['question_id']); ?>)</label>
                                        <input type="text" name="questions[]" class="form-control" value="<?php echo htmlspecialchars($q['question_text']); ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Type</label>
                                        <select name="question_types[]" class="form-control" onchange="toggleOptions(this, <?php echo $index; ?>)">
                                            <option value="text" <?php echo $q['question_type'] === 'text' ? 'selected' : ''; ?>>Text</option>
                                            <option value="single_choice" <?php echo $q['question_type'] === 'single_choice' ? 'selected' : ''; ?>>Single Choice</option>
                                        </select>
                                    </div>
                                    <div class="form-group options-field" style="display: <?php echo $q['question_type'] === 'single_choice' ? 'block' : 'none'; ?>;">
                                        <label>Options (comma-separated)</label>
                                        <input type="text" name="options[]" class="form-control" value="<?php echo $q['options'] ? htmlspecialchars(implode(',', json_decode($q['options'], true))) : ''; ?>" placeholder="e.g., Yes,No,Maybe">
                                    </div>
                                    <button type="button" class="btn btn-danger btn-sm mt-2" onclick="removeQuestion(this)">Remove</button>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="alert alert-warning">No questions found for this form. Add new questions below.</div>
                        <?php endif; ?>
                    <?php elseif ($action === 'create'): ?>
                        <div class="question-block mb-3">
                            <input type="hidden" name="question_ids[]" value="">
                            <div class="form-group">
                                <label>Question 1</label>
                                <input type="text" name="questions[]" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label>Type</label>
                                <select name="question_types[]" class="form-control" onchange="toggleOptions(this, 0)">
                                    <option value="text">Text</option>
                                    <option value="single_choice">Single Choice</option>
                                </select>
                            </div>
                            <div class="form-group options-field" style="display: none;">
                                <label>Options (comma-separated)</label>
                                <input type="text" name="options[]" class="form-control" placeholder="e.g., Yes,No,Maybe">
                            </div>
                            <button type="button" class="btn btn-danger btn-sm mt-2" onclick="removeQuestion(this)">Remove</button>
                        </div>
                    <?php endif; ?>
                </div>
                <button type="button" class="btn btn-secondary mb-3" onclick="addQuestion()">Add Question</button>
                <button type="submit" class="btn btn-primary mb-3"><?php echo $action === 'create' ? 'Save Form' : 'Update Form'; ?></button>
                <a href="?action=list" class="btn btn-secondary mb-3" style="margin-left: 10px;">Cancel</a>
            </form>

        <?php elseif ($action === 'view' && $form): ?>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="?action=list">Manage Forms</a></li>
                    <li class="breadcrumb-item active" aria-current="page">View Form</li>
                </ol>
            </nav>
            <h3>View Evaluation Form: <?php echo htmlspecialchars($form['title']); ?></h3>
            <p><strong>Start Date:</strong> <?php echo htmlspecialchars($form['start_date']); ?></p>
            <p><strong>End Date:</strong> <?php echo htmlspecialchars($form['end_date']); ?></p>
            <h4>Questions</h4>
            <?php if (empty($questions)): ?>
                <p>No questions found.</p>
            <?php else: ?>
                <ol>
                    <?php foreach ($questions as $q): ?>
                        <li>
                            <?php echo htmlspecialchars($q['question_text']); ?>
                            (Type: <?php echo $q['question_type'] === 'single_choice' ? 'Single Choice' : 'Text'; ?>)
                            <?php if ($q['question_type'] === 'single_choice' && $q['options']): ?>
                                <ul>
                                    <?php foreach (json_decode($q['options'], true) as $option): ?>
                                        <li><?php echo htmlspecialchars($option); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ol>
            <?php endif; ?>
            <a href="?action=edit&form_id=<?php echo $form['form_id']; ?>" class="btn btn-warning">Edit</a>
            <a href="?action=list" class="btn btn-secondary">Back to List</a>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js?ver=20250508"></script>
</body>
</html>