<?php
function generateOTP() {
    return rand(100000, 999999);
}

function generateVerificationRef() {
    return "HBR-" . strtoupper(uniqid());
}

function handleImageUpload($inputName, $uploadDir) {
    if (!isset($_FILES[$inputName]) || $_FILES[$inputName]['error'] !== UPLOAD_ERR_OK) {
        return null; // No file uploaded or error occurred
    }

    $fileTmp  = $_FILES[$inputName]['tmp_name'];
    $fileName = basename($_FILES[$inputName]['name']);
    $ext      = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    // Allowed file types
    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
    if (!in_array($ext, $allowed)) {
        return null; // Invalid file type
    }

    // Create directory if not exists
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $newFileName = uniqid() . '.' . $ext;
    $destination = rtrim($uploadDir, '/') . '/' . $newFileName;

    if (move_uploaded_file($fileTmp, $destination)) {
        return $newFileName;
    }

    return null; // Upload failed
}

function log_audit($conn, $action_type, $table_name = null, $record_id = null, $old_data = null, $new_data = null, $user_id = null, $user_email = null, $ref_id = null, $system_tag = 'Portal') {
    if ($table_name === null) {
        $table_name = 'unspecified';
    }
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN';
    $performed_at = date('Y-m-d H:i:s');

    $stmt = $conn->prepare("INSERT INTO audit_log (user_id, user_email, action_type, table_name, record_id, old_data, new_data, ip_address, user_agent, performed_at, ref_id, system_tag)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $stmt->bind_param( "isssisssssss", $user_id, $user_email, $action_type, $table_name, $record_id, $old_data, $new_data, $ip_address, $user_agent, $performed_at, $ref_id, $system_tag );

    $stmt->execute();
    $stmt->close();
}
function sendOTP($toEmail, $otpCode) {
    $subject = "Your OTP Code";
    $message = "
        <html>
        <head>
            <style>
                body { font-family: Candara, sans-serif; background: #f9f9f9; color: #333; }
                .email-container { padding: 20px; background: #ffffff; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto; }
                .btn { background-color: #0d6efd; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none; display: inline-block; margin-top: 20px; }
            </style>
        </head>
        <body>
            <div class='email-box'>
                <h2>Your One-Time Password (OTP)</h2>
                <p>Your OTP is: <strong style='font-size: 1.5rem;'>$otpCode</strong></p><br><a href='https://verify.sylvianettebox.net/verify-email?vemail=$toEmail' class='btn'>Confirm OTP</a>
                <p>This OTP will expire in 10 minutes.</p>
                <p>— HealthBüro Team</p>
            </div>
        </body>
        </html>
    ";

    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: HealthBüro <no-reply@healthburo.com>\r\n";

    return mail($toEmail, $subject, $message, $headers);
}

function sendPasswordResetEmail($email, $token) {
    $reset_link = "https://healthburo.com/reset-password?token=$token";
    $subject = "Password Reset Request";
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: HealthBüro Team <info@healthburo.com>\r\n";

    $message = "
    <html>
    <head>
      <style>
        body { font-family: Candara, sans-serif; background: #f9f9f9; color: #333; }
        .email-container { padding: 20px; background: #ffffff; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto; }
        .btn { background-color: #0d6efd; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none; display: inline-block; margin-top: 20px; }
      </style>
    </head>
    <body>
      <div class='email-container'>
        <h2>Password Reset Request</h2>
        <p>Hello,</p>
        <p>We received a request to reset your password. Click the button below to proceed:</p>
        <a href='$reset_link' class='btn'>Reset Password</a>
        <p>If you didn't request this, please ignore this message. The link will expire in 10 minutes.</p>
        <p>— HealthBüro Team</p>
      </div>
    </body>
    </html>
    ";

    return mail($email, $subject, $message, $headers);
}

function sendPasswordResetConfirmation($email) {
    $subject = "Your Password Has Been Reset";
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: HealthBüro <no-reply@healthburo.com>\r\n";

    $message = "
    <html><body style='font-family:Candara;'>
      <div style='padding:20px; max-width:600px; background:#fff; border:1px solid #ddd; border-radius:8px;'>
        <h3>Password Reset Successful</h3>
        <p>Hello,</p>
        <p>Your password has been successfully reset on <strong>HealthBüro</strong>.</p>
        <p>If this wasn’t you, please contact our support immediately.</p>
        <p style='margin-top:20px;'>— HealthBüro Team</p>
      </div>
    </body></html>";

    return mail($email, $subject, $message, $headers);
}

function sendVerificationSuccessEmail($email) {
    $subject = "Email Verified Successfully";
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: HealthBüro Team <no-reply@healthburo.com>\r\n";

    $message = "
    <html><body style='font-family:Candara,sans-serif;background:#f4f4f4;padding:20px;'>
      <div style='max-width:600px;margin:auto;background:white;border-radius:8px;padding:20px;'>
        <h3 style='color:green;'>Email Verification Complete</h3>
        <p>Hello,</p>
        <p>Your email <strong>$email</strong> has been successfully verified. You can now access all features of your account.</p>
        <p style='margin-top:20px;'>— HealthBüro</p>
      </div>
    </body></html>";

    return mail($email, $subject, $message, $headers);
}