<?php



namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Validation;
use App\Models\CommentModel;
use App\Models\BlogCommentModel;
use App\Models\SubscriberModel;

// use App\Models\CurrentCategoryModel;
use App\Models\CurrentPostModel;
// use App\Models\CommentModel;
// use App\Models\BlogCommentModel;
// use App\Models\HeadlineModel;
// use App\Models\SubHeadlineModel;
// use App\Models\QuizModel;
// use App\Models\UserModel;
// use App\Models\QuestionModel;
// use App\Models\OptionModel;
// use App\Models\SyllabusModel;

// use CodeIgniter\I18n\Time;

use App\Models\BlogPostModel;
// use App\Models\BlogCategoryModel;


// use App\Models\MockHeadingModel;
// use App\Models\MockCategoryModel;
// use App\Models\MockSubCategoryModel;
// use App\Models\MockTopicModel;
// use App\Models\MockQuestionsModel;
// use App\Models\MockTestsModel;


// use App\Models\CurrentAffairQuestionModel;
// use App\Models\CurrentAffairOptionModel;

// use App\Models\CurrentAffairModel;
// use App\Models\NotificationModel;


class BackendController extends BaseController
{

    public function index() //admin dashboard
    {
        $totalsubscribers = 0;
        $subscriberModel = new SubscriberModel();
        $blogPostModel = new BlogPostModel();
        $currentPostModel = new CurrentPostModel();
        // Fetch the total number of subscribers
        $totalsubscribers = $subscriberModel->countAllResults();
        // $latestSubscribers = $subscriberModel->orderBy('created_at', 'DESC')->findAll(5);
        $totalblog = $blogPostModel->countAllResults();
        $totalcurrentpost = $currentPostModel->countAllResults();

        // $data=[totalsubscribers];
        // Combine data to pass to view
        $data = [
            'title' => 'Superadmin Dashboard',
            'totalsubscribers' => $totalsubscribers,
            'totalblog' => $totalblog,
            'totalcurrentpost' => $totalcurrentpost
        ];

        return view('admin/dashboard', $data);
    }

