<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Controllers\View\EmailController;
use App\Models\SupportRequestModel;
use App\Models\UserModel;

class SupportController extends BaseController
{
    public function __construct()
    {
        helper(['form']);
    }

    public function index()
    {
        return view('/support');
    }


    public function submit()
    {
        // Retrieve user_id from session
        $session = session();
        $user_id = $session->get('user_id');

        // If no user_id is found in the session, redirect with an error
        if (!$user_id) {
            return redirect()->back()->with('error', 'You must be logged in to submit a support request.');
        }

        // Load the UserModel to retrieve user information
        $userModel = new UserModel();
        $user = $userModel->find($user_id);

        // If the user does not exist, redirect with an error
        if (!$user) {
            return redirect()->back()->with('error', 'User not found. Please contact support.');
        }

        // Retrieve form data
        $subject = $this->request->getPost('subject');
        $message = $this->request->getPost('message');

        // Get the user's full name using firstname and lastname
        $full_name = $user['firstname'] . ' ' . $user['lastname'];

        // Call the function to send an email using SMTP (configured via Email.php or .env)
        $sendStatus = $this->sendSupportEmail($user['email'], $full_name, $subject, $message);

        if ($sendStatus === true) {
            return redirect()->back()->with('success', 'Your support request has been submitted successfully.');
        } else {
            // If email fails, log the error and display a message
            log_message('error', $sendStatus);
            return redirect()->back()->with('error', 'Failed to send your support request. Please try again later.');
        }
    }

    /**
     * Function to send an email via SMTP from user to support@domain.org
     *
     * @param string $user_email - The email address of the user sending the request.
     * @param string $user_name - The name of the user sending the request.
     * @param string $subject - The subject of the support request.
     * @param string $message - The body of the support request.
     * @return bool|string - Returns true if email sent successfully, otherwise error message.
     */
    public function sendSupportEmail($user_email, $full_name, $subject, $message)
    {
        $mailer = new EmailController();
        $ok = $mailer->sendEmail(
            'support@alrahmaisgl.org',
            $subject,
            nl2br($message),
            null,
            $user_email,
            $full_name
        );

        return $ok === true ? true : 'Failed to send support email.';
    }



    public function requests()
    {
        $supportModel = new SupportRequestModel();
        $userId = session()->get('user_id');
        $data['requests'] = $supportModel->where('user_id', $userId)->findAll();

        return view('/support_requests', $data);
    }

    public function supportTeacher()
    {
        return view('/teacher/teacher_support');
    }
}


/*
    public function submit()
    {
        $validation = \Config\Services::validation();

        // Define validation rules
        $validation->setRules([
            'subject' => 'required|min_length[3]',
            'message' => 'required|min_length[10]',
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return view('/support', [
                'validation' => $validation
            ]);
        }

        $supportModel = new SupportRequestModel();
        $supportModel->save([
            'user_id' => session()->get('user_id'),
            'subject' => $this->request->getPost('subject'),
            'message' => $this->request->getPost('message'),
            'status' => 'open'
        ]);

        session()->setFlashdata('success', 'Your support request has been submitted.');

        return redirect()->to('/support');
    }
*/
