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

/* =========================
   AUTHORIZATION CHECK
========================= */
if (
    !isset($_SESSION['loggedin']) ||
    $_SESSION['loggedin'] !== true ||
    !isset($_SESSION['role']) ||
    $_SESSION['role'] !== 'admin'
) {
    die("
        <script>
            alert('Access denied. Only administrators can add users.');
            window.location.href = '../dashboard.php';
        </script>
    ");
}

/* =========================
   COMPANY CONTEXT CHECK
========================= */
if (!isset($_SESSION['company_id'])) {
    die("
        <script>
            alert('Company context missing. Please re-login.');
            window.location.href = '../sign-in.php';
        </script>
    ");
}

$company_id = (int) $_SESSION['company_id'];


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

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';


/* =========================
   SEND WELCOME EMAIL
========================= */
function sendWelcomeEmail($toEmail, $toName)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtppro.zoho.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'docsupport@docadvisory.com';
        $mail->Password   = 'DegitechSolutions@2025'; // move to env later
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;

        $mail->setFrom('docsupport@docadvisory.com', 'Finvoicer Support');
        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);
        $mail->Subject = 'Welcome to Finvoicer';

        $mail->Body = "<p>Dear <strong>{$toName}</strong>,<br>Your account has been created successfully.</p>";
        $mail->AltBody = "Welcome {$toName}! Your account has been created successfully.";

        $mail->send();
        return true;

    } catch (Exception $e) {
        return false;
    }
}

/* =========================
   ADD USER HANDLER
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $name     = trim($_POST['name'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';
    $role     = $_POST['role'] ?? 'user';

    if ($password !== $confirm) {
        die("<script>alert('Passwords do not match');history.back();</script>");
    }

    /* =========================
       CHECK EMAIL (PER COMPANY)
    ========================= */
    $stmt = $conn->prepare("
        SELECT id 
        FROM users 
        WHERE email = ? AND company_id = ?
    ");
    $stmt->bind_param("si", $email, $company_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        die("<script>alert('Email already exists for this company');history.back();</script>");
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    $emailVerified  = 1;

    /* =========================
       INSERT USER (WITH COMPANY)
    ========================= */
    $stmt = $conn->prepare("
        INSERT INTO users (
            company_id,
            name,
            email,
            password,
            role,
            email_verified
        ) VALUES (?, ?, ?, ?, ?, ?)
    ");

    $stmt->bind_param(
        "issssi",
        $company_id,
        $name,
        $email,
        $hashedPassword,
        $role,
        $emailVerified
    );

    if ($stmt->execute()) {

        sendWelcomeEmail($email, $name);

        echo "<script>
            alert('User added successfully!');
            window.location.href = '../Admin/user-list.php';
        </script>";
        exit;
    }

        echo "
        <script>
            alert('Registration FAILED');
            window.location.href = 'user-add.php';
        </script>
        ";
    exit;
}
?>