    public function submitTest($mockId)
    {
        $answers = $this->request->getPost('answers');
        $mockQuestionsModel = new MockQuestionsModel();

        $questions = $mockQuestionsModel->where('mock_test_id', $mockId)->findAll();
        $totalQuestions = count($questions);
        $correctAnswers = 0;

        $answerDetails = [];
        foreach ($questions as $index => $question) {
            $correctOptionIndex = $question['correct_option']; // Assuming `correct_option` stores the index
            $isCorrect = isset($answers[$question['id']]) && $answers[$question['id']] == $correctOptionIndex;
            if ($isCorrect) {
                $correctAnswers++;
            }

            $answerDetails[$question['id']] = [
                'index' => $index + 1,
                'correctOption' => $correctOptionIndex,
                'selectedOption' => $answers[$question['id']] ?? null,
                'isCorrect' => $isCorrect,
            ];
        }

        $score = ($correctAnswers / $totalQuestions) * 100;

        return $this->response->setJSON([
            'totalQuestions' => $totalQuestions,
            'correctAnswers' => $correctAnswers,
            'score' => $score,
            'answers' => $answerDetails,
        ]);
    }
    public function store()//comments store
    {
        // Validation rules
        $validationRules = [
            'name' => 'required|min_length[2]|max_length[255]',
            'email' => 'required|min_length[3]|max_length[255]|valid_email',
            'comments' => 'required|min_length[3]|max_length[255]',
        ];

        if (!$this->validate($validationRules)) {
            return redirect()->back()->withInput()->with('usererrors', $this->validator->getErrors());
        }

        // Collect data from the request
        $data = [
            'name' => $this->request->getPost('name'),
            'post_id' => $this->request->getPost('post_id'),
            'email' => $this->request->getPost('email'),
            'comment' => $this->request->getPost('comments'),
            'slugurl' => $this->request->getPost('slugurl') // Capture the slugurl
        ];

        // Create a new instance of the Comment model
        $comment = new CommentModel();

        // Save the data into the database
        if ($comment->save($data)) {
            // Redirect with success message to the page identified by slugurl
            return redirect(route_to('current_post_view', $data['slugurl']))->with('usersuccess', 'Comment posted successfully');
        } else {
            // Redirect back with error message if the save failed
            return redirect()->back()->withInput()->with('usererrors', 'Failed to post comment.');
        }
    }
    public function BlogComments()
    {


        // // Validation rules
        $validationRules = [
            'post_id' => 'required',
            'name' => 'required|min_length[2]|max_length[255]',
            'email' => 'required|min_length[3]|max_length[255]|valid_email',
            'comments' => 'required|min_length[3]|max_length[255]',
        ];

        // // Run validation
        if (!$this->validate($validationRules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }
        // dd($validationRules);
        $data = [
            'name' => $this->request->getPost('name'),
            'post_id' => $this->request->getPost('post_id'),
            'email' => $this->request->getPost('email'),
            'comment' => $this->request->getPost('comments'),
            'created_at' => date('Y-m-d H:i:s'),

        ];
        $comment = new BlogCommentModel();
        // Attempt to save the comment
        if ($comment->save($data)) {
            // On successful comment posting, redirect to the blog post view
            return redirect()->back()->with('usersuccess', 'Comment posted successfully');
        } else {
            // If saving the comment fails, return with a failure message
            return redirect()->back()->withInput()->with('usererrors', 'Failed to post comment.');
        }
    }
    public function NewsLetterStore()
    {
        helper(['form', 'url']);
        $validationRules = [
            'name' => 'required|min_length[2]|max_length[25]',
            'email' => 'required|valid_email|is_unique[subscribers.email]',
        ];

        $model = new SubscriberModel();  // Collect input data from the form
        $data = [
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'created_at' => date('Y-m-d H:i:s'), // Add created timestamp
            'updated_at' => date('Y-m-d H:i:s'), // Add updated timestamp
        ];

        $email = $this->request->getPost('email');
        $username = $this->request->getPost('name');

        if ($this->validate($validationRules)) {
            if ($model->insert($data)) {
                // Send a confirmation email
                $this->sendConfirmationEmail($email, $username);
                return redirect()->back()->with('success', 'Thank you for subscribing!');

            } else {

                return redirect()->back()->with('error', 'Failed to subscribe, please try again.');
            }
        } else {

            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }
    }

    private function sendConfirmationEmail($email, $username)
    {
        // Load the email service
        $emailService = \Config\Services::email();
        $emailService->setTo($email);
        // $emailService->setFrom('info@topf.co.in', 'Examintro.com');
        $emailService->setFrom('newsletter@examintro.com', 'Examintro.com');
        $emailService->setSubject('Thank you for subscribing!');
        $emailService->setMailType('html');  // Ensure the email is sent as HTML
        $emailMessage = "
            <html>
            <head>
                <title>Welcome to Examintro.com!</title>
            </head>
            <body>
                <h1>Hi $username,</h1>
                <p>Thank you for subscribing to our newsletter at <strong><a href='https://examintro.com' target='_blank'>Examintro.com</a></strong>!</p>
                <p>We're thrilled to have you with us. As a subscriber, you will get:</p>
                <ul>
                    <li>Exclusive updates on exam tips and tricks</li>
                    <li>New content on study resources</li>
                    <li>Special offers and discounts for our courses</li>
                </ul>
                <p>Stay tuned, as we bring you the best content to help you succeed in your exams!</p>
                <p>Visit our website: <a href='https://examintro.com' target='_blank'>https://examintro.com</a></p>
    
                <footer>
                    <p>Best regards,</p>
                    <p><strong>The Examintro.com Team</strong></p>
                </footer>
            </body>
            </html>
        ";

        // Set the email message content as HTML
        $emailService->setMessage($emailMessage);

        // Send the email
        if (!$emailService->send()) {
            // Handle email sending failure
            log_message('error', 'Email sending failed: ' . $emailService->printDebugger());
        } else {
            // Optionally, log a success message
            log_message('info', 'Confirmation email sent to ' . $email);
        }
    }

}


// use CodeIgniter\Controller;
// use App\Controllers\BaseController;
// use CodeIgniter\HTTP\ResponseInterface;
// use Config\Validation;


// class BackendController1 extends BaseController
// {

//     // public function dnewsletterstore()
//     // {
//     //     helper(['form', 'url']);
//     //     $validationRules = [
//     //         'name'  => 'required|min_length[2]|max_length[255]',
//     //         'email' => 'required|valid_email|is_unique[subscribers.email]',
//     //     ];

//     //     $model = new SubscriberModel();  // Collect input data from the form
//     //     $data = [
//     //         'name'  => $this->request->getPost('name'),
//     //         'email' => $this->request->getPost('email'),
//     //     ];

//     //     // Ensure email value is available before calling sendConfirmationEmail
//     //     $email = $this->request->getPost('email');

//     //     if ($this->validate($validationRules)) {
//     //         if ($model->insert($data)) {
//     //             // Send a confirmation email
//     //             $this->sendConfirmationEmail($email);
//     //             return redirect()->back()->with('success', 'Thank you for subscribing!');
//     //         } else {
//     //             return redirect()->back()->with('error', 'Failed to subscribe, please try again.');
//     //         }
//     //     } else {
//     //         return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
//     //     }
//     // }

//     // private function sendConfirmationEmail($email)
//     // {
//     //     $emailService = \Config\Services::email();

//     //     $emailService->setTo($email);
//     //     $emailService->setFrom('info@topf.co.in', 'Your Website');
//     //     $emailService->setSubject('Thank you for subscribing!');
//     //     $emailService->setMessage('Thank you for subscribing to our newsletter. Stay tuned for our latest updates!');

//     //     if (!$emailService->send()) {
//     //         // Handle email error
//     //         log_message('error', 'Email sending failed: ' . $emailService->printDebugger());
//     //     }
//     // }

//     public function index() //admin dashboard
//     {

//         return view('admin/dashboard', ['title' => 'Dashboard']);
//     }



// }
