<?php
session_start();
require_once __DIR__ . "/../config/db.php";

/* =========================================
   PHPMailer
========================================= */
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/../vendor/PHPMailer/src/Exception.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/SMTP.php';

/* =========================================
   1️⃣ Pastikan hanya admin boleh add staff
========================================= */
if (!isset($_SESSION['role']) || $_SESSION['role'] !== "admin") {
    $_SESSION['add_staff_error'] = "Only admin can add staff.";
    header("Location: ../settings.php");
    exit();
}

/* =========================================
   2️⃣ Ambil POST data
========================================= */
$name  = trim($_POST['full_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone_number'] ?? '');
$role  = $_POST['role'] ?? '';
$department_id = $_POST['department_id'] ?? null;

/* =========================================
   3️⃣ Validasi fields
========================================= */
if (
    $name === '' ||
    $email === '' ||
    $role === '' ||
    ($role !== 'admin' && empty($department_id))
) {
    $_SESSION['add_staff_error'] = "All required fields must be filled.";
    header("Location: ../settings.php");
    exit();
}

/* =========================================
   4️⃣ Check duplicate email
========================================= */
$stmtEmail = mysqli_prepare($conn, "SELECT id FROM users WHERE email = ?");
mysqli_stmt_bind_param($stmtEmail, "s", $email);
mysqli_stmt_execute($stmtEmail);
mysqli_stmt_store_result($stmtEmail);

if (mysqli_stmt_num_rows($stmtEmail) > 0) {
    $_SESSION['add_staff_error'] = "This email is already registered.";
    header("Location: ../settings.php");
    exit();
}

/* =========================================
   5️⃣ Check duplicate phone
========================================= */
if (!empty($phone)) {

    $stmtPhone = mysqli_prepare($conn, "SELECT id FROM users WHERE phone_number = ?");
    mysqli_stmt_bind_param($stmtPhone, "s", $phone);
    mysqli_stmt_execute($stmtPhone);
    mysqli_stmt_store_result($stmtPhone);

    if (mysqli_stmt_num_rows($stmtPhone) > 0) {
        $_SESSION['add_staff_error'] = "This phone number is already registered.";
        header("Location: ../settings.php");
        exit();
    }
}

/* =========================================
   6️⃣ Handle profile picture upload
========================================= */
$profile_pic_name = null;
$upload_folder = __DIR__ . "/../assets/profile_pics/";

if (!is_dir($upload_folder)) {
    mkdir($upload_folder, 0777, true);
}

if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] === 0) {

    $file_tmp  = $_FILES['profile_pic']['tmp_name'];
    $file_name = $_FILES['profile_pic']['name'];
    $file_size = $_FILES['profile_pic']['size'];
    $file_ext  = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    $allowed = ["jpg", "jpeg", "png"];

    if (!in_array($file_ext, $allowed)) {

        $_SESSION['add_staff_error'] = "Only JPG/PNG images are allowed.";
        header("Location: ../settings.php");
        exit();
    }

    if ($file_size > 2 * 1024 * 1024) {

        $_SESSION['add_staff_error'] = "Image size must be less than 2MB.";
        header("Location: ../settings.php");
        exit();
    }

    $profile_pic_name = uniqid() . "." . $file_ext;
    $upload_path = $upload_folder . $profile_pic_name;

    if (!move_uploaded_file($file_tmp, $upload_path)) {

        $_SESSION['add_staff_error'] = "Failed to upload image. Check folder permission.";
        header("Location: ../settings.php");
        exit();
    }
}

/* =========================================
   7️⃣ Insert into users table
========================================= */
$default_password = "123456";
$password = password_hash($default_password, PASSWORD_DEFAULT);

$department_id_for_db = ($role === 'admin')
    ? NULL
    : intval($department_id);

$stmt = mysqli_prepare(
    $conn,
    "INSERT INTO users
    (full_name,email,phone_number,password,role,profile_pic,department_id)
    VALUES (?,?,?,?,?,?,?)"
);

mysqli_stmt_bind_param(
    $stmt,
    "ssssssi",
    $name,
    $email,
    $phone,
    $password,
    $role,
    $profile_pic_name,
    $department_id_for_db
);

/* =========================================
   8️⃣ Execute insert
========================================= */
if (!mysqli_stmt_execute($stmt)) {

    $_SESSION['add_staff_error'] =
        "Failed to add staff: " . mysqli_stmt_error($stmt);

    header("Location: ../settings.php");
    exit();
}

/* =========================================
   9️⃣ SEND WELCOME EMAIL
========================================= */
try {

    $mail = new PHPMailer(true);

    /* SMTP SETTINGS */
    $mail->isSMTP();
    $mail->Host       = 'mail.priorisys.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'support@qrcare.priorisys.com';
    $mail->Password   = 'Hifzhan2017';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    /* OPTIONAL FOR XAMPP */
    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer'       => false,
            'verify_peer_name'  => false,
            'allow_self_signed' => true
        ]
    ];

    /* EMAIL DETAILS */
    $mail->setFrom(
        'support@qrcare.priorisys.com',
        'QRCareTrack'
    );

    $mail->addAddress($email, $name);

    $mail->isHTML(true);

    $mail->Subject = 'Welcome to QRCareTrack System';

    $mail->Body = "
    <div style='font-family:Segoe UI,sans-serif;padding:20px;'>

        <h2>Welcome to QRCareTrack System</h2>

        <p>Hello <strong>{$name}</strong>,</p>

        <p>
            Your account has been successfully created by the administrator.
        </p>

        <p>
            Below are your login details:
        </p>

        <table style='border-collapse:collapse;margin-top:10px;'>
            <tr>
                <td style='padding:8px;border:1px solid #ddd;'>
                    <strong>Email</strong>
                </td>
                <td style='padding:8px;border:1px solid #ddd;'>
                    {$email}
                </td>
            </tr>

            <tr>
                <td style='padding:8px;border:1px solid #ddd;'>
                    <strong>Default Password</strong>
                </td>
                <td style='padding:8px;border:1px solid #ddd;'>
                    {$default_password}
                </td>
            </tr>

            <tr>
                <td style='padding:8px;border:1px solid #ddd;'>
                    <strong>Role</strong>
                </td>
                <td style='padding:8px;border:1px solid #ddd;'>
                    " . ucfirst($role) . "
                </td>
            </tr>
        </table>

        <br>

        <p>
            Please log in and change your password after your first login.
        </p>

        <br>

        <p>
            Regards,<br>
            <strong>QRCareTrack System</strong>
        </p>

    </div>
    ";

    $mail->AltBody = "
Welcome to QRCareTrack System

Hello {$name},

Your account has been created successfully.

Login Details:
Email: {$email}
Password: {$default_password}
Role: {$role}

Please change your password after first login.

Regards,
QRCareTrack System
    ";

    $mail->send();

} catch (Exception $e) {

    // Email gagal tapi staff tetap berjaya ditambah
    $_SESSION['add_staff_warning'] =
        "Staff added, but welcome email failed to send.";
}

/* =========================================
   🔟 SUCCESS
========================================= */
$_SESSION['add_staff_success'] =
    "Staff added successfully and welcome email sent.";

header("Location: ../settings.php");
exit();
?>