summaryrefslogtreecommitdiff
path: root/includes/pages/user_questions.php
blob: 7654d540ac38e700ba8289bdcb7e404ea8ed462b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

use Engelsystem\Models\Question;

/**
 * @return string
 */
function questions_title()
{
    return __('Ask the Heaven');
}

/**
 * @return string
 */
function user_questions()
{
    $user = auth()->user();
    $request = request();

    if (!$request->has('action')) {
        $open_questions = $user->questionsAsked()->whereNull('answerer_id')->get();
        $answered_questions = $user->questionsAsked()->whereNotNull('answerer_id')->get();

        return Questions_view(
            $open_questions->all(),
            $answered_questions->all(),
            page_link_to('user_questions', ['action' => 'ask'])
        );
    } else {
        switch ($request->input('action')) {
            case 'ask':
                $question = request()->get('question');
                if (!empty($question) && $request->hasPostData('submit')) {
                    Question::create([
                        'user_id' => $user->id,
                        'text' => $question,
                    ]);

                    success(__('You question was saved.'));
                    throw_redirect(page_link_to('user_questions'));
                } else {
                    return page_with_title(questions_title(), [
                        error(__('Please enter a question!'), true)
                    ]);
                }
                break;
            case 'delete':
                if (
                    $request->has('id')
                    && preg_match('/^\d{1,11}$/', $request->input('id'))
                    && $request->hasPostData('submit')
                ) {
                    $question_id = $request->input('id');
                } else {
                    return error(__('Incomplete call, missing Question ID.'), true);
                }

                $question = Question::find($question_id);
                if (!empty($question) && $question->user_id == $user->id) {
                    $question->delete();
                    throw_redirect(page_link_to('user_questions'));
                } else {
                    return page_with_title(questions_title(), [
                        error(__('No question found.'), true)
                    ]);
                }
                break;
        }
    }

    return '';
}