<?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';

function send_json_error($message) {
    echo json_encode([
        "status" => "error",
        "message" => $message
    ]);
    exit();
}

/* 1️⃣ Pastikan hanya admin boleh add staff */
if (!isset($_SESSION['role']) || $_SESSION['role'] !== "admin") {
    send_json_error("Only admin can add staff.");
}

/* 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))
) {
    send_json_error("All required fields must be filled.");
}

/* 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) {
    send_json_error("This email is already registered.");
}

/* 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) {
        send_json_error("This phone number is already registered.");
    }
}

/* 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)) {
        send_json_error("Only JPG/PNG images are allowed.");
    }

    if ($file_size > 2 * 1024 * 1024) {
        send_json_error("Image size must be less than 2MB.");
    }

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

    if (!move_uploaded_file($file_tmp, $upload_path)) {
        send_json_error("Failed to upload image. Check folder permission.");
    }
}

/* 7️⃣ Insert into users table */
/* Generate random password */
$default_password = substr(str_shuffle(
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'
), 0, 10);

$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)) {
    send_json_error("Failed to add staff: " . mysqli_stmt_error($stmt));
}

/* 9️⃣ SEND WELCOME EMAIL */
$email_failed = false;
try {
    $mail = new PHPMailer(true);
    $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;

    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer'       => false,
            'verify_peer_name'  => false,
            'allow_self_signed' => true
        ]
    ];

    $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\n\nHello {$name},\n\nYour account has been created successfully.\n\nLogin Details:\nEmail: {$email}\nPassword: {$default_password}\nRole: {$role}\n\nPlease change your password after first login.\n\nRegards,\nQRCareTrack System";

    $mail->send();
} catch (Exception $e) {
    $email_failed = true;
}

/* 🔟 SUCCESS RESPONSE */
if ($email_failed) {
    echo json_encode([
        "status" => "success",
        "message" => "Staff added successfully, but welcome email failed to send."
    ]);
} else {
    echo json_encode([
        "status" => "success",
        "message" => "Staff added successfully and welcome email sent."
    ]);
}
exit();
?>