<?php
session_start();
date_default_timezone_set('Africa/Blantyre');

include_once 'model/users_model.php';
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Instantiate the users model
$users_model = new users_model();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve form data
    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $userrole = $_POST['userrole'];
    $user_state = $_POST['user_state'];
    $created_at = date('Y-m-d H:i:s');
    $created_by = $_SESSION['user_id'];

    // Step 1: Check if the email already exists in the database
    $existingUser = $users_model->getUserByEmail($email);

    if ($existingUser) {
        // If email exists, notify the user and stop the process
        $_SESSION['notification'] = [
            'type' => 'error',
            'message' => "The email address is already registered. Please use a different email.",
            'title' => 'Email Already Registered'
        ];
        header('Location: system_users.php');
        exit();
    }

    // Step 2: Generate a random password for the user
    $password = bin2hex(random_bytes(4)); // Generates a random 8-character password

    // Step 3: Add the new user to the database
    $result = $users_model->addSystemUser($fullname, $email, $password, $created_at, $userrole, $created_by, $user_state);

    if ($result) {
        // Step 4: If user added successfully, send the email with login details
        $mail = new PHPMailer(true);  // Passing `true` enables exceptions

        try {
            // Configure PHPMailer
            $mail->isSMTP();
            $mail->Host       = 'llgolf.smartplus-mw.com';  // SMTP server
            $mail->SMTPAuth   = true;
            $mail->Username   = 'info@hrdcmalawi.org';  // SMTP username
            $mail->Password   = 'hrdc#2025Info@@';       // SMTP password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SMTP encryption
            $mail->Port       = 465;  // SMTP port

            // Sender and recipient info
            $mail->setFrom('info@hrdcmalawi.org', 'HRDC MALAWI');
            $mail->addAddress($email, $fullname); // Send email to the new user

            // Email content
            $mail->isHTML(true); 
            $mail->Subject = 'HRDC SYSTEM USER ACCOUNT';
            $mail->Body = "<p>Dear $fullname,</p>";
            $mail->Body .= "<p>Find your login details for HRDC admin panel below:</p>";
            $mail->Body .= "<p><strong>Username/Email:</strong> $email</p>";
            $mail->Body .= "<p><strong>Password:</strong> $password</p>";

            // Attempt to send the email
            $mail->send();

            // Step 5: Set success notification and redirect
            $_SESSION['notification'] = [
                'type' => 'success',
                'message' => "User added successfully.<br> An email has been sent to the user with their login details.",
                'title' => 'Success'
            ];
            header('Location: system_users.php');
            exit();

        } catch (Exception $e) {
            // If email sending fails, notify the user but still save the new user
            $_SESSION['notification'] = [
                'type' => 'error',
                'title' => 'Email Not Sent',
                'message' => 'User added, but failed to send email. Mailer Error: ' . $mail->ErrorInfo
            ];
            header('Location: system_users.php');
            exit();
        }

    } else {
        // If adding the user to the database fails
        $_SESSION['notification'] = [
            'type' => 'error',
            'message' => "Failed to add user. Please try again.",
            'title' => 'Failed to Add User'
        ];
        header('Location: system_users.php');
        exit();
    }
}
